PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label spatial. Show all posts
Showing posts with label spatial. Show all posts

Saturday, October 8, 2022

[FIXED] Why can I not get worldclim data (avg temp and prec) for the state which I live at all using R?

 October 08, 2022     r, spatial, stack, statistics     No comments   

Issue

I'd like to get the average temperature and precipitation for the state of Ceara in Brazil; I made a cropped area on the map as:

enter image description here

and I used the center lat/lon as lat=-5.49839 and lon=-39.32062 I got the caps of latitude and longitude as latinicial=-7.24614 (minimum latitude), latfinal=-3.76140 (maximum latitude), longinicial=-40.38084 (minimum longitude) and longfinal=-38.77385 (maximum longitude) then I've simulated a uniformly distributed temperature for both latitude and longitude which lies in their maxima and minima.

My code is given as follows:

library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(dismo)
library(rgdal)
library(sf)
d=getData('worldclim',lat=-5.49839,lon=-39.32062,res=0.5,var='bio')
latinicial=-7.24614
latfinal=-3.76140
longinicial=-40.38084
longfinal=-38.77385
latitude=runif(100,latinicial,latfinal)
longitude=runif(100,longinicial,longfinal)
coord=data.frame(latitude,longitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1,12)]]
names(d)=c("Temp","Prec")
extract(d,points)

But when I run it, I got NA values for all rows even though I'm showing you only 4 rows:

enter image description here

So, I'd like to know what happened to it. Why do I get NA values?


Solution

The problem is with the order of longitude and latitude in coords. When you put coords into SpatialPoints, it expects the order to be longitude then latitude, but you have it reversed. Once you fix that, then it will extract the data correctly. All the code above coord works fine. Also, if you are going to run this code multiple times, then I would recommend using set.seed. This will allow you to get the same values every time when you run the runif statements.

library(raster)
library(sp)

set.seed(243)
d = getData(
  'worldclim',
  lat = -5.49839,
  lon = -39.32062,
  res = 0.5,
  var = 'bio'
)
latinicial = -7.24614
latfinal = -3.76140
longinicial = -40.38084
longfinal = -38.77385
latitude = runif(100, latinicial, latfinal)
longitude = runif(100, longinicial, longfinal)
coord = data.frame(longitude, latitude)
points = SpatialPoints(coord, proj4string = d@crs)
d <- d[[c(1, 12)]]
names(d) = c("Temp", "Prec")
extract(d, coord)

Output

head()

       Temp Prec
  [1,]  239  655
  [2,]  267  832
  [3,]  256  541
  [4,]  269  740
  [5,]  242  784
  [6,]  233  981


Answered By - AndrewGB
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] How to find the maximum distance between any pair of GPS points?

 September 26, 2022     geospatial, gps, r, spatial     No comments   

Issue

I am trying to determine the maximum distance between any two pairs of GPS points in a data frame containing 1000's of GPS points. I am not sure what I have done thus far is correct. How can I accomplish this? Thanks

structure(list(Id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L), .Label = "A628", class = "factor"), DateTime = structure(c(1557401400, 
1557403200, 1557405000, 1557406800, 1557408600, 1557410400, 1557417600, 
1557419400, 1557421200, 1557423000), class = c("POSIXct", "POSIXt"
), tzone = "CST6CDT"), Longitude = c(-97.4468676, -97.4760327, 
-97.4766244, -97.4768354, -97.4766027, -97.4762566, -97.4756206, 
-97.4760795, -97.4757018, -97.4758084), Latitude = c(26.5649515, 
26.5864111, 26.5874319, 26.5874866, 26.5874287, 26.5878552, 26.5881477, 
26.588534, 26.5879895, 26.5876414)), row.names = c(NA, 10L), class = "data.frame")
library(sp)
library(adehabitatHR)
library(raster)
library(rgdal)
library(sf)

collars <- read.csv('C:\\Users\\kujld016\\Desktop\\All\\Projects\\Thermal_Deer\\all_data\\collars_clean.csv')

collars <- collars %>%
  mutate_if(is.character, as.factor) %>%
  mutate(DateTime=as.POSIXct(DateTime, format="%Y-%m-%d %H:%M:%S",tz='CST6CDT'))

for(j in 1:length(collars)) {
  collarIDs <- unique(collars$Id)
  
  for(i in 1:length(collarIDs)) { 
    collarID <- collarIDs[i]
    collar <- filter(collars, Id == collarID)
    
    #coerce to spatialpointsdataframe and reproject
    dat.sp<-SpatialPointsDataFrame(coords=collar[c('Longitude', 'Latitude')],data=collar,
                                   proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
    
    dat.proj <- spTransform(dat.sp, CRS("+proj=utm +zone=14 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"))

aref <- (max(spDists(dat.proj))) ###is this calculating the maximum distance between any 2 points in the data frame

Solution

Easier with the sf package, rather than sp:

library(sf)
library(dplyr)

# the_data <- from posted sample data in question
# make data.frame an sf object with lat/lon projection
data_sf <- st_as_sf(the_data, coords = c("Longitude", "Latitude")) %>%
  st_set_crs(4326)

# distance matrix for all the points
dist_mat <- st_distance(data_sf)

# where's the longest distance?
which(dist_mat == max(dist_mat), arr.ind = TRUE)
#>      row col
#> [1,]   8   1
#> [2,]   1   8

dist_mat[8,1]
#> 3913.472 [m]

Created on 2022-04-08 by the reprex package (v2.0.1)



Answered By - mrhellmann
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 9, 2022

[FIXED] CakePHP 3.5 Always apply asText() MySQL function to Spatial field

 January 09, 2022     cakephp, cakephp-3.0, mysql, php, spatial     No comments   

Issue

I have a custom PolygonType which represents a POLYGON() field in a MySQL table.

class PolygonType extends BaseType implements ExpressionTypeInterface
{
    public function toPHP($value, Driver $d)
    {
        // $value is binary, requires unpack()
    }
}

I can use $query->func()->astext() on every find, but I would like to know if it's possible to always apply MySQL's AsText() function when selecting this field instead (similar to how toExpression() can be used when inserting data).


Solution

Based on ndp's answer, it's possible to inspect the field types via $query->getDefaultTypes() and apply a SQL function as required. However, $value is empty if no fields are initially stated (e.g. when using Table::get() so there's also a check for this.

public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
    $query->traverse(
        function (&$value) use ($query) {

            if (is_array($value) && empty($value)) {
                $query->all();
            }

            $defaultTypes = $query->getDefaultTypes();

            foreach ($value as $key => $field) {
                if (in_array($defaultTypes[$field], ['point', 'polygon'])) {
                    $value[$key] = $query->func()->astext([
                        $this->aliasField($field) => 'identifier'
                    ]);
                }
            }

            $query->select($value);
        },
        ['select']
    );
}


Answered By - robmcvey
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing