Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def graph_response(graph, format):
'''
Return a proper flask response for a RDF resource given an expected format.
'''
fmt = guess_format(format)
if not fmt:
abort(404)
headers = {
'Content-Type': RDF_MIME_TYPES[fmt]
}
kwargs =... | [] |
Please provide a description of the function:def valid_at(self, valid_date):
'''Limit current QuerySet to zone valid at a given date'''
is_valid = db.Q(validity__end__gt=valid_date,
validity__start__lte=valid_date)
no_validity = db.Q(validity=None)
return self(is_... | [] |
Please provide a description of the function:def resolve(self, geoid, id_only=False):
'''
Resolve a GeoZone given a GeoID.
The start date is resolved from the given GeoID,
ie. it find there is a zone valid a the geoid validity,
resolve the `latest` alias
or use `latest` ... | [] |
Please provide a description of the function:def keys_values(self):
keys_values = []
for value in self.keys.values():
if isinstance(value, list):
keys_values += value
elif isinstance(value, basestring) and not value.startswith('-'):
# Avoi... | [
"Key values might be a list or not, always return a list."
] |
Please provide a description of the function:def level_i18n_name(self):
for level, name in spatial_granularities:
if self.level == level:
return name
return self.level_name | [
"In use within templates for dynamic translations."
] |
Please provide a description of the function:def ancestors_objects(self):
ancestors_objects = []
for ancestor in self.ancestors:
try:
ancestor_object = GeoZone.objects.get(id=ancestor)
except GeoZone.DoesNotExist:
continue
ance... | [
"Ancestors objects sorted by name."
] |
Please provide a description of the function:def child_level(self):
HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS')
try:
return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1]
except (IndexError, ValueError):
return None | [
"Return the child level given handled levels."
] |
Please provide a description of the function:def harvest(self):
'''Start the harvesting process'''
if self.perform_initialization() is not None:
self.process_items()
self.finalize()
return self.job | [] |
Please provide a description of the function:def perform_initialization(self):
'''Initialize the harvesting for a given job'''
log.debug('Initializing backend')
factory = HarvestJob if self.dryrun else HarvestJob.objects.create
self.job = factory(status='initializing',
... | [] |
Please provide a description of the function:def get_dataset(self, remote_id):
'''Get or create a dataset given its remote ID (and its source)
We first try to match `source_id` to be source domain independent
'''
dataset = Dataset.objects(__raw__={
'extras.harvest:remote_id':... | [] |
Please provide a description of the function:def validate(self, data, schema):
'''Perform a data validation against a given schema.
:param data: an object to validate
:param schema: a Voluptous schema to validate against
'''
try:
return schema(data)
except Mu... | [] |
Please provide a description of the function:def add(obj):
'''
Handle a badge add API.
- Expecting badge_fieds as payload
- Return the badge as payload
- Return 200 if the badge is already
- Return 201 if the badge is added
'''
Form = badge_form(obj.__class__)
form = api.validate(Fo... | [] |
Please provide a description of the function:def remove(obj, kind):
'''
Handle badge removal API
- Returns 404 if the badge for this kind is absent
- Returns 204 on success
'''
if not obj.get_badge(kind):
api.abort(404, 'Badge does not exists')
obj.remove_badge(kind)
return '', ... | [] |
Please provide a description of the function:def check_for_territories(query):
if not query or not current_app.config.get('ACTIVATE_TERRITORIES'):
return []
dbqs = db.Q()
query = query.lower()
is_digit = query.isdigit()
query_length = len(query)
for level in current_app.config.get(... | [
"\n Return a geozone queryset of territories given the `query`.\n\n Results are sorted by population and area (biggest first).\n "
] |
Please provide a description of the function:def parse(text):
'''Parse a geoid from text and return a tuple (level, code, validity)'''
if '@' in text:
spatial, validity = text.split('@')
else:
spatial = text
validity = 'latest'
if ':' not in spatial:
raise GeoIDError('Bad... | [] |
Please provide a description of the function:def build(level, code, validity=None):
'''Serialize a GeoID from its parts'''
spatial = ':'.join((level, code))
if not validity:
return spatial
elif isinstance(validity, basestring):
return '@'.join((spatial, validity))
elif isinstance(val... | [] |
Please provide a description of the function:def from_zone(zone):
'''Build a GeoID from a given zone'''
validity = zone.validity.start if zone.validity else None
return build(zone.level, zone.code, validity) | [] |
Please provide a description of the function:def resource_to_rdf(resource, dataset=None, graph=None):
'''
Map a Resource domain model to a DCAT/RDF graph
'''
graph = graph or Graph(namespace_manager=namespace_manager)
if dataset and dataset.id:
id = URIRef(url_for('datasets.show_redirect', d... | [] |
Please provide a description of the function:def dataset_to_rdf(dataset, graph=None):
'''
Map a dataset domain model to a DCAT/RDF graph
'''
# Use the unlocalized permalink to the dataset as URI when available
# unless there is already an upstream URI
if 'uri' in dataset.extras:
id = URI... | [] |
Please provide a description of the function:def temporal_from_literal(text):
'''
Parse a temporal coverage from a literal ie. either:
- an ISO date range
- a single ISO date period (month,year)
'''
if text.count('/') == 1:
# This is an ISO date range as preconized by Gov.uk
# ht... | [] |
Please provide a description of the function:def temporal_from_resource(resource):
'''
Parse a temporal coverage from a RDF class/resource ie. either:
- a `dct:PeriodOfTime` with schema.org `startDate` and `endDate` properties
- an inline gov.uk Time Interval value
- an URI reference to a gov.uk Tim... | [] |
Please provide a description of the function:def temporal_from_rdf(period_of_time):
'''Failsafe parsing of a temporal coverage'''
try:
if isinstance(period_of_time, Literal):
return temporal_from_literal(str(period_of_time))
elif isinstance(period_of_time, RdfResource):
r... | [] |
Please provide a description of the function:def title_from_rdf(rdf, url):
'''
Try to extract a distribution title from a property.
As it's not a mandatory property,
it fallback on building a title from the URL
then the format and in last ressort a generic resource name.
'''
title = rdf_valu... | [] |
Please provide a description of the function:def resource_from_rdf(graph_or_distrib, dataset=None):
'''
Map a Resource domain model to a DCAT/RDF graph
'''
if isinstance(graph_or_distrib, RdfResource):
distrib = graph_or_distrib
else:
node = graph_or_distrib.value(predicate=RDF.type,... | [] |
Please provide a description of the function:def dataset_from_rdf(graph, dataset=None, node=None):
'''
Create or update a dataset from a RDF/DCAT graph
'''
dataset = dataset or Dataset()
if node is None: # Assume first match is the only match
node = graph.value(predicate=RDF.type, object=D... | [] |
Please provide a description of the function:def check_url_does_not_exists(form, field):
'''Ensure a reuse URL is not yet registered'''
if field.data != field.object_data and Reuse.url_exists(field.data):
raise validators.ValidationError(_('This URL is already registered')) | [] |
Please provide a description of the function:def attach_zone(geoid, organization_id_or_slug):
'''Attach a zone <geoid> restricted to level for a given <organization>.'''
organization = Organization.objects.get_by_id_or_slug(
organization_id_or_slug)
if not organization:
log.error('No organiz... | [] |
Please provide a description of the function:def detach_zone(organization_id_or_slug):
'''Detach the zone of a given <organization>.'''
organization = Organization.objects.get_by_id_or_slug(
organization_id_or_slug)
if not organization:
exit_with_error(
'No organization found for... | [] |
Please provide a description of the function:def init(ctx):
'''Initialize your udata instance (search index, user, sample data...)'''
log.info('Apply DB migrations if needed')
ctx.invoke(migrate, record=True)
ctx.invoke(index)
if IS_TTY:
text = _('Do you want to create a superadmin user?'... | [] |
Please provide a description of the function:def obj_to_string(obj):
'''Render an object into a unicode string if possible'''
if not obj:
return None
elif isinstance(obj, bytes):
return obj.decode('utf-8')
elif isinstance(obj, basestring):
return obj
elif is_lazy_string(obj):... | [] |
Please provide a description of the function:def add_filter(self, filter_values):
field = self._params['field']
# Build a `AND` query on values wihtout the OR operator.
# and a `OR` query for each value containing the OR operator.
filters = [
Q('bool', should=[
... | [
"Improve the original one to deal with OR cases."
] |
Please provide a description of the function:def get_values(self, data, filter_values):
values = super(ModelTermsFacet, self).get_values(data, filter_values)
ids = [key for (key, doc_count, selected) in values]
# Perform a model resolution: models are feched from DB
# We use mod... | [
"\n Turn the raw bucket data into a list of tuples containing the object,\n number of documents and a flag indicating whether this value has been\n selected or not.\n "
] |
Please provide a description of the function:def get_value_filter(self, filter_value):
'''
Fix here until upstream PR is merged
https://github.com/elastic/elasticsearch-dsl-py/pull/473
'''
self.validate_parameter(filter_value)
f, t = self._ranges[filter_value]
lim... | [] |
Please provide a description of the function:def save(self, commit=True, **kwargs):
'''Register the current user as admin on creation'''
org = super(OrganizationForm, self).save(commit=False, **kwargs)
if not org.id:
user = current_user._get_current_object()
member = Mem... | [] |
Please provide a description of the function:def load(filename, drop=False):
'''
Load a geozones archive from <filename>
<filename> can be either a local path or a remote URL.
'''
if filename.startswith('http'):
log.info('Downloading GeoZones bundle: %s', filename)
filename, _ = url... | [] |
Please provide a description of the function:def load_logos(filename):
'''
Load logos from a geologos archive from <filename>
<filename> can be either a local path or a remote URL.
'''
if filename.startswith('http'):
log.info('Downloading GeoLogos bundle: %s', filename)
filename, _ ... | [] |
Please provide a description of the function:def migrate():
'''
Migrate zones from old to new ids in datasets.
Should only be run once with the new version of geozones w/ geohisto.
'''
counter = Counter()
drom_zone = GeoZone.objects(id='country-subset:fr:drom').first()
dromcom_zone = GeoZon... | [] |
Please provide a description of the function:def get_cache_key(path):
# Python 2/3 support for path hashing
try:
path_hash = hashlib.md5(path).hexdigest()
except TypeError:
path_hash = hashlib.md5(path.encode('utf-8')).hexdigest()
return settings.cache_key_prefix + path_hash | [
"\n Create a cache key by concatenating the prefix with a hash of the path.\n "
] |
Please provide a description of the function:def get_remote_etag(storage, prefixed_path):
normalized_path = safe_join(storage.location, prefixed_path).replace(
'\\', '/')
try:
return storage.bucket.get_key(normalized_path).etag
except AttributeError:
pass
try:
return... | [
"\n Get etag of path from S3 using boto or boto3.\n "
] |
Please provide a description of the function:def get_etag(storage, path, prefixed_path):
cache_key = get_cache_key(path)
etag = cache.get(cache_key, False)
if etag is False:
etag = get_remote_etag(storage, prefixed_path)
cache.set(cache_key, etag)
return etag | [
"\n Get etag of path from cache or S3 - in that order.\n "
] |
Please provide a description of the function:def get_file_hash(storage, path):
contents = storage.open(path).read()
file_hash = hashlib.md5(contents).hexdigest()
# Check if content should be gzipped and hash gzipped content
content_type = mimetypes.guess_type(path)[0] or 'application/octet-stream'... | [
"\n Create md5 hash from file contents.\n "
] |
Please provide a description of the function:def has_matching_etag(remote_storage, source_storage, path, prefixed_path):
storage_etag = get_etag(remote_storage, path, prefixed_path)
local_etag = get_file_hash(source_storage, path)
return storage_etag == local_etag | [
"\n Compare etag of path in source storage with remote.\n "
] |
Please provide a description of the function:def should_copy_file(remote_storage, path, prefixed_path, source_storage):
if has_matching_etag(
remote_storage, source_storage, path, prefixed_path):
logger.info("%s: Skipping based on matching file hashes" % path)
return False
# In... | [
"\n Returns True if the file should be copied, otherwise False.\n "
] |
Please provide a description of the function:def set_options(self, **options):
ignore_etag = options.pop('ignore_etag', False)
disable = options.pop('disable_collectfast', False)
if ignore_etag:
warnings.warn(
"--ignore-etag is deprecated since 0.5.0, use "
... | [
"\n Set options and handle deprecation.\n "
] |
Please provide a description of the function:def collect(self):
ret = super(Command, self).collect()
if settings.threads:
Pool(settings.threads).map(self.do_copy_file, self.tasks)
return ret | [
"\n Override collect to copy files concurrently. The tasks are populated by\n Command.copy_file() which is called by super().collect().\n "
] |
Please provide a description of the function:def handle(self, **options):
super(Command, self).handle(**options)
return "{} static file{} copied.".format(
self.num_copied_files,
'' if self.num_copied_files == 1 else 's') | [
"\n Override handle to supress summary output\n "
] |
Please provide a description of the function:def do_copy_file(self, args):
path, prefixed_path, source_storage = args
reset_connection(self.storage)
if self.collectfast_enabled and not self.dry_run:
try:
if not should_copy_file(
self... | [
"\n Determine if file should be copied or not and handle exceptions.\n "
] |
Please provide a description of the function:def copy_file(self, path, prefixed_path, source_storage):
args = (path, prefixed_path, source_storage)
if settings.threads:
self.tasks.append(args)
else:
self.do_copy_file(args) | [
"\n Appends path to task queue if threads are enabled, otherwise copies\n the file with a blocking call.\n "
] |
Please provide a description of the function:def delete_file(self, path, prefixed_path, source_storage):
if not self.collectfast_enabled:
return super(Command, self).delete_file(
path, prefixed_path, source_storage)
if not self.dry_run:
self.log("Deleting... | [
"\n Override delete_file to skip modified time and exists lookups.\n "
] |
Please provide a description of the function:def join(rasters):
raster = rasters[0] # using the first raster to understand what is the type of data we have
mask_band = None
nodata = None
with raster._raster_opener(raster.source_file) as r:
nodata = r.nodata
mask_flags = r.mask_fla... | [
"\n This method takes a list of rasters and returns a raster that is constructed of all of them\n "
] |
Please provide a description of the function:def merge_all(rasters, roi=None, dest_resolution=None, merge_strategy=MergeStrategy.UNION,
shape=None, ul_corner=None, crs=None, pixel_strategy=PixelStrategy.FIRST,
resampling=Resampling.nearest):
first_raster = rasters[0]
if roi:
... | [
"Merge a list of rasters, cropping by a region of interest.\n There are cases that the roi is not precise enough for this cases one can use,\n the upper left corner the shape and crs to precisely define the roi.\n When roi is provided the ul_corner, shape and crs are ignored\n "
] |
Please provide a description of the function:def _merge_common_bands(rasters):
# type: (List[_Raster]) -> List[_Raster]
# Compute band order
all_bands = IndexedSet([rs.band_names[0] for rs in rasters])
def key(rs):
return all_bands.index(rs.band_names[0])
rasters_final = [] # type: L... | [
"Combine the common bands.\n\n "
] |
Please provide a description of the function:def _prepare_rasters(rasters, merge_strategy, first, resampling=Resampling.nearest):
# type: (List[GeoRaster2], MergeStrategy, GeoRaster2, Resampling) -> Tuple[IndexedSet[str], List[Optional[_Raster]]]
# Create list of prepared rasters
all_band_names = Index... | [
"Prepares the rasters according to the baseline (first) raster and the merge strategy.\n\n The baseline (first) raster is used to crop and reproject the other rasters,\n while the merge strategy is used to compute the bands of the result. These\n are returned for diagnostics.\n\n "
] |
Please provide a description of the function:def _explode_raster(raster, band_names=[]):
# type: (_Raster, Iterable[str]) -> List[_Raster]
# Using band_names=[] does no harm because we are not mutating it in place
# and it makes MyPy happy
if not band_names:
band_names = raster.band_names
... | [
"Splits a raster into multiband rasters.\n\n "
] |
Please provide a description of the function:def _fill_pixels(one, other):
# type: (_Raster, _Raster) -> _Raster
assert len(one.band_names) == len(other.band_names) == 1, "Rasters are not single band"
# We raise an error in the intersection is empty.
# Other options include returning an "empty" ra... | [
"Merges two single band rasters with the same band by filling the pixels according to depth.\n\n "
] |
Please provide a description of the function:def _stack_bands(one, other):
# type: (_Raster, _Raster) -> _Raster
assert set(one.band_names).intersection(set(other.band_names)) == set()
# We raise an error in the bands are the same. See above.
if one.band_names == other.band_names:
raise Va... | [
"Merges two rasters with non overlapping bands by stacking the bands.\n\n "
] |
Please provide a description of the function:def merge_two(one, other, merge_strategy=MergeStrategy.UNION, silent=False, pixel_strategy=PixelStrategy.FIRST):
# type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrategy) -> GeoRaster2
other_res = _prepare_other_raster(one, other)
if other_res is ... | [
"Merge two rasters into one.\n\n Parameters\n ----------\n one : GeoRaster2\n Left raster to merge.\n other : GeoRaster2\n Right raster to merge.\n merge_strategy : MergeStrategy, optional\n Merge strategy, from :py:data:`telluric.georaster.MergeStrategy` (default to \"union\").\... |
Please provide a description of the function:def _set_image(self, image, nodata=None):
# convert to masked array:
if isinstance(image, np.ma.core.MaskedArray):
masked = image
elif isinstance(image, np.core.ndarray):
masked = self._build_masked_array(image, nodata... | [
"\n Set self._image.\n\n :param image: supported: np.ma.array, np.array, TODO: PIL image\n :param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata\n :return:\n "
] |
Please provide a description of the function:def _raster_opener(cls, filename, *args, **kwargs):
with rasterio.Env(**cls.get_gdal_env(filename)):
try:
return rasterio.open(filename, *args, **kwargs)
except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_Base... | [
"Return handler to open rasters (rasterio.open)."
] |
Please provide a description of the function:def from_wms(cls, filename, vector, resolution, destination_file=None):
doc = wms_vrt(filename,
bounds=vector,
resolution=resolution).tostring()
filename = cls._save_to_destination_file(doc, destination_fil... | [
"Create georaster from the web service definition file."
] |
Please provide a description of the function:def from_rasters(cls, rasters, relative_to_vrt=True, destination_file=None, nodata=None, mask_band=None):
if isinstance(rasters, list):
doc = raster_list_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
else:
doc = ... | [
"Create georaster out of a list of rasters."
] |
Please provide a description of the function:def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):
if mutable:
geo_raster = MutableGeoRaster(filename=filename, band_names=band_names, **kwargs)
else:
geo_raster = cls(filename=filename, band_na... | [
"\n Read a georaster from a file.\n\n :param filename: url\n :param band_names: list of strings, or string.\n if None - will try to read from image, otherwise - these will be ['0', ..]\n :param lazy_load: if True - do not load anything\n :return: GeoRast... |
Please provide a description of the function:def tags(cls, filename, namespace=None):
return cls._raster_opener(filename).tags(ns=namespace) | [
"Extract tags from file."
] |
Please provide a description of the function:def image(self):
if self._image is None:
self._populate_from_rasterio_object(read_image=True)
return self._image | [
"Raster bitmap in numpy array."
] |
Please provide a description of the function:def band_names(self):
if self._band_names is None:
self._populate_from_rasterio_object(read_image=False)
return self._band_names | [
"Raster affine."
] |
Please provide a description of the function:def affine(self):
if self._affine is None:
self._populate_from_rasterio_object(read_image=False)
return self._affine | [
"Raster affine."
] |
Please provide a description of the function:def crs(self): # type: () -> CRS
if self._crs is None:
self._populate_from_rasterio_object(read_image=False)
return self._crs | [
"Raster crs."
] |
Please provide a description of the function:def shape(self):
if self._shape is None:
self._populate_from_rasterio_object(read_image=False)
return self._shape | [
"Raster shape."
] |
Please provide a description of the function:def source_file(self):
if self._filename is None:
self._filename = self._as_in_memory_geotiff()._filename
return self._filename | [
" When using open, returns the filename used\n "
] |
Please provide a description of the function:def blockshapes(self):
if self._blockshapes is None:
if self._filename:
self._populate_from_rasterio_object(read_image=False)
else:
# if no file is attached to the raster set the shape of each band to b... | [
"Raster all bands block shape."
] |
Please provide a description of the function:def save(self, filename, tags=None, **kwargs):
if not filename.startswith("/vsi"):
folder = os.path.abspath(os.path.join(filename, os.pardir))
os.makedirs(folder, exist_ok=True)
internal_mask = kwargs.get('GDAL_TIFF_INTERNAL_... | [
"\n Save GeoRaster to a file.\n\n :param filename: url\n :param tags: tags to add to default namespace\n\n optional parameters:\n\n * GDAL_TIFF_INTERNAL_MASK: specifies whether mask is within image file, or additional .msk\n * overviews: if True, will save with previews. de... |
Please provide a description of the function:def get(self, point):
if not (isinstance(point, GeoVector) and point.type == 'Point'):
raise TypeError('expect GeoVector(Point), got %s' % (point,))
target = self.to_raster(point)
return self.image[:, int(target.y), int(target.x)... | [
"\n Get the pixel values at the requested point.\n\n :param point: A GeoVector(POINT) with the coordinates of the values to get\n :return: numpy array of values\n "
] |
Please provide a description of the function:def astype(self, dst_type, in_range='dtype', out_range='dtype', clip_negative=False):
def type_max(dtype):
return np.iinfo(dtype).max
def type_min(dtype):
return np.iinfo(dtype).min
if (
in_range is None... | [
" Returns copy of the raster, converted to desired type\n Supported types: uint8, uint16, uint32, int8, int16, int32, float16, float32, float64\n\n :param dst_type: desired type\n :param in_range: str or 2-tuple, default 'dtype':\n 'image': use image min/max as the intensity range,\n... |
Please provide a description of the function:def crop(self, vector, resolution=None, masked=None,
bands=None, resampling=Resampling.cubic):
bounds, window = self._vector_to_raster_bounds(vector.envelope, boundless=self._image is None)
if resolution:
xsize, ysize = self.... | [
"\n crops raster outside vector (convex hull)\n :param vector: GeoVector, GeoFeature, FeatureCollection\n :param resolution: output resolution, None for full resolution\n :param resampling: reprojection resampling method, default `cubic`\n\n :return: GeoRaster\n "
] |
Please provide a description of the function:def pixel_crop(self, bounds, xsize=None, ysize=None, window=None,
masked=None, bands=None, resampling=Resampling.cubic):
if self._image is not None:
raster = self._crop(bounds, xsize=xsize, ysize=ysize, resampling=resampling)
... | [
"Crop raster outside vector (convex hull).\n\n :param bounds: bounds of requester portion of the image in image pixels\n :param xsize: output raster width, None for full resolution\n :param ysize: output raster height, None for full resolution\n :param windows: the bounds representation ... |
Please provide a description of the function:def _crop(self, bounds, xsize=None, ysize=None, resampling=Resampling.cubic):
out_raster = self[
int(bounds[0]): int(bounds[2]),
int(bounds[1]): int(bounds[3])
]
if xsize and ysize:
if not (xsize == out_ra... | [
"Crop raster outside vector (convex hull).\n\n :param bounds: bounds on image\n :param xsize: output raster width, None for full resolution\n :param ysize: output raster height, None for full resolution\n :param resampling: reprojection resampling method, default `cubic`\n\n :retu... |
Please provide a description of the function:def copy(self, mutable=False):
if self.not_loaded():
_cls = self.__class__
if mutable:
_cls = MutableGeoRaster
return _cls.open(self._filename)
return self.copy_with(mutable=mutable) | [
"Return a copy of this GeoRaster with no modifications.\n\n Can be use to create a Mutable copy of the GeoRaster"
] |
Please provide a description of the function:def copy_with(self, mutable=False, **kwargs):
init_args = {'affine': self.affine, 'crs': self.crs, 'band_names': self.band_names, 'nodata': self.nodata_value}
init_args.update(kwargs)
# The image is a special case because we don't want to ma... | [
"Get a copy of this GeoRaster with some attributes changed. NOTE: image is shallow-copied!"
] |
Please provide a description of the function:def resize(self, ratio=None, ratio_x=None, ratio_y=None, dest_width=None, dest_height=None, dest_resolution=None,
resampling=Resampling.cubic):
# validate input:
if sum([ratio is not None, ratio_x is not None and ratio_y is not None,
... | [
"\n Provide either ratio, or ratio_x and ratio_y, or dest_width and/or dest_height.\n\n :return: GeoRaster2\n "
] |
Please provide a description of the function:def _resize(self, ratio_x, ratio_y, resampling):
new_width = int(np.ceil(self.width * ratio_x))
new_height = int(np.ceil(self.height * ratio_y))
dest_affine = self.affine * Affine.scale(1 / ratio_x, 1 / ratio_y)
if self.not_loaded():... | [
"Return raster resized by ratio."
] |
Please provide a description of the function:def to_pillow_image(self, return_mask=False):
img = np.rollaxis(np.rollaxis(self.image.data, 2), 2)
img = Image.fromarray(img[:, :, 0]) if img.shape[2] == 1 else Image.fromarray(img)
if return_mask:
mask = np.ma.getmaskarray(self.... | [
"Return Pillow. Image, and optionally also mask."
] |
Please provide a description of the function:def _reproject(self, new_width, new_height, dest_affine, dtype=None,
dst_crs=None, resampling=Resampling.cubic):
if new_width == 0 or new_height == 0:
return None
dst_crs = dst_crs or self.crs
dtype = dtype or s... | [
"Return re-projected raster to new raster.\n\n :param new_width: new raster width in pixels\n :param new_height: new raster height in pixels\n :param dest_affine: new raster affine\n :param dtype: new raster dtype, default current dtype\n :param dst_crs: new raster crs, default cu... |
Please provide a description of the function:def reproject(self, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, target_aligned_pixels=False,
resampling=Resampling.cubic, creation_options=None, **kwargs):
if self._image is None and s... | [
"Return re-projected raster to new raster.\n\n Parameters\n ------------\n dst_crs: rasterio.crs.CRS, optional\n Target coordinate reference system.\n resolution: tuple (x resolution, y resolution) or float, optional\n Target resolution, in units of target coordinat... |
Please provide a description of the function:def to_png(self, transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype'):
return self.to_bytes(transparent=transparent, thumbnail_size=thumbnail_size,
resampling=resampling, in_range=in_range,... | [
"\n Convert to png format (discarding geo).\n\n Optionally also resizes.\n Note: for color images returns interlaced.\n :param transparent: if True - sets alpha channel for nodata pixels\n :param thumbnail_size: if not None - resize to thumbnail size, e.g. 512\n :param in_r... |
Please provide a description of the function:def to_bytes(self, transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype',
format="png"):
resampling = resampling if resampling is not None else Resampling.cubic
if self.num_bands < 3:
... | [
"\n Convert to selected format (discarding geo).\n\n Optionally also resizes.\n Note: for color images returns interlaced.\n :param transparent: if True - sets alpha channel for nodata pixels\n :param thumbnail_size: if not None - resize to thumbnail size, e.g. 512\n :param... |
Please provide a description of the function:def from_bytes(cls, image_bytes, affine, crs, band_names=None):
b = io.BytesIO(image_bytes)
image = imageio.imread(b)
roll = np.rollaxis(image, 2)
if band_names is None:
band_names = [0, 1, 2]
elif isinstance(band_... | [
"Create GeoRaster from image BytesIo object.\n\n :param image_bytes: io.BytesIO object\n :param affine: rasters affine\n :param crs: rasters crs\n :param band_names: e.g. ['red', 'blue'] or 'red'\n "
] |
Please provide a description of the function:def _repr_html_(self):
TileServer.run_tileserver(self, self.footprint())
capture = "raster: %s" % self._filename
mp = TileServer.folium_client(self, self.footprint(), capture=capture)
return mp._repr_html_() | [
"Required for jupyter notebook to show raster as an interactive map."
] |
Please provide a description of the function:def image_corner(self, corner):
if corner not in self.corner_types():
raise GeoRaster2Error('corner %s invalid, expected: %s' % (corner, self.corner_types()))
x = 0 if corner[1] == 'l' else self.width
y = 0 if corner[0] == 'u' el... | [
"Return image corner in pixels, as shapely.Point."
] |
Please provide a description of the function:def center(self):
image_center = Point(self.width / 2, self.height / 2)
return self.to_world(image_center) | [
"Return footprint center in world coordinates, as GeoVector."
] |
Please provide a description of the function:def bounds(self):
corners = [self.image_corner(corner) for corner in self.corner_types()]
return Polygon([[corner.x, corner.y] for corner in corners]) | [
"Return image rectangle in pixels, as shapely.Polygon."
] |
Please provide a description of the function:def _calc_footprint(self):
corners = [self.corner(corner) for corner in self.corner_types()]
coords = []
for corner in corners:
shape = corner.get_shape(corner.crs)
coords.append([shape.x, shape.y])
shp = Poly... | [
"Return rectangle in world coordinates, as GeoVector."
] |
Please provide a description of the function:def to_raster(self, vector):
return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine) | [
"Return the vector in pixel coordinates, as shapely.Geometry."
] |
Please provide a description of the function:def to_world(self, shape, dst_crs=None):
if dst_crs is None:
dst_crs = self.crs
shp = transform(shape, self.crs, dst_crs, dst_affine=self.affine)
return GeoVector(shp, dst_crs) | [
"Return the shape (provided in pixel coordinates) in world coordinates, as GeoVector."
] |
Please provide a description of the function:def reduce(self, op):
per_band = [getattr(np.ma, op)(self.image.data[band, np.ma.getmaskarray(self.image)[band, :, :] == np.False_])
for band in range(self.num_bands)]
return per_band | [
"Reduce the raster to a score, using 'op' operation.\n\n nodata pixels are ignored.\n op is currently limited to numpy.ma, e.g. 'mean', 'std' etc\n :returns list of per-band values\n "
] |
Please provide a description of the function:def mask(self, vector, mask_shape_nodata=False):
from telluric.collections import BaseCollection
# crop raster to reduce memory footprint
cropped = self.crop(vector)
if isinstance(vector, BaseCollection):
shapes = [cropp... | [
"\n Set pixels outside vector as nodata.\n\n :param vector: GeoVector, GeoFeature, FeatureCollection\n :param mask_shape_nodata: if True - pixels inside shape are set nodata, if False - outside shape is nodata\n :return: GeoRaster2\n "
] |
Please provide a description of the function:def mask_by_value(self, nodata):
return self.copy_with(image=np.ma.masked_array(self.image.data, mask=self.image.data == nodata)) | [
"\n Return raster with a mask calculated based on provided value.\n Only pixels with value=nodata will be masked.\n\n :param nodata: value of the pixels that should be masked\n :return: GeoRaster2\n "
] |
Please provide a description of the function:def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256,
overview_blocksize=256, creation_options=None):
src = self # GeoRaster2.open(self._filename)
with tempfile.NamedTemporaryFile(suffix=... | [
"Save as Cloud Optimized GeoTiff object to a new file.\n\n :param dest_url: path to the new raster\n :param resampling: which Resampling to use on reading, default Resampling.gauss\n :param blocksize: the size of the blocks default 256\n :param overview_blocksize: the block size of the o... |
Please provide a description of the function:def _get_window_out_shape(self, bands, window, xsize, ysize):
if xsize and ysize is None:
ratio = window.width / xsize
ysize = math.ceil(window.height / ratio)
elif ysize and xsize is None:
ratio = window.height /... | [
"Get the outshape of a window.\n\n this method is only used inside get_window to calculate the out_shape\n "
] |
Please provide a description of the function:def _read_with_mask(raster, masked):
if masked is None:
mask_flags = raster.mask_flag_enums
per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])
masked = per_dataset_mask
... | [
" returns if we should read from rasterio using the masked\n "
] |
Please provide a description of the function:def get_window(self, window, bands=None,
xsize=None, ysize=None,
resampling=Resampling.cubic, masked=None, affine=None
):
bands = bands or list(range(1, self.num_bands + 1))
# requested_out_sh... | [
"Get window from raster.\n\n :param window: requested window\n :param bands: list of indices of requested bads, default None which returns all bands\n :param xsize: tile x size default None, for full resolution pass None\n :param ysize: tile y size default None, for full resolution pass ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.