Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def comptiles(filedir, comparedir, sampling, filetype):
# plotdir = '/Users/dnomadb/Documents/pcomp'
files = os.listdir(filedir)
cfiles = os.listdir(comparedir)
if plotdir:
import matplotlib.pyplot as plot
for f in files:
fileinfo = f.split('-')
if len(fileinfo[-1].split('.')) != 0 and fileinfo[-1].split('.')[-1] == filetype:
x, y, z = tiledelta.getXYZ(fileinfo)
bbox = mercantile.bounds(x, y, z)
with rio.drivers():
with rio.open(os.path.join(filedir, f), 'r') as src:
greyimage_before = (src.read(1).astype(np.uint16) + src.read(2).astype(np.uint16) + src.read(3).astype(np.uint16))
with rio.open(os.path.join(comparedir, f), 'r') as src:
greyimage_after = (src.read(1).astype(np.uint16) + src.read(2).astype(np.uint16) + src.read(3).astype(np.uint16))
pcplo = tiledelta.compareGreys(greyimage_after, greyimage_before, 10, 20)
pcplo = pcplo[::sampling,::sampling]
if plotdir:
fig = plot.figure(figsize=(20,10))
before = fig.add_subplot(131)
before.imshow(greyimage_after,cmap='Greys_r')
after = fig.add_subplot(132)
after.imshow(greyimage_before, cmap='Greys_r')
pc2 = fig.add_subplot(133)
def request_ee_task(x, y, year, dry_run=False):
# Get the region bounds to build a polygon.
bounds = mercantile.bounds(x, y, config.region_zoom_level)
north = bounds.north
east = bounds.east + 0.1
south = bounds.south - 0.1
west = bounds.west
# Start the task asynchronously to export to Google Cloud Storage.
region_id = f"{x}-{y}-{year}"
output_path_prefix = f"regions/{x}/{y}/{year}/"
output_path = f"gs://{config.BUCKET}/{output_path_prefix}"
task = ee.batch.Export.image.toCloudStorage(
image=landsat_image.get(year),
description=region_id,
bucket=config.BUCKET,
fileNamePrefix=output_path_prefix,
region=[
[east, north],
def serve(self):
bounds = mercantile.bounds(self.x, self.y, self.zoom)
self.west, self.south = mercantile.xy(bounds.west, bounds.south)
self.east, self.north = mercantile.xy(bounds.east, bounds.north)
self.layers = []
if self.namespace not in RECIPES:
msg = 'Recipe "{}" not found. Available recipes are: {}'
abort(400, msg.format(self.namespace, list(RECIPES.keys())))
self.recipe = RECIPES[self.namespace]
names = self.recipe.layers.keys() if self.ALL else self.names
for name in names:
if name not in self.recipe.layers:
abort(400, u'Layer "{}" not found in recipe {}'.format(
name, self.namespace))
self.process_layer(self.recipe.layers[name])
self.post_process()
return self.content, 200, {"Content-Type": self.CONTENT_TYPE}
def get_geojson(self):
"""Return geojson of the bounding tile."""
w, s, e, n = list(mercantile.bounds(*self.bounding_tile))
return {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[w, s],
[e, s],
[e, n],
[w, n],
[w, s]
]
import mercantile
if not hasattr(input_gdf, 'geometry'):
raise ValueError('This dataframe has no valid geometry.')
geometry_name = input_gdf.geometry.name
dfs = []
for _, row in input_gdf.iterrows():
input_geometry = row[geometry_name]
bounds = input_geometry.bounds
tiles = mercantile.tiles(bounds[0], bounds[1], bounds[2], bounds[3], zoom_level)
new_rows = []
for tile in tiles:
new_row = row.copy()
new_geometry = box(*mercantile.bounds(tile))
if new_geometry.intersects(input_geometry):
new_row[geometry_name] = new_geometry
new_row['quadkey'] = mercantile.quadkey(tile)
new_rows.append(new_row)
dfs.append(pd.DataFrame(new_rows))
df = pd.concat(dfs).reset_index(drop=True)
return CartoDataFrame(df, geometry=geometry_name, crs='epsg:4326')
def _calc_tms_zoom(self, scale):
for z in range(15,20):
b = mercantile.bounds(0,0,z)
if scale > math.sqrt((b.north - b.south)*(b.east - b.west) / (256*256)):
return z
def get_opts(self, count):
"""Return rasterio dataset creation options for the bounding tile."""
w, s, e, n = list(mercantile.bounds(*self.bounding_tile))
w, s = mercantile.xy(w, s)
e, n = mercantile.xy(e, n)
xcell = ((e - w) / self.tileshape)
ycell = ((n - s) / self.tileshape)
return {
'dtype': np.float32,
'driver': 'GTiff',
'height': self.tileshape,
'width': self.tileshape,
'count': count,
'compress': 'lzw',
'transform': affine.Affine(xcell, 0, w, 0, -ycell, n),
'crs': 'epsg:3857'}
def intersects(tile): # noqa
t = mercantile.bounds(*tile)
def _intersects(src):
(left, bottom, right, top) = src['bounds']
return not(
left >= t.east or
right <= t.west or
top <= t.south or
bottom >= t.north
)
return _intersects
where_cause = "WHERE"
else:
where_cause = "AND"
return """
SELECT
ST_AsMVT(tile)
FROM
({data_query}
{where_cause}
{area_filter}
{geom_column_definition} && {extent}
) as tile""".format(data_query=data_query, where_cause=where_cause, area_filter=area_filter, geom_column_definition=geom_column_definition, extent=extent)
# Wrap EALGIS query in a PostGIS query to produce a vector tile
mvt_query = create_vectortile_sql(layer, bounds=bounds(x, y, z))
with datastore().access_data() as db:
tile = db.session.execute(mvt_query).fetchone()[0]
return BytesIO(tile).read()