Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_from_epsg_neg():
try:
crs.from_epsg(-1)
except ValueError:
pass
except:
raise
def test_forward(self):
with mock.patch('geopy.geocoders.googlev3.GoogleV3.geocode',
ForwardMock()) as m:
g = geocode(self.locations, provider='googlev3', timeout=2)
self.assertEqual(len(self.locations), m.call_count)
n = len(self.locations)
self.assertIsInstance(g, gpd.GeoDataFrame)
expected = GeoSeries([Point(float(x)+0.5, float(x)) for x in range(n)],
crs=from_epsg(4326))
assert_geoseries_equal(expected, g['geometry'])
tm.assert_series_equal(g['address'],
pd.Series(self.locations, name='address'))
def transform_data(self, outformat=None, epsg=None):
"""
Transform the IO data into the requested format and projection if
necessary.
:param outformat: Output format
:param epsg:
:return:
"""
out_data = geopandas.GeoDataFrame.copy(self.data)
if epsg and str(self.get_epsg()) != epsg:
out_data[out_data.geometry.name] = \
self.data.geometry.to_crs(epsg=epsg)
out_data.crs = fiona.crs.from_epsg(epsg)
if outformat == formats.JSON and self.default_output in (
formats.PANDAS, formats.JSON):
out_json = out_data.to_json()
if out_data.crs:
gj = json.loads(out_json)
gj["crs"] = {
"type": "name",
"properties": {
"name": out_data.crs["init"].upper()
}
}
return json.dumps(gj)
else:
return out_json
elif outformat in [formats.PANDAS, None]:
return out_data
d.close()
profile.pop('tiled', None)
profile.update(
height=new_data.shape[1],
width=new_data.shape[2],
transform=transform,
driver='GTiff'
)
with rasterio.open(file_path, 'w', **profile) as output:
output.write(new_data.astype(profile['dtype']))
bbox = self.bbox
if bbox is not None:
bbox = box(*bbox)
geo = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=from_epsg(4326))
geo = geo.to_crs(crs=profile['crs'])
bbox = geo.geometry
with rasterio.open(file_path, 'r') as merged:
new_data, transform = rasterio.mask.mask(dataset=merged, shapes=bbox, all_touched=True, crop=True)
# profile.pop('tiled', None)
profile.update(
height=new_data.shape[1],
width=new_data.shape[2],
transform=transform,
)
with rasterio.open(file_path, 'w', **profile) as clipped:
clipped.write(new_data)
with rasterio.open(file_path) as f:
def main():
#Calculate zonal statistics.
z_stats = zonal_stats(zones_in,vrt, stats=statistics)
#Add the results to original shape file and save as new shape file
results = gpd.read_file(zones_in)
for index, row in results.iterrows():
for stat in statistics:
results.loc[index, stat] = z_stats[index][stat]
results.crs=from_epsg(3067)
results.to_file(zones_out)
EPSG code specifying output projection.
"""
from fiona.crs import from_epsg
if crs is None and epsg is None:
raise TypeError("Must set either crs or epsg for output.")
if self.crs is None:
raise ValueError(
"Cannot transform naive geometries. "
"Please set a crs on the object first."
)
if crs is None:
try:
crs = from_epsg(epsg)
except (TypeError, ValueError):
raise ValueError("Invalid epsg: {}".format(epsg))
# skip transformation if the input CRS and output CRS are the exact same
if _PYPROJ_VERSION >= LooseVersion("2.1.2") and pyproj.CRS.from_user_input(
self.crs
).is_exact_same(pyproj.CRS.from_user_input(crs)):
return self
if _PYPROJ_VERSION >= LooseVersion("2.2.0"):
# if availale, use always_xy=True to preserve GIS axis order
transformer = pyproj.Transformer.from_crs(self.crs, crs, always_xy=True)
project = transformer.transform
elif _PYPROJ_VERSION >= LooseVersion("2.1.0"):
# use transformer for repeated transformations
transformer = pyproj.Transformer.from_crs(self.crs, crs)
def pixc_to_shp(input_name, output_name, lat_name, lon_name, var_names, group_name=None, progress=False):
pixc = nc.Dataset(input_name, "r")
if group_name is None:
latitude = pixc.variables[lat_name][:]
longitude = pixc.variables[lon_name][:]
variables = [pixc.variables[var_name][:] for var_name in var_names]
else:
latitude = pixc.groups[group_name].variables[lat_name][:]
longitude = pixc.groups[group_name].variables[lon_name][:]
variables = [pixc.groups[group_name].variables[var_name][:] for var_name in var_names]
nb_points = latitude.size
driver = "ESRI Shapefile"
crs = fiona.crs.from_epsg(4326) # WGS84
schema = {'properties': OrderedDict([(lon_name, 'float:24.15'), (lat_name, 'float:24.15')] + [(var_name, 'float:24.15') for var_name in var_names]), 'geometry': 'Point'}
sys.stdout.write("Writting shp points")
with fiona.open(output_name,'w', driver=driver, crs=crs, schema=schema) as c:
for i in range(nb_points):
point = geometry.Point(longitude[i], latitude[i])
prop = {lon_name: float(point.coords.xy[0][0]),
lat_name: float(point.coords.xy[1][0])}
for var_name, var_values in zip(var_names, variables):
prop[var_name] = float(var_values[i])
c.write({'geometry': geometry.mapping(point), 'properties': prop})
points = []
point_out_file = os.path.join(output_dir, "." +
filebase + '.shp')
# Set up the shapefile schema.
point_schema = {'geometry': 'Point',
'properties': {'line': 'str',
'segyfile': 'str',
'trace': 'int'
}
}
with fiona.open(point_out_file, "w",
driver="ESRI Shapefile",
crs=crs.from_epsg(26920),
schema=point_schema) as trace_out:
for i, trace in enumerate(segy):
header = trace.stats.segy.trace_header
scalar = header.scalar_to_be_applied_to_all_coordinates
if scalar == -100:
gain = 0.01
elif scalar == -10:
gain = 0.1
else:
gain = 1.0
x = float(header.source_coordinate_x) * gain
y = float(header.source_coordinate_y) * gain