id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,500
|
opendatateam/udata
|
udata/search/fields.py
|
TermsFacet.add_filter
|
def add_filter(self, filter_values):
"""Improve the original one to deal with OR cases."""
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=[
Q('term', **{field: v}) for v in value.split(OR_SEPARATOR)
])
if OR_SEPARATOR in value else
Q('term', **{field: value})
for value in filter_values
]
return Q('bool', must=filters) if len(filters) > 1 else filters[0]
|
python
|
def add_filter(self, filter_values):
"""Improve the original one to deal with OR cases."""
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=[
Q('term', **{field: v}) for v in value.split(OR_SEPARATOR)
])
if OR_SEPARATOR in value else
Q('term', **{field: value})
for value in filter_values
]
return Q('bool', must=filters) if len(filters) > 1 else filters[0]
|
[
"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",
"=",
"[",
"Q",
"(",
"'term'",
",",
"*",
"*",
"{",
"field",
":",
"v",
"}",
")",
"for",
"v",
"in",
"value",
".",
"split",
"(",
"OR_SEPARATOR",
")",
"]",
")",
"if",
"OR_SEPARATOR",
"in",
"value",
"else",
"Q",
"(",
"'term'",
",",
"*",
"*",
"{",
"field",
":",
"value",
"}",
")",
"for",
"value",
"in",
"filter_values",
"]",
"return",
"Q",
"(",
"'bool'",
",",
"must",
"=",
"filters",
")",
"if",
"len",
"(",
"filters",
")",
">",
"1",
"else",
"filters",
"[",
"0",
"]"
] |
Improve the original one to deal with OR cases.
|
[
"Improve",
"the",
"original",
"one",
"to",
"deal",
"with",
"OR",
"cases",
"."
] |
f016585af94b0ff6bd73738c700324adc8ba7f8f
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/fields.py#L87-L100
|
14,501
|
opendatateam/udata
|
udata/search/fields.py
|
ModelTermsFacet.get_values
|
def get_values(self, data, filter_values):
"""
Turn the raw bucket data into a list of tuples containing the object,
number of documents and a flag indicating whether this value has been
selected or not.
"""
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 model field to cast IDs
ids = [self.model_field.to_mongo(id) for id in ids]
objects = self.model.objects.in_bulk(ids)
return [
(objects.get(self.model_field.to_mongo(key)), doc_count, selected)
for (key, doc_count, selected) in values
]
|
python
|
def get_values(self, data, filter_values):
"""
Turn the raw bucket data into a list of tuples containing the object,
number of documents and a flag indicating whether this value has been
selected or not.
"""
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 model field to cast IDs
ids = [self.model_field.to_mongo(id) for id in ids]
objects = self.model.objects.in_bulk(ids)
return [
(objects.get(self.model_field.to_mongo(key)), doc_count, selected)
for (key, doc_count, selected) in values
]
|
[
"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 model field to cast IDs",
"ids",
"=",
"[",
"self",
".",
"model_field",
".",
"to_mongo",
"(",
"id",
")",
"for",
"id",
"in",
"ids",
"]",
"objects",
"=",
"self",
".",
"model",
".",
"objects",
".",
"in_bulk",
"(",
"ids",
")",
"return",
"[",
"(",
"objects",
".",
"get",
"(",
"self",
".",
"model_field",
".",
"to_mongo",
"(",
"key",
")",
")",
",",
"doc_count",
",",
"selected",
")",
"for",
"(",
"key",
",",
"doc_count",
",",
"selected",
")",
"in",
"values",
"]"
] |
Turn the raw bucket data into a list of tuples containing the object,
number of documents and a flag indicating whether this value has been
selected or not.
|
[
"Turn",
"the",
"raw",
"bucket",
"data",
"into",
"a",
"list",
"of",
"tuples",
"containing",
"the",
"object",
"number",
"of",
"documents",
"and",
"a",
"flag",
"indicating",
"whether",
"this",
"value",
"has",
"been",
"selected",
"or",
"not",
"."
] |
f016585af94b0ff6bd73738c700324adc8ba7f8f
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/fields.py#L135-L151
|
14,502
|
opendatateam/udata
|
udata/core/organization/forms.py
|
OrganizationForm.save
|
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 = Member(user=user, role='admin')
org.members.append(member)
if commit:
org.save()
return org
|
python
|
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 = Member(user=user, role='admin')
org.members.append(member)
if commit:
org.save()
return org
|
[
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"org",
"=",
"super",
"(",
"OrganizationForm",
",",
"self",
")",
".",
"save",
"(",
"commit",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"org",
".",
"id",
":",
"user",
"=",
"current_user",
".",
"_get_current_object",
"(",
")",
"member",
"=",
"Member",
"(",
"user",
"=",
"user",
",",
"role",
"=",
"'admin'",
")",
"org",
".",
"members",
".",
"append",
"(",
"member",
")",
"if",
"commit",
":",
"org",
".",
"save",
"(",
")",
"return",
"org"
] |
Register the current user as admin on creation
|
[
"Register",
"the",
"current",
"user",
"as",
"admin",
"on",
"creation"
] |
f016585af94b0ff6bd73738c700324adc8ba7f8f
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/organization/forms.py#L36-L48
|
14,503
|
antonagestam/collectfast
|
collectfast/etag.py
|
get_cache_key
|
def get_cache_key(path):
"""
Create a cache key by concatenating the prefix with a hash of the 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
|
python
|
def get_cache_key(path):
"""
Create a cache key by concatenating the prefix with a hash of the 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
|
[
"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"
] |
Create a cache key by concatenating the prefix with a hash of the path.
|
[
"Create",
"a",
"cache",
"key",
"by",
"concatenating",
"the",
"prefix",
"with",
"a",
"hash",
"of",
"the",
"path",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L28-L37
|
14,504
|
antonagestam/collectfast
|
collectfast/etag.py
|
get_remote_etag
|
def get_remote_etag(storage, prefixed_path):
"""
Get etag of path from S3 using boto or boto3.
"""
normalized_path = safe_join(storage.location, prefixed_path).replace(
'\\', '/')
try:
return storage.bucket.get_key(normalized_path).etag
except AttributeError:
pass
try:
return storage.bucket.Object(normalized_path).e_tag
except:
pass
return None
|
python
|
def get_remote_etag(storage, prefixed_path):
"""
Get etag of path from S3 using boto or boto3.
"""
normalized_path = safe_join(storage.location, prefixed_path).replace(
'\\', '/')
try:
return storage.bucket.get_key(normalized_path).etag
except AttributeError:
pass
try:
return storage.bucket.Object(normalized_path).e_tag
except:
pass
return None
|
[
"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",
"storage",
".",
"bucket",
".",
"Object",
"(",
"normalized_path",
")",
".",
"e_tag",
"except",
":",
"pass",
"return",
"None"
] |
Get etag of path from S3 using boto or boto3.
|
[
"Get",
"etag",
"of",
"path",
"from",
"S3",
"using",
"boto",
"or",
"boto3",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L40-L54
|
14,505
|
antonagestam/collectfast
|
collectfast/etag.py
|
get_etag
|
def get_etag(storage, path, prefixed_path):
"""
Get etag of path from cache or S3 - in that order.
"""
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
|
python
|
def get_etag(storage, path, prefixed_path):
"""
Get etag of path from cache or S3 - in that order.
"""
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
|
[
"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"
] |
Get etag of path from cache or S3 - in that order.
|
[
"Get",
"etag",
"of",
"path",
"from",
"cache",
"or",
"S3",
"-",
"in",
"that",
"order",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L57-L66
|
14,506
|
antonagestam/collectfast
|
collectfast/etag.py
|
get_file_hash
|
def get_file_hash(storage, path):
"""
Create md5 hash from file contents.
"""
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'
if settings.is_gzipped and content_type in settings.gzip_content_types:
cache_key = get_cache_key('gzip_hash_%s' % file_hash)
file_hash = cache.get(cache_key, False)
if file_hash is False:
buffer = BytesIO()
zf = gzip.GzipFile(
mode='wb', compresslevel=6, fileobj=buffer, mtime=0.0)
zf.write(force_bytes(contents))
zf.close()
file_hash = hashlib.md5(buffer.getvalue()).hexdigest()
cache.set(cache_key, file_hash)
return '"%s"' % file_hash
|
python
|
def get_file_hash(storage, path):
"""
Create md5 hash from file contents.
"""
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'
if settings.is_gzipped and content_type in settings.gzip_content_types:
cache_key = get_cache_key('gzip_hash_%s' % file_hash)
file_hash = cache.get(cache_key, False)
if file_hash is False:
buffer = BytesIO()
zf = gzip.GzipFile(
mode='wb', compresslevel=6, fileobj=buffer, mtime=0.0)
zf.write(force_bytes(contents))
zf.close()
file_hash = hashlib.md5(buffer.getvalue()).hexdigest()
cache.set(cache_key, file_hash)
return '"%s"' % file_hash
|
[
"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'",
"if",
"settings",
".",
"is_gzipped",
"and",
"content_type",
"in",
"settings",
".",
"gzip_content_types",
":",
"cache_key",
"=",
"get_cache_key",
"(",
"'gzip_hash_%s'",
"%",
"file_hash",
")",
"file_hash",
"=",
"cache",
".",
"get",
"(",
"cache_key",
",",
"False",
")",
"if",
"file_hash",
"is",
"False",
":",
"buffer",
"=",
"BytesIO",
"(",
")",
"zf",
"=",
"gzip",
".",
"GzipFile",
"(",
"mode",
"=",
"'wb'",
",",
"compresslevel",
"=",
"6",
",",
"fileobj",
"=",
"buffer",
",",
"mtime",
"=",
"0.0",
")",
"zf",
".",
"write",
"(",
"force_bytes",
"(",
"contents",
")",
")",
"zf",
".",
"close",
"(",
")",
"file_hash",
"=",
"hashlib",
".",
"md5",
"(",
"buffer",
".",
"getvalue",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"cache",
".",
"set",
"(",
"cache_key",
",",
"file_hash",
")",
"return",
"'\"%s\"'",
"%",
"file_hash"
] |
Create md5 hash from file contents.
|
[
"Create",
"md5",
"hash",
"from",
"file",
"contents",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L76-L97
|
14,507
|
antonagestam/collectfast
|
collectfast/etag.py
|
has_matching_etag
|
def has_matching_etag(remote_storage, source_storage, path, prefixed_path):
"""
Compare etag of path in source storage with remote.
"""
storage_etag = get_etag(remote_storage, path, prefixed_path)
local_etag = get_file_hash(source_storage, path)
return storage_etag == local_etag
|
python
|
def has_matching_etag(remote_storage, source_storage, path, prefixed_path):
"""
Compare etag of path in source storage with remote.
"""
storage_etag = get_etag(remote_storage, path, prefixed_path)
local_etag = get_file_hash(source_storage, path)
return storage_etag == local_etag
|
[
"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"
] |
Compare etag of path in source storage with remote.
|
[
"Compare",
"etag",
"of",
"path",
"in",
"source",
"storage",
"with",
"remote",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L100-L106
|
14,508
|
antonagestam/collectfast
|
collectfast/etag.py
|
should_copy_file
|
def should_copy_file(remote_storage, path, prefixed_path, source_storage):
"""
Returns True if the file should be copied, otherwise False.
"""
if has_matching_etag(
remote_storage, source_storage, path, prefixed_path):
logger.info("%s: Skipping based on matching file hashes" % path)
return False
# Invalidate cached versions of lookup before copy
destroy_etag(path)
logger.info("%s: Hashes did not match" % path)
return True
|
python
|
def should_copy_file(remote_storage, path, prefixed_path, source_storage):
"""
Returns True if the file should be copied, otherwise False.
"""
if has_matching_etag(
remote_storage, source_storage, path, prefixed_path):
logger.info("%s: Skipping based on matching file hashes" % path)
return False
# Invalidate cached versions of lookup before copy
destroy_etag(path)
logger.info("%s: Hashes did not match" % path)
return True
|
[
"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",
"# Invalidate cached versions of lookup before copy",
"destroy_etag",
"(",
"path",
")",
"logger",
".",
"info",
"(",
"\"%s: Hashes did not match\"",
"%",
"path",
")",
"return",
"True"
] |
Returns True if the file should be copied, otherwise False.
|
[
"Returns",
"True",
"if",
"the",
"file",
"should",
"be",
"copied",
"otherwise",
"False",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/etag.py#L109-L121
|
14,509
|
antonagestam/collectfast
|
collectfast/management/commands/collectstatic.py
|
Command.set_options
|
def set_options(self, **options):
"""
Set options and handle deprecation.
"""
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 "
"--disable-collectfast instead.")
if ignore_etag or disable:
self.collectfast_enabled = False
super(Command, self).set_options(**options)
|
python
|
def set_options(self, **options):
"""
Set options and handle deprecation.
"""
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 "
"--disable-collectfast instead.")
if ignore_etag or disable:
self.collectfast_enabled = False
super(Command, self).set_options(**options)
|
[
"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 \"",
"\"--disable-collectfast instead.\"",
")",
"if",
"ignore_etag",
"or",
"disable",
":",
"self",
".",
"collectfast_enabled",
"=",
"False",
"super",
"(",
"Command",
",",
"self",
")",
".",
"set_options",
"(",
"*",
"*",
"options",
")"
] |
Set options and handle deprecation.
|
[
"Set",
"options",
"and",
"handle",
"deprecation",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/management/commands/collectstatic.py#L44-L56
|
14,510
|
antonagestam/collectfast
|
collectfast/management/commands/collectstatic.py
|
Command.handle
|
def handle(self, **options):
"""
Override handle to supress summary output
"""
super(Command, self).handle(**options)
return "{} static file{} copied.".format(
self.num_copied_files,
'' if self.num_copied_files == 1 else 's')
|
python
|
def handle(self, **options):
"""
Override handle to supress summary output
"""
super(Command, self).handle(**options)
return "{} static file{} copied.".format(
self.num_copied_files,
'' if self.num_copied_files == 1 else 's')
|
[
"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'",
")"
] |
Override handle to supress summary output
|
[
"Override",
"handle",
"to",
"supress",
"summary",
"output"
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/management/commands/collectstatic.py#L68-L75
|
14,511
|
antonagestam/collectfast
|
collectfast/management/commands/collectstatic.py
|
Command.do_copy_file
|
def do_copy_file(self, args):
"""
Determine if file should be copied or not and handle exceptions.
"""
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.storage, path, prefixed_path, source_storage):
return False
except Exception as e:
if settings.debug:
raise
# Ignore errors and let default collectstatic handle copy
self.stdout.write(smart_str(
"Ignored error in Collectfast:\n%s\n--> Continuing using "
"default collectstatic." % e))
self.num_copied_files += 1
return super(Command, self).copy_file(
path, prefixed_path, source_storage)
|
python
|
def do_copy_file(self, args):
"""
Determine if file should be copied or not and handle exceptions.
"""
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.storage, path, prefixed_path, source_storage):
return False
except Exception as e:
if settings.debug:
raise
# Ignore errors and let default collectstatic handle copy
self.stdout.write(smart_str(
"Ignored error in Collectfast:\n%s\n--> Continuing using "
"default collectstatic." % e))
self.num_copied_files += 1
return super(Command, self).copy_file(
path, prefixed_path, source_storage)
|
[
"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",
".",
"storage",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"if",
"settings",
".",
"debug",
":",
"raise",
"# Ignore errors and let default collectstatic handle copy",
"self",
".",
"stdout",
".",
"write",
"(",
"smart_str",
"(",
"\"Ignored error in Collectfast:\\n%s\\n--> Continuing using \"",
"\"default collectstatic.\"",
"%",
"e",
")",
")",
"self",
".",
"num_copied_files",
"+=",
"1",
"return",
"super",
"(",
"Command",
",",
"self",
")",
".",
"copy_file",
"(",
"path",
",",
"prefixed_path",
",",
"source_storage",
")"
] |
Determine if file should be copied or not and handle exceptions.
|
[
"Determine",
"if",
"file",
"should",
"be",
"copied",
"or",
"not",
"and",
"handle",
"exceptions",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/management/commands/collectstatic.py#L77-L100
|
14,512
|
antonagestam/collectfast
|
collectfast/management/commands/collectstatic.py
|
Command.copy_file
|
def copy_file(self, path, prefixed_path, source_storage):
"""
Appends path to task queue if threads are enabled, otherwise copies
the file with a blocking call.
"""
args = (path, prefixed_path, source_storage)
if settings.threads:
self.tasks.append(args)
else:
self.do_copy_file(args)
|
python
|
def copy_file(self, path, prefixed_path, source_storage):
"""
Appends path to task queue if threads are enabled, otherwise copies
the file with a blocking call.
"""
args = (path, prefixed_path, source_storage)
if settings.threads:
self.tasks.append(args)
else:
self.do_copy_file(args)
|
[
"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",
")"
] |
Appends path to task queue if threads are enabled, otherwise copies
the file with a blocking call.
|
[
"Appends",
"path",
"to",
"task",
"queue",
"if",
"threads",
"are",
"enabled",
"otherwise",
"copies",
"the",
"file",
"with",
"a",
"blocking",
"call",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/management/commands/collectstatic.py#L102-L111
|
14,513
|
antonagestam/collectfast
|
collectfast/management/commands/collectstatic.py
|
Command.delete_file
|
def delete_file(self, path, prefixed_path, source_storage):
"""
Override delete_file to skip modified time and exists lookups.
"""
if not self.collectfast_enabled:
return super(Command, self).delete_file(
path, prefixed_path, source_storage)
if not self.dry_run:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
else:
self.log("Pretending to delete '%s'" % path)
return True
|
python
|
def delete_file(self, path, prefixed_path, source_storage):
"""
Override delete_file to skip modified time and exists lookups.
"""
if not self.collectfast_enabled:
return super(Command, self).delete_file(
path, prefixed_path, source_storage)
if not self.dry_run:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
else:
self.log("Pretending to delete '%s'" % path)
return True
|
[
"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 '%s'\"",
"%",
"path",
")",
"self",
".",
"storage",
".",
"delete",
"(",
"prefixed_path",
")",
"else",
":",
"self",
".",
"log",
"(",
"\"Pretending to delete '%s'\"",
"%",
"path",
")",
"return",
"True"
] |
Override delete_file to skip modified time and exists lookups.
|
[
"Override",
"delete_file",
"to",
"skip",
"modified",
"time",
"and",
"exists",
"lookups",
"."
] |
fb9d7976da2a2578528fa6f3bbd053ee87475ecb
|
https://github.com/antonagestam/collectfast/blob/fb9d7976da2a2578528fa6f3bbd053ee87475ecb/collectfast/management/commands/collectstatic.py#L113-L125
|
14,514
|
satellogic/telluric
|
telluric/georaster.py
|
join
|
def join(rasters):
"""
This method takes a list of rasters and returns a raster that is constructed of all of them
"""
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_flag_enums
per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])
if per_dataset_mask and nodata is None:
mask_band = 0
return GeoRaster2.from_rasters(rasters, relative_to_vrt=False, nodata=nodata, mask_band=mask_band)
|
python
|
def join(rasters):
"""
This method takes a list of rasters and returns a raster that is constructed of all of them
"""
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_flag_enums
per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])
if per_dataset_mask and nodata is None:
mask_band = 0
return GeoRaster2.from_rasters(rasters, relative_to_vrt=False, nodata=nodata, mask_band=mask_band)
|
[
"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_flag_enums",
"per_dataset_mask",
"=",
"all",
"(",
"[",
"rasterio",
".",
"enums",
".",
"MaskFlags",
".",
"per_dataset",
"in",
"flags",
"for",
"flags",
"in",
"mask_flags",
"]",
")",
"if",
"per_dataset_mask",
"and",
"nodata",
"is",
"None",
":",
"mask_band",
"=",
"0",
"return",
"GeoRaster2",
".",
"from_rasters",
"(",
"rasters",
",",
"relative_to_vrt",
"=",
"False",
",",
"nodata",
"=",
"nodata",
",",
"mask_band",
"=",
"mask_band",
")"
] |
This method takes a list of rasters and returns a raster that is constructed of all of them
|
[
"This",
"method",
"takes",
"a",
"list",
"of",
"rasters",
"and",
"returns",
"a",
"raster",
"that",
"is",
"constructed",
"of",
"all",
"of",
"them"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L95-L109
|
14,515
|
satellogic/telluric
|
telluric/georaster.py
|
merge_all
|
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):
"""Merge a list of rasters, cropping by a region of interest.
There are cases that the roi is not precise enough for this cases one can use,
the upper left corner the shape and crs to precisely define the roi.
When roi is provided the ul_corner, shape and crs are ignored
"""
first_raster = rasters[0]
if roi:
crs = crs or roi.crs
dest_resolution = dest_resolution or _dest_resolution(first_raster, crs)
# Create empty raster
empty = GeoRaster2.empty_from_roi(
roi, resolution=dest_resolution, band_names=first_raster.band_names,
dtype=first_raster.dtype, shape=shape, ul_corner=ul_corner, crs=crs)
# Create a list of single band rasters
all_band_names, projected_rasters = _prepare_rasters(rasters, merge_strategy, empty,
resampling=resampling)
assert len(projected_rasters) == len(rasters)
prepared_rasters = _apply_pixel_strategy(projected_rasters, pixel_strategy)
# Extend the rasters list with only those that have the requested bands
prepared_rasters = _explode_rasters(prepared_rasters, all_band_names)
if all_band_names:
# Merge common bands
prepared_rasters = _merge_common_bands(prepared_rasters)
# Merge all bands
raster = reduce(_stack_bands, prepared_rasters)
return empty.copy_with(image=raster.image, band_names=raster.band_names)
else:
raise ValueError("result contains no bands, use another merge strategy")
|
python
|
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):
"""Merge a list of rasters, cropping by a region of interest.
There are cases that the roi is not precise enough for this cases one can use,
the upper left corner the shape and crs to precisely define the roi.
When roi is provided the ul_corner, shape and crs are ignored
"""
first_raster = rasters[0]
if roi:
crs = crs or roi.crs
dest_resolution = dest_resolution or _dest_resolution(first_raster, crs)
# Create empty raster
empty = GeoRaster2.empty_from_roi(
roi, resolution=dest_resolution, band_names=first_raster.band_names,
dtype=first_raster.dtype, shape=shape, ul_corner=ul_corner, crs=crs)
# Create a list of single band rasters
all_band_names, projected_rasters = _prepare_rasters(rasters, merge_strategy, empty,
resampling=resampling)
assert len(projected_rasters) == len(rasters)
prepared_rasters = _apply_pixel_strategy(projected_rasters, pixel_strategy)
# Extend the rasters list with only those that have the requested bands
prepared_rasters = _explode_rasters(prepared_rasters, all_band_names)
if all_band_names:
# Merge common bands
prepared_rasters = _merge_common_bands(prepared_rasters)
# Merge all bands
raster = reduce(_stack_bands, prepared_rasters)
return empty.copy_with(image=raster.image, band_names=raster.band_names)
else:
raise ValueError("result contains no bands, use another merge strategy")
|
[
"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",
":",
"crs",
"=",
"crs",
"or",
"roi",
".",
"crs",
"dest_resolution",
"=",
"dest_resolution",
"or",
"_dest_resolution",
"(",
"first_raster",
",",
"crs",
")",
"# Create empty raster",
"empty",
"=",
"GeoRaster2",
".",
"empty_from_roi",
"(",
"roi",
",",
"resolution",
"=",
"dest_resolution",
",",
"band_names",
"=",
"first_raster",
".",
"band_names",
",",
"dtype",
"=",
"first_raster",
".",
"dtype",
",",
"shape",
"=",
"shape",
",",
"ul_corner",
"=",
"ul_corner",
",",
"crs",
"=",
"crs",
")",
"# Create a list of single band rasters",
"all_band_names",
",",
"projected_rasters",
"=",
"_prepare_rasters",
"(",
"rasters",
",",
"merge_strategy",
",",
"empty",
",",
"resampling",
"=",
"resampling",
")",
"assert",
"len",
"(",
"projected_rasters",
")",
"==",
"len",
"(",
"rasters",
")",
"prepared_rasters",
"=",
"_apply_pixel_strategy",
"(",
"projected_rasters",
",",
"pixel_strategy",
")",
"# Extend the rasters list with only those that have the requested bands",
"prepared_rasters",
"=",
"_explode_rasters",
"(",
"prepared_rasters",
",",
"all_band_names",
")",
"if",
"all_band_names",
":",
"# Merge common bands",
"prepared_rasters",
"=",
"_merge_common_bands",
"(",
"prepared_rasters",
")",
"# Merge all bands",
"raster",
"=",
"reduce",
"(",
"_stack_bands",
",",
"prepared_rasters",
")",
"return",
"empty",
".",
"copy_with",
"(",
"image",
"=",
"raster",
".",
"image",
",",
"band_names",
"=",
"raster",
".",
"band_names",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"result contains no bands, use another merge strategy\"",
")"
] |
Merge a list of rasters, cropping by a region of interest.
There are cases that the roi is not precise enough for this cases one can use,
the upper left corner the shape and crs to precisely define the roi.
When roi is provided the ul_corner, shape and crs are ignored
|
[
"Merge",
"a",
"list",
"of",
"rasters",
"cropping",
"by",
"a",
"region",
"of",
"interest",
".",
"There",
"are",
"cases",
"that",
"the",
"roi",
"is",
"not",
"precise",
"enough",
"for",
"this",
"cases",
"one",
"can",
"use",
"the",
"upper",
"left",
"corner",
"the",
"shape",
"and",
"crs",
"to",
"precisely",
"define",
"the",
"roi",
".",
"When",
"roi",
"is",
"provided",
"the",
"ul_corner",
"shape",
"and",
"crs",
"are",
"ignored"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L120-L161
|
14,516
|
satellogic/telluric
|
telluric/georaster.py
|
_merge_common_bands
|
def _merge_common_bands(rasters):
# type: (List[_Raster]) -> List[_Raster]
"""Combine the common bands.
"""
# 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: List[_Raster]
for band_name, rasters_group in groupby(sorted(rasters, key=key), key=key):
rasters_final.append(reduce(_fill_pixels, rasters_group))
return rasters_final
|
python
|
def _merge_common_bands(rasters):
# type: (List[_Raster]) -> List[_Raster]
"""Combine the common bands.
"""
# 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: List[_Raster]
for band_name, rasters_group in groupby(sorted(rasters, key=key), key=key):
rasters_final.append(reduce(_fill_pixels, rasters_group))
return rasters_final
|
[
"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: List[_Raster]",
"for",
"band_name",
",",
"rasters_group",
"in",
"groupby",
"(",
"sorted",
"(",
"rasters",
",",
"key",
"=",
"key",
")",
",",
"key",
"=",
"key",
")",
":",
"rasters_final",
".",
"append",
"(",
"reduce",
"(",
"_fill_pixels",
",",
"rasters_group",
")",
")",
"return",
"rasters_final"
] |
Combine the common bands.
|
[
"Combine",
"the",
"common",
"bands",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L197-L212
|
14,517
|
satellogic/telluric
|
telluric/georaster.py
|
_explode_raster
|
def _explode_raster(raster, band_names=[]):
# type: (_Raster, Iterable[str]) -> List[_Raster]
"""Splits a raster into multiband rasters.
"""
# 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
else:
band_names = list(IndexedSet(raster.band_names).intersection(band_names))
return [_Raster(image=raster.bands_data([band_name]), band_names=[band_name]) for band_name in band_names]
|
python
|
def _explode_raster(raster, band_names=[]):
# type: (_Raster, Iterable[str]) -> List[_Raster]
"""Splits a raster into multiband rasters.
"""
# 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
else:
band_names = list(IndexedSet(raster.band_names).intersection(band_names))
return [_Raster(image=raster.bands_data([band_name]), band_names=[band_name]) for band_name in band_names]
|
[
"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",
"else",
":",
"band_names",
"=",
"list",
"(",
"IndexedSet",
"(",
"raster",
".",
"band_names",
")",
".",
"intersection",
"(",
"band_names",
")",
")",
"return",
"[",
"_Raster",
"(",
"image",
"=",
"raster",
".",
"bands_data",
"(",
"[",
"band_name",
"]",
")",
",",
"band_names",
"=",
"[",
"band_name",
"]",
")",
"for",
"band_name",
"in",
"band_names",
"]"
] |
Splits a raster into multiband rasters.
|
[
"Splits",
"a",
"raster",
"into",
"multiband",
"rasters",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L244-L256
|
14,518
|
satellogic/telluric
|
telluric/georaster.py
|
_fill_pixels
|
def _fill_pixels(one, other):
# type: (_Raster, _Raster) -> _Raster
"""Merges two single band rasters with the same band by filling the pixels according to depth.
"""
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" raster or just None.
# The problem with the former is that GeoRaster2 expects a 2D or 3D
# numpy array, so there is no obvious way to signal that this raster
# has no bands. Also, returning a (1, 1, 0) numpy array is useless
# for future concatenation, so the expected shape should be used
# instead. The problem with the latter is that it breaks concatenation
# anyway and requires special attention. Suggestions welcome.
if one.band_names != other.band_names:
raise ValueError("rasters have no bands in common, use another merge strategy")
new_image = one.image.copy()
other_image = other.image
# The values that I want to mask are the ones that:
# * Were already masked in the other array, _or_
# * Were already unmasked in the one array, so I don't overwrite them
other_values_mask = (np.ma.getmaskarray(other_image)[0] | (~np.ma.getmaskarray(one.image)[0]))
# Reshape the mask to fit the future array
other_values_mask = other_values_mask[None, ...]
# Overwrite the values that I don't want to mask
new_image[~other_values_mask] = other_image[~other_values_mask]
# In other words, the values that I wanted to write are the ones that:
# * Were already masked in the one array, _and_
# * Were not masked in the other array
# The reason for using the inverted form is to retain the semantics
# of "masked=True" that apply for masked arrays. The same logic
# could be written, using the De Morgan's laws, as
# other_values_mask = (one.image.mask[0] & (~other_image.mask[0])
# other_values_mask = other_values_mask[None, ...]
# new_image[other_values_mask] = other_image[other_values_mask]
# but here the word "mask" does not mean the same as in masked arrays.
return _Raster(image=new_image, band_names=one.band_names)
|
python
|
def _fill_pixels(one, other):
# type: (_Raster, _Raster) -> _Raster
"""Merges two single band rasters with the same band by filling the pixels according to depth.
"""
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" raster or just None.
# The problem with the former is that GeoRaster2 expects a 2D or 3D
# numpy array, so there is no obvious way to signal that this raster
# has no bands. Also, returning a (1, 1, 0) numpy array is useless
# for future concatenation, so the expected shape should be used
# instead. The problem with the latter is that it breaks concatenation
# anyway and requires special attention. Suggestions welcome.
if one.band_names != other.band_names:
raise ValueError("rasters have no bands in common, use another merge strategy")
new_image = one.image.copy()
other_image = other.image
# The values that I want to mask are the ones that:
# * Were already masked in the other array, _or_
# * Were already unmasked in the one array, so I don't overwrite them
other_values_mask = (np.ma.getmaskarray(other_image)[0] | (~np.ma.getmaskarray(one.image)[0]))
# Reshape the mask to fit the future array
other_values_mask = other_values_mask[None, ...]
# Overwrite the values that I don't want to mask
new_image[~other_values_mask] = other_image[~other_values_mask]
# In other words, the values that I wanted to write are the ones that:
# * Were already masked in the one array, _and_
# * Were not masked in the other array
# The reason for using the inverted form is to retain the semantics
# of "masked=True" that apply for masked arrays. The same logic
# could be written, using the De Morgan's laws, as
# other_values_mask = (one.image.mask[0] & (~other_image.mask[0])
# other_values_mask = other_values_mask[None, ...]
# new_image[other_values_mask] = other_image[other_values_mask]
# but here the word "mask" does not mean the same as in masked arrays.
return _Raster(image=new_image, band_names=one.band_names)
|
[
"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\" raster or just None.",
"# The problem with the former is that GeoRaster2 expects a 2D or 3D",
"# numpy array, so there is no obvious way to signal that this raster",
"# has no bands. Also, returning a (1, 1, 0) numpy array is useless",
"# for future concatenation, so the expected shape should be used",
"# instead. The problem with the latter is that it breaks concatenation",
"# anyway and requires special attention. Suggestions welcome.",
"if",
"one",
".",
"band_names",
"!=",
"other",
".",
"band_names",
":",
"raise",
"ValueError",
"(",
"\"rasters have no bands in common, use another merge strategy\"",
")",
"new_image",
"=",
"one",
".",
"image",
".",
"copy",
"(",
")",
"other_image",
"=",
"other",
".",
"image",
"# The values that I want to mask are the ones that:",
"# * Were already masked in the other array, _or_",
"# * Were already unmasked in the one array, so I don't overwrite them",
"other_values_mask",
"=",
"(",
"np",
".",
"ma",
".",
"getmaskarray",
"(",
"other_image",
")",
"[",
"0",
"]",
"|",
"(",
"~",
"np",
".",
"ma",
".",
"getmaskarray",
"(",
"one",
".",
"image",
")",
"[",
"0",
"]",
")",
")",
"# Reshape the mask to fit the future array",
"other_values_mask",
"=",
"other_values_mask",
"[",
"None",
",",
"...",
"]",
"# Overwrite the values that I don't want to mask",
"new_image",
"[",
"~",
"other_values_mask",
"]",
"=",
"other_image",
"[",
"~",
"other_values_mask",
"]",
"# In other words, the values that I wanted to write are the ones that:",
"# * Were already masked in the one array, _and_",
"# * Were not masked in the other array",
"# The reason for using the inverted form is to retain the semantics",
"# of \"masked=True\" that apply for masked arrays. The same logic",
"# could be written, using the De Morgan's laws, as",
"# other_values_mask = (one.image.mask[0] & (~other_image.mask[0])",
"# other_values_mask = other_values_mask[None, ...]",
"# new_image[other_values_mask] = other_image[other_values_mask]",
"# but here the word \"mask\" does not mean the same as in masked arrays.",
"return",
"_Raster",
"(",
"image",
"=",
"new_image",
",",
"band_names",
"=",
"one",
".",
"band_names",
")"
] |
Merges two single band rasters with the same band by filling the pixels according to depth.
|
[
"Merges",
"two",
"single",
"band",
"rasters",
"with",
"the",
"same",
"band",
"by",
"filling",
"the",
"pixels",
"according",
"to",
"depth",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L286-L329
|
14,519
|
satellogic/telluric
|
telluric/georaster.py
|
_stack_bands
|
def _stack_bands(one, other):
# type: (_Raster, _Raster) -> _Raster
"""Merges two rasters with non overlapping bands by stacking the bands.
"""
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 ValueError("rasters have the same bands, use another merge strategy")
# Apply "or" to the mask in the same way rasterio does, see
# https://mapbox.github.io/rasterio/topics/masks.html#dataset-masks
# In other words, mask the values that are already masked in either
# of the two rasters, since one mask per band is not supported
new_mask = np.ma.getmaskarray(one.image)[0] | np.ma.getmaskarray(other.image)[0]
# Concatenate the data along the band axis and apply the mask
new_image = np.ma.masked_array(
np.concatenate([
one.image.data,
other.image.data
]),
mask=[new_mask] * (one.image.shape[0] + other.image.shape[0])
)
new_bands = one.band_names + other.band_names
# We don't copy image and mask here, due to performance issues,
# this output should not use without eventually being copied
# In this context we are copying the object in the end of merge_all merge_first and merge
return _Raster(image=new_image, band_names=new_bands)
|
python
|
def _stack_bands(one, other):
# type: (_Raster, _Raster) -> _Raster
"""Merges two rasters with non overlapping bands by stacking the bands.
"""
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 ValueError("rasters have the same bands, use another merge strategy")
# Apply "or" to the mask in the same way rasterio does, see
# https://mapbox.github.io/rasterio/topics/masks.html#dataset-masks
# In other words, mask the values that are already masked in either
# of the two rasters, since one mask per band is not supported
new_mask = np.ma.getmaskarray(one.image)[0] | np.ma.getmaskarray(other.image)[0]
# Concatenate the data along the band axis and apply the mask
new_image = np.ma.masked_array(
np.concatenate([
one.image.data,
other.image.data
]),
mask=[new_mask] * (one.image.shape[0] + other.image.shape[0])
)
new_bands = one.band_names + other.band_names
# We don't copy image and mask here, due to performance issues,
# this output should not use without eventually being copied
# In this context we are copying the object in the end of merge_all merge_first and merge
return _Raster(image=new_image, band_names=new_bands)
|
[
"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",
"ValueError",
"(",
"\"rasters have the same bands, use another merge strategy\"",
")",
"# Apply \"or\" to the mask in the same way rasterio does, see",
"# https://mapbox.github.io/rasterio/topics/masks.html#dataset-masks",
"# In other words, mask the values that are already masked in either",
"# of the two rasters, since one mask per band is not supported",
"new_mask",
"=",
"np",
".",
"ma",
".",
"getmaskarray",
"(",
"one",
".",
"image",
")",
"[",
"0",
"]",
"|",
"np",
".",
"ma",
".",
"getmaskarray",
"(",
"other",
".",
"image",
")",
"[",
"0",
"]",
"# Concatenate the data along the band axis and apply the mask",
"new_image",
"=",
"np",
".",
"ma",
".",
"masked_array",
"(",
"np",
".",
"concatenate",
"(",
"[",
"one",
".",
"image",
".",
"data",
",",
"other",
".",
"image",
".",
"data",
"]",
")",
",",
"mask",
"=",
"[",
"new_mask",
"]",
"*",
"(",
"one",
".",
"image",
".",
"shape",
"[",
"0",
"]",
"+",
"other",
".",
"image",
".",
"shape",
"[",
"0",
"]",
")",
")",
"new_bands",
"=",
"one",
".",
"band_names",
"+",
"other",
".",
"band_names",
"# We don't copy image and mask here, due to performance issues,",
"# this output should not use without eventually being copied",
"# In this context we are copying the object in the end of merge_all merge_first and merge",
"return",
"_Raster",
"(",
"image",
"=",
"new_image",
",",
"band_names",
"=",
"new_bands",
")"
] |
Merges two rasters with non overlapping bands by stacking the bands.
|
[
"Merges",
"two",
"rasters",
"with",
"non",
"overlapping",
"bands",
"by",
"stacking",
"the",
"bands",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L332-L362
|
14,520
|
satellogic/telluric
|
telluric/georaster.py
|
merge_two
|
def merge_two(one, other, merge_strategy=MergeStrategy.UNION, silent=False, pixel_strategy=PixelStrategy.FIRST):
# type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrategy) -> GeoRaster2
"""Merge two rasters into one.
Parameters
----------
one : GeoRaster2
Left raster to merge.
other : GeoRaster2
Right raster to merge.
merge_strategy : MergeStrategy, optional
Merge strategy, from :py:data:`telluric.georaster.MergeStrategy` (default to "union").
silent : bool, optional
Whether to raise errors or return some result, default to False (raise errors).
pixel_strategy: PixelStrategy, optional
Pixel strategy, from :py:data:`telluric.georaster.PixelStrategy` (default to "top").
Returns
-------
GeoRaster2
"""
other_res = _prepare_other_raster(one, other)
if other_res is None:
if silent:
return one
else:
raise ValueError("rasters do not intersect")
else:
other = other.copy_with(image=other_res.image, band_names=other_res.band_names) # To make MyPy happy
# Create a list of single band rasters
# Cropping won't happen twice, since other was already cropped
all_band_names, projected_rasters = _prepare_rasters([other], merge_strategy, first=one)
if not all_band_names and not silent:
raise ValueError("rasters have no bands in common, use another merge strategy")
prepared_rasters = _apply_pixel_strategy(projected_rasters, pixel_strategy)
prepared_rasters = _explode_rasters(prepared_rasters, all_band_names)
# Merge common bands
prepared_rasters = _merge_common_bands(_explode_raster(one, all_band_names) + prepared_rasters)
# Merge all bands
raster = reduce(_stack_bands, prepared_rasters)
return one.copy_with(image=raster.image, band_names=raster.band_names)
|
python
|
def merge_two(one, other, merge_strategy=MergeStrategy.UNION, silent=False, pixel_strategy=PixelStrategy.FIRST):
# type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrategy) -> GeoRaster2
"""Merge two rasters into one.
Parameters
----------
one : GeoRaster2
Left raster to merge.
other : GeoRaster2
Right raster to merge.
merge_strategy : MergeStrategy, optional
Merge strategy, from :py:data:`telluric.georaster.MergeStrategy` (default to "union").
silent : bool, optional
Whether to raise errors or return some result, default to False (raise errors).
pixel_strategy: PixelStrategy, optional
Pixel strategy, from :py:data:`telluric.georaster.PixelStrategy` (default to "top").
Returns
-------
GeoRaster2
"""
other_res = _prepare_other_raster(one, other)
if other_res is None:
if silent:
return one
else:
raise ValueError("rasters do not intersect")
else:
other = other.copy_with(image=other_res.image, band_names=other_res.band_names) # To make MyPy happy
# Create a list of single band rasters
# Cropping won't happen twice, since other was already cropped
all_band_names, projected_rasters = _prepare_rasters([other], merge_strategy, first=one)
if not all_band_names and not silent:
raise ValueError("rasters have no bands in common, use another merge strategy")
prepared_rasters = _apply_pixel_strategy(projected_rasters, pixel_strategy)
prepared_rasters = _explode_rasters(prepared_rasters, all_band_names)
# Merge common bands
prepared_rasters = _merge_common_bands(_explode_raster(one, all_band_names) + prepared_rasters)
# Merge all bands
raster = reduce(_stack_bands, prepared_rasters)
return one.copy_with(image=raster.image, band_names=raster.band_names)
|
[
"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",
"None",
":",
"if",
"silent",
":",
"return",
"one",
"else",
":",
"raise",
"ValueError",
"(",
"\"rasters do not intersect\"",
")",
"else",
":",
"other",
"=",
"other",
".",
"copy_with",
"(",
"image",
"=",
"other_res",
".",
"image",
",",
"band_names",
"=",
"other_res",
".",
"band_names",
")",
"# To make MyPy happy",
"# Create a list of single band rasters",
"# Cropping won't happen twice, since other was already cropped",
"all_band_names",
",",
"projected_rasters",
"=",
"_prepare_rasters",
"(",
"[",
"other",
"]",
",",
"merge_strategy",
",",
"first",
"=",
"one",
")",
"if",
"not",
"all_band_names",
"and",
"not",
"silent",
":",
"raise",
"ValueError",
"(",
"\"rasters have no bands in common, use another merge strategy\"",
")",
"prepared_rasters",
"=",
"_apply_pixel_strategy",
"(",
"projected_rasters",
",",
"pixel_strategy",
")",
"prepared_rasters",
"=",
"_explode_rasters",
"(",
"prepared_rasters",
",",
"all_band_names",
")",
"# Merge common bands",
"prepared_rasters",
"=",
"_merge_common_bands",
"(",
"_explode_raster",
"(",
"one",
",",
"all_band_names",
")",
"+",
"prepared_rasters",
")",
"# Merge all bands",
"raster",
"=",
"reduce",
"(",
"_stack_bands",
",",
"prepared_rasters",
")",
"return",
"one",
".",
"copy_with",
"(",
"image",
"=",
"raster",
".",
"image",
",",
"band_names",
"=",
"raster",
".",
"band_names",
")"
] |
Merge two rasters into one.
Parameters
----------
one : GeoRaster2
Left raster to merge.
other : GeoRaster2
Right raster to merge.
merge_strategy : MergeStrategy, optional
Merge strategy, from :py:data:`telluric.georaster.MergeStrategy` (default to "union").
silent : bool, optional
Whether to raise errors or return some result, default to False (raise errors).
pixel_strategy: PixelStrategy, optional
Pixel strategy, from :py:data:`telluric.georaster.PixelStrategy` (default to "top").
Returns
-------
GeoRaster2
|
[
"Merge",
"two",
"rasters",
"into",
"one",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L365-L414
|
14,521
|
satellogic/telluric
|
telluric/georaster.py
|
_Raster._set_image
|
def _set_image(self, image, nodata=None):
"""
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
"""
# 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)
else:
raise GeoRaster2NotImplementedError('only ndarray or masked array supported, got %s' % type(image))
# make sure array is 3d:
if len(masked.shape) == 3:
self._image = masked
elif len(masked.shape) == 2:
self._image = masked[np.newaxis, :, :]
else:
raise GeoRaster2Error('expected 2d or 3d image, got shape=%s' % masked.shape)
# update shape
if self._shape is None:
self._set_shape(self._image.shape)
self._image_after_load_validations()
if self._image_readonly:
self._image.setflags(write=0)
|
python
|
def _set_image(self, image, nodata=None):
"""
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
"""
# 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)
else:
raise GeoRaster2NotImplementedError('only ndarray or masked array supported, got %s' % type(image))
# make sure array is 3d:
if len(masked.shape) == 3:
self._image = masked
elif len(masked.shape) == 2:
self._image = masked[np.newaxis, :, :]
else:
raise GeoRaster2Error('expected 2d or 3d image, got shape=%s' % masked.shape)
# update shape
if self._shape is None:
self._set_shape(self._image.shape)
self._image_after_load_validations()
if self._image_readonly:
self._image.setflags(write=0)
|
[
"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",
")",
"else",
":",
"raise",
"GeoRaster2NotImplementedError",
"(",
"'only ndarray or masked array supported, got %s'",
"%",
"type",
"(",
"image",
")",
")",
"# make sure array is 3d:",
"if",
"len",
"(",
"masked",
".",
"shape",
")",
"==",
"3",
":",
"self",
".",
"_image",
"=",
"masked",
"elif",
"len",
"(",
"masked",
".",
"shape",
")",
"==",
"2",
":",
"self",
".",
"_image",
"=",
"masked",
"[",
"np",
".",
"newaxis",
",",
":",
",",
":",
"]",
"else",
":",
"raise",
"GeoRaster2Error",
"(",
"'expected 2d or 3d image, got shape=%s'",
"%",
"masked",
".",
"shape",
")",
"# update shape",
"if",
"self",
".",
"_shape",
"is",
"None",
":",
"self",
".",
"_set_shape",
"(",
"self",
".",
"_image",
".",
"shape",
")",
"self",
".",
"_image_after_load_validations",
"(",
")",
"if",
"self",
".",
"_image_readonly",
":",
"self",
".",
"_image",
".",
"setflags",
"(",
"write",
"=",
"0",
")"
] |
Set self._image.
:param image: supported: np.ma.array, np.array, TODO: PIL image
:param nodata: if provided image is array (not masked array), treat pixels with value=nodata as nodata
:return:
|
[
"Set",
"self",
".",
"_image",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L467-L497
|
14,522
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.from_wms
|
def from_wms(cls, filename, vector, resolution, destination_file=None):
"""Create georaster from the web service definition file."""
doc = wms_vrt(filename,
bounds=vector,
resolution=resolution).tostring()
filename = cls._save_to_destination_file(doc, destination_file)
return GeoRaster2.open(filename)
|
python
|
def from_wms(cls, filename, vector, resolution, destination_file=None):
"""Create georaster from the web service definition file."""
doc = wms_vrt(filename,
bounds=vector,
resolution=resolution).tostring()
filename = cls._save_to_destination_file(doc, destination_file)
return GeoRaster2.open(filename)
|
[
"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_file",
")",
"return",
"GeoRaster2",
".",
"open",
"(",
"filename",
")"
] |
Create georaster from the web service definition file.
|
[
"Create",
"georaster",
"from",
"the",
"web",
"service",
"definition",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L626-L632
|
14,523
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.from_rasters
|
def from_rasters(cls, rasters, relative_to_vrt=True, destination_file=None, nodata=None, mask_band=None):
"""Create georaster out of a list of rasters."""
if isinstance(rasters, list):
doc = raster_list_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
else:
doc = raster_collection_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
filename = cls._save_to_destination_file(doc, destination_file)
return GeoRaster2.open(filename)
|
python
|
def from_rasters(cls, rasters, relative_to_vrt=True, destination_file=None, nodata=None, mask_band=None):
"""Create georaster out of a list of rasters."""
if isinstance(rasters, list):
doc = raster_list_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
else:
doc = raster_collection_vrt(rasters, relative_to_vrt, nodata, mask_band).tostring()
filename = cls._save_to_destination_file(doc, destination_file)
return GeoRaster2.open(filename)
|
[
"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",
"=",
"raster_collection_vrt",
"(",
"rasters",
",",
"relative_to_vrt",
",",
"nodata",
",",
"mask_band",
")",
".",
"tostring",
"(",
")",
"filename",
"=",
"cls",
".",
"_save_to_destination_file",
"(",
"doc",
",",
"destination_file",
")",
"return",
"GeoRaster2",
".",
"open",
"(",
"filename",
")"
] |
Create georaster out of a list of rasters.
|
[
"Create",
"georaster",
"out",
"of",
"a",
"list",
"of",
"rasters",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L635-L642
|
14,524
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.open
|
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):
"""
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..]
:param lazy_load: if True - do not load anything
:return: GeoRaster2
"""
if mutable:
geo_raster = MutableGeoRaster(filename=filename, band_names=band_names, **kwargs)
else:
geo_raster = cls(filename=filename, band_names=band_names, **kwargs)
if not lazy_load:
geo_raster._populate_from_rasterio_object(read_image=True)
return geo_raster
|
python
|
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs):
"""
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..]
:param lazy_load: if True - do not load anything
:return: GeoRaster2
"""
if mutable:
geo_raster = MutableGeoRaster(filename=filename, band_names=band_names, **kwargs)
else:
geo_raster = cls(filename=filename, band_names=band_names, **kwargs)
if not lazy_load:
geo_raster._populate_from_rasterio_object(read_image=True)
return geo_raster
|
[
"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_names",
"=",
"band_names",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"lazy_load",
":",
"geo_raster",
".",
"_populate_from_rasterio_object",
"(",
"read_image",
"=",
"True",
")",
"return",
"geo_raster"
] |
Read a georaster from a file.
:param filename: url
:param band_names: list of strings, or string.
if None - will try to read from image, otherwise - these will be ['0', ..]
:param lazy_load: if True - do not load anything
:return: GeoRaster2
|
[
"Read",
"a",
"georaster",
"from",
"a",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L645-L661
|
14,525
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.tags
|
def tags(cls, filename, namespace=None):
"""Extract tags from file."""
return cls._raster_opener(filename).tags(ns=namespace)
|
python
|
def tags(cls, filename, namespace=None):
"""Extract tags from file."""
return cls._raster_opener(filename).tags(ns=namespace)
|
[
"def",
"tags",
"(",
"cls",
",",
"filename",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"cls",
".",
"_raster_opener",
"(",
"filename",
")",
".",
"tags",
"(",
"ns",
"=",
"namespace",
")"
] |
Extract tags from file.
|
[
"Extract",
"tags",
"from",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L724-L726
|
14,526
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.image
|
def image(self):
"""Raster bitmap in numpy array."""
if self._image is None:
self._populate_from_rasterio_object(read_image=True)
return self._image
|
python
|
def image(self):
"""Raster bitmap in numpy array."""
if self._image is None:
self._populate_from_rasterio_object(read_image=True)
return self._image
|
[
"def",
"image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_image",
"is",
"None",
":",
"self",
".",
"_populate_from_rasterio_object",
"(",
"read_image",
"=",
"True",
")",
"return",
"self",
".",
"_image"
] |
Raster bitmap in numpy array.
|
[
"Raster",
"bitmap",
"in",
"numpy",
"array",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L729-L733
|
14,527
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.crs
|
def crs(self): # type: () -> CRS
"""Raster crs."""
if self._crs is None:
self._populate_from_rasterio_object(read_image=False)
return self._crs
|
python
|
def crs(self): # type: () -> CRS
"""Raster crs."""
if self._crs is None:
self._populate_from_rasterio_object(read_image=False)
return self._crs
|
[
"def",
"crs",
"(",
"self",
")",
":",
"# type: () -> CRS",
"if",
"self",
".",
"_crs",
"is",
"None",
":",
"self",
".",
"_populate_from_rasterio_object",
"(",
"read_image",
"=",
"False",
")",
"return",
"self",
".",
"_crs"
] |
Raster crs.
|
[
"Raster",
"crs",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L758-L762
|
14,528
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.shape
|
def shape(self):
"""Raster shape."""
if self._shape is None:
self._populate_from_rasterio_object(read_image=False)
return self._shape
|
python
|
def shape(self):
"""Raster shape."""
if self._shape is None:
self._populate_from_rasterio_object(read_image=False)
return self._shape
|
[
"def",
"shape",
"(",
"self",
")",
":",
"if",
"self",
".",
"_shape",
"is",
"None",
":",
"self",
".",
"_populate_from_rasterio_object",
"(",
"read_image",
"=",
"False",
")",
"return",
"self",
".",
"_shape"
] |
Raster shape.
|
[
"Raster",
"shape",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L765-L769
|
14,529
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.source_file
|
def source_file(self):
""" When using open, returns the filename used
"""
if self._filename is None:
self._filename = self._as_in_memory_geotiff()._filename
return self._filename
|
python
|
def source_file(self):
""" When using open, returns the filename used
"""
if self._filename is None:
self._filename = self._as_in_memory_geotiff()._filename
return self._filename
|
[
"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
|
[
"When",
"using",
"open",
"returns",
"the",
"filename",
"used"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L788-L793
|
14,530
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.blockshapes
|
def blockshapes(self):
"""Raster all bands block shape."""
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 be the data array size
self._blockshapes = [(self.height, self.width) for z in range(self.num_bands)]
return self._blockshapes
|
python
|
def blockshapes(self):
"""Raster all bands block shape."""
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 be the data array size
self._blockshapes = [(self.height, self.width) for z in range(self.num_bands)]
return self._blockshapes
|
[
"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 be the data array size",
"self",
".",
"_blockshapes",
"=",
"[",
"(",
"self",
".",
"height",
",",
"self",
".",
"width",
")",
"for",
"z",
"in",
"range",
"(",
"self",
".",
"num_bands",
")",
"]",
"return",
"self",
".",
"_blockshapes"
] |
Raster all bands block shape.
|
[
"Raster",
"all",
"bands",
"block",
"shape",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L822-L830
|
14,531
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.get
|
def get(self, point):
"""
Get the pixel values at the requested point.
:param point: A GeoVector(POINT) with the coordinates of the values to get
:return: numpy array of values
"""
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)]
|
python
|
def get(self, point):
"""
Get the pixel values at the requested point.
:param point: A GeoVector(POINT) with the coordinates of the values to get
:return: numpy array of values
"""
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)]
|
[
"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",
")",
"]"
] |
Get the pixel values at the requested point.
:param point: A GeoVector(POINT) with the coordinates of the values to get
:return: numpy array of values
|
[
"Get",
"the",
"pixel",
"values",
"at",
"the",
"requested",
"point",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L978-L989
|
14,532
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.copy
|
def copy(self, mutable=False):
"""Return a copy of this GeoRaster with no modifications.
Can be use to create a Mutable copy of the GeoRaster"""
if self.not_loaded():
_cls = self.__class__
if mutable:
_cls = MutableGeoRaster
return _cls.open(self._filename)
return self.copy_with(mutable=mutable)
|
python
|
def copy(self, mutable=False):
"""Return a copy of this GeoRaster with no modifications.
Can be use to create a Mutable copy of the GeoRaster"""
if self.not_loaded():
_cls = self.__class__
if mutable:
_cls = MutableGeoRaster
return _cls.open(self._filename)
return self.copy_with(mutable=mutable)
|
[
"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.
Can be use to create a Mutable copy of the GeoRaster
|
[
"Return",
"a",
"copy",
"of",
"this",
"GeoRaster",
"with",
"no",
"modifications",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1198-L1209
|
14,533
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._resize
|
def _resize(self, ratio_x, ratio_y, resampling):
"""Return raster resized by ratio."""
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():
window = rasterio.windows.Window(0, 0, self.width, self.height)
resized_raster = self.get_window(window, xsize=new_width, ysize=new_height, resampling=resampling)
else:
resized_raster = self._reproject(new_width, new_height, dest_affine, resampling=resampling)
return resized_raster
|
python
|
def _resize(self, ratio_x, ratio_y, resampling):
"""Return raster resized by ratio."""
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():
window = rasterio.windows.Window(0, 0, self.width, self.height)
resized_raster = self.get_window(window, xsize=new_width, ysize=new_height, resampling=resampling)
else:
resized_raster = self._reproject(new_width, new_height, dest_affine, resampling=resampling)
return resized_raster
|
[
"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",
"(",
")",
":",
"window",
"=",
"rasterio",
".",
"windows",
".",
"Window",
"(",
"0",
",",
"0",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"resized_raster",
"=",
"self",
".",
"get_window",
"(",
"window",
",",
"xsize",
"=",
"new_width",
",",
"ysize",
"=",
"new_height",
",",
"resampling",
"=",
"resampling",
")",
"else",
":",
"resized_raster",
"=",
"self",
".",
"_reproject",
"(",
"new_width",
",",
"new_height",
",",
"dest_affine",
",",
"resampling",
"=",
"resampling",
")",
"return",
"resized_raster"
] |
Return raster resized by ratio.
|
[
"Return",
"raster",
"resized",
"by",
"ratio",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1277-L1288
|
14,534
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.to_pillow_image
|
def to_pillow_image(self, return_mask=False):
"""Return Pillow. Image, and optionally also mask."""
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.image)
mask = Image.fromarray(np.rollaxis(np.rollaxis(mask, 2), 2).astype(np.uint8)[:, :, 0])
return img, mask
else:
return img
|
python
|
def to_pillow_image(self, return_mask=False):
"""Return Pillow. Image, and optionally also mask."""
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.image)
mask = Image.fromarray(np.rollaxis(np.rollaxis(mask, 2), 2).astype(np.uint8)[:, :, 0])
return img, mask
else:
return img
|
[
"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",
".",
"image",
")",
"mask",
"=",
"Image",
".",
"fromarray",
"(",
"np",
".",
"rollaxis",
"(",
"np",
".",
"rollaxis",
"(",
"mask",
",",
"2",
")",
",",
"2",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"[",
":",
",",
":",
",",
"0",
"]",
")",
"return",
"img",
",",
"mask",
"else",
":",
"return",
"img"
] |
Return Pillow. Image, and optionally also mask.
|
[
"Return",
"Pillow",
".",
"Image",
"and",
"optionally",
"also",
"mask",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1290-L1299
|
14,535
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.from_bytes
|
def from_bytes(cls, image_bytes, affine, crs, band_names=None):
"""Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red'
"""
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_names, str):
band_names = [band_names]
return GeoRaster2(image=roll[:3, :, :], affine=affine, crs=crs, band_names=band_names)
|
python
|
def from_bytes(cls, image_bytes, affine, crs, band_names=None):
"""Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red'
"""
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_names, str):
band_names = [band_names]
return GeoRaster2(image=roll[:3, :, :], affine=affine, crs=crs, band_names=band_names)
|
[
"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_names",
",",
"str",
")",
":",
"band_names",
"=",
"[",
"band_names",
"]",
"return",
"GeoRaster2",
"(",
"image",
"=",
"roll",
"[",
":",
"3",
",",
":",
",",
":",
"]",
",",
"affine",
"=",
"affine",
",",
"crs",
"=",
"crs",
",",
"band_names",
"=",
"band_names",
")"
] |
Create GeoRaster from image BytesIo object.
:param image_bytes: io.BytesIO object
:param affine: rasters affine
:param crs: rasters crs
:param band_names: e.g. ['red', 'blue'] or 'red'
|
[
"Create",
"GeoRaster",
"from",
"image",
"BytesIo",
"object",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1506-L1522
|
14,536
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._repr_html_
|
def _repr_html_(self):
"""Required for jupyter notebook to show raster as an interactive map."""
TileServer.run_tileserver(self, self.footprint())
capture = "raster: %s" % self._filename
mp = TileServer.folium_client(self, self.footprint(), capture=capture)
return mp._repr_html_()
|
python
|
def _repr_html_(self):
"""Required for jupyter notebook to show raster as an interactive map."""
TileServer.run_tileserver(self, self.footprint())
capture = "raster: %s" % self._filename
mp = TileServer.folium_client(self, self.footprint(), capture=capture)
return mp._repr_html_()
|
[
"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.
|
[
"Required",
"for",
"jupyter",
"notebook",
"to",
"show",
"raster",
"as",
"an",
"interactive",
"map",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1524-L1529
|
14,537
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.image_corner
|
def image_corner(self, corner):
"""Return image corner in pixels, as shapely.Point."""
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' else self.height
return Point(x, y)
|
python
|
def image_corner(self, corner):
"""Return image corner in pixels, as shapely.Point."""
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' else self.height
return Point(x, y)
|
[
"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'",
"else",
"self",
".",
"height",
"return",
"Point",
"(",
"x",
",",
"y",
")"
] |
Return image corner in pixels, as shapely.Point.
|
[
"Return",
"image",
"corner",
"in",
"pixels",
"as",
"shapely",
".",
"Point",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1555-L1562
|
14,538
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.center
|
def center(self):
"""Return footprint center in world coordinates, as GeoVector."""
image_center = Point(self.width / 2, self.height / 2)
return self.to_world(image_center)
|
python
|
def center(self):
"""Return footprint center in world coordinates, as GeoVector."""
image_center = Point(self.width / 2, self.height / 2)
return self.to_world(image_center)
|
[
"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.
|
[
"Return",
"footprint",
"center",
"in",
"world",
"coordinates",
"as",
"GeoVector",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1576-L1579
|
14,539
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.bounds
|
def bounds(self):
"""Return image rectangle in pixels, as shapely.Polygon."""
corners = [self.image_corner(corner) for corner in self.corner_types()]
return Polygon([[corner.x, corner.y] for corner in corners])
|
python
|
def bounds(self):
"""Return image rectangle in pixels, as shapely.Polygon."""
corners = [self.image_corner(corner) for corner in self.corner_types()]
return Polygon([[corner.x, corner.y] for corner in corners])
|
[
"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.
|
[
"Return",
"image",
"rectangle",
"in",
"pixels",
"as",
"shapely",
".",
"Polygon",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1581-L1584
|
14,540
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._calc_footprint
|
def _calc_footprint(self):
"""Return rectangle in world coordinates, as GeoVector."""
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 = Polygon(coords)
# TODO use GeoVector.from_bounds
self._footprint = GeoVector(shp, self.crs)
return self._footprint
|
python
|
def _calc_footprint(self):
"""Return rectangle in world coordinates, as GeoVector."""
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 = Polygon(coords)
# TODO use GeoVector.from_bounds
self._footprint = GeoVector(shp, self.crs)
return self._footprint
|
[
"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",
"=",
"Polygon",
"(",
"coords",
")",
"# TODO use GeoVector.from_bounds",
"self",
".",
"_footprint",
"=",
"GeoVector",
"(",
"shp",
",",
"self",
".",
"crs",
")",
"return",
"self",
".",
"_footprint"
] |
Return rectangle in world coordinates, as GeoVector.
|
[
"Return",
"rectangle",
"in",
"world",
"coordinates",
"as",
"GeoVector",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1586-L1597
|
14,541
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.to_raster
|
def to_raster(self, vector):
"""Return the vector in pixel coordinates, as shapely.Geometry."""
return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine)
|
python
|
def to_raster(self, vector):
"""Return the vector in pixel coordinates, as shapely.Geometry."""
return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine)
|
[
"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.
|
[
"Return",
"the",
"vector",
"in",
"pixel",
"coordinates",
"as",
"shapely",
".",
"Geometry",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1611-L1613
|
14,542
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.reduce
|
def reduce(self, op):
"""Reduce the raster to a score, using 'op' operation.
nodata pixels are ignored.
op is currently limited to numpy.ma, e.g. 'mean', 'std' etc
:returns list of per-band values
"""
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
|
python
|
def reduce(self, op):
"""Reduce the raster to a score, using 'op' operation.
nodata pixels are ignored.
op is currently limited to numpy.ma, e.g. 'mean', 'std' etc
:returns list of per-band values
"""
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
|
[
"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.
nodata pixels are ignored.
op is currently limited to numpy.ma, e.g. 'mean', 'std' etc
:returns list of per-band values
|
[
"Reduce",
"the",
"raster",
"to",
"a",
"score",
"using",
"op",
"operation",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1642-L1651
|
14,543
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.mask
|
def mask(self, vector, mask_shape_nodata=False):
"""
Set pixels outside vector as nodata.
:param vector: GeoVector, GeoFeature, FeatureCollection
:param mask_shape_nodata: if True - pixels inside shape are set nodata, if False - outside shape is nodata
:return: GeoRaster2
"""
from telluric.collections import BaseCollection
# crop raster to reduce memory footprint
cropped = self.crop(vector)
if isinstance(vector, BaseCollection):
shapes = [cropped.to_raster(feature) for feature in vector]
else:
shapes = [cropped.to_raster(vector)]
mask = geometry_mask(shapes, (cropped.height, cropped.width), Affine.identity(), invert=mask_shape_nodata)
masked = cropped.deepcopy_with()
masked.image.mask |= mask
return masked
|
python
|
def mask(self, vector, mask_shape_nodata=False):
"""
Set pixels outside vector as nodata.
:param vector: GeoVector, GeoFeature, FeatureCollection
:param mask_shape_nodata: if True - pixels inside shape are set nodata, if False - outside shape is nodata
:return: GeoRaster2
"""
from telluric.collections import BaseCollection
# crop raster to reduce memory footprint
cropped = self.crop(vector)
if isinstance(vector, BaseCollection):
shapes = [cropped.to_raster(feature) for feature in vector]
else:
shapes = [cropped.to_raster(vector)]
mask = geometry_mask(shapes, (cropped.height, cropped.width), Affine.identity(), invert=mask_shape_nodata)
masked = cropped.deepcopy_with()
masked.image.mask |= mask
return masked
|
[
"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",
"=",
"[",
"cropped",
".",
"to_raster",
"(",
"feature",
")",
"for",
"feature",
"in",
"vector",
"]",
"else",
":",
"shapes",
"=",
"[",
"cropped",
".",
"to_raster",
"(",
"vector",
")",
"]",
"mask",
"=",
"geometry_mask",
"(",
"shapes",
",",
"(",
"cropped",
".",
"height",
",",
"cropped",
".",
"width",
")",
",",
"Affine",
".",
"identity",
"(",
")",
",",
"invert",
"=",
"mask_shape_nodata",
")",
"masked",
"=",
"cropped",
".",
"deepcopy_with",
"(",
")",
"masked",
".",
"image",
".",
"mask",
"|=",
"mask",
"return",
"masked"
] |
Set pixels outside vector as nodata.
:param vector: GeoVector, GeoFeature, FeatureCollection
:param mask_shape_nodata: if True - pixels inside shape are set nodata, if False - outside shape is nodata
:return: GeoRaster2
|
[
"Set",
"pixels",
"outside",
"vector",
"as",
"nodata",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1700-L1721
|
14,544
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.mask_by_value
|
def mask_by_value(self, nodata):
"""
Return raster with a mask calculated based on provided value.
Only pixels with value=nodata will be masked.
:param nodata: value of the pixels that should be masked
:return: GeoRaster2
"""
return self.copy_with(image=np.ma.masked_array(self.image.data, mask=self.image.data == nodata))
|
python
|
def mask_by_value(self, nodata):
"""
Return raster with a mask calculated based on provided value.
Only pixels with value=nodata will be masked.
:param nodata: value of the pixels that should be masked
:return: GeoRaster2
"""
return self.copy_with(image=np.ma.masked_array(self.image.data, mask=self.image.data == nodata))
|
[
"def",
"mask_by_value",
"(",
"self",
",",
"nodata",
")",
":",
"return",
"self",
".",
"copy_with",
"(",
"image",
"=",
"np",
".",
"ma",
".",
"masked_array",
"(",
"self",
".",
"image",
".",
"data",
",",
"mask",
"=",
"self",
".",
"image",
".",
"data",
"==",
"nodata",
")",
")"
] |
Return raster with a mask calculated based on provided value.
Only pixels with value=nodata will be masked.
:param nodata: value of the pixels that should be masked
:return: GeoRaster2
|
[
"Return",
"raster",
"with",
"a",
"mask",
"calculated",
"based",
"on",
"provided",
"value",
".",
"Only",
"pixels",
"with",
"value",
"=",
"nodata",
"will",
"be",
"masked",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1723-L1731
|
14,545
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.save_cloud_optimized
|
def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256,
overview_blocksize=256, creation_options=None):
"""Save as Cloud Optimized GeoTiff object to a new file.
:param dest_url: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: dict, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
the list of creation_options can be found here https://www.gdal.org/frmt_gtiff.html
:return: new GeoRaster of the tiled object
"""
src = self # GeoRaster2.open(self._filename)
with tempfile.NamedTemporaryFile(suffix='.tif') as tf:
src.save(tf.name, overviews=False)
convert_to_cog(tf.name, dest_url, resampling, blocksize, overview_blocksize, creation_options)
geotiff = GeoRaster2.open(dest_url)
return geotiff
|
python
|
def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256,
overview_blocksize=256, creation_options=None):
"""Save as Cloud Optimized GeoTiff object to a new file.
:param dest_url: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: dict, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
the list of creation_options can be found here https://www.gdal.org/frmt_gtiff.html
:return: new GeoRaster of the tiled object
"""
src = self # GeoRaster2.open(self._filename)
with tempfile.NamedTemporaryFile(suffix='.tif') as tf:
src.save(tf.name, overviews=False)
convert_to_cog(tf.name, dest_url, resampling, blocksize, overview_blocksize, creation_options)
geotiff = GeoRaster2.open(dest_url)
return geotiff
|
[
"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",
"=",
"'.tif'",
")",
"as",
"tf",
":",
"src",
".",
"save",
"(",
"tf",
".",
"name",
",",
"overviews",
"=",
"False",
")",
"convert_to_cog",
"(",
"tf",
".",
"name",
",",
"dest_url",
",",
"resampling",
",",
"blocksize",
",",
"overview_blocksize",
",",
"creation_options",
")",
"geotiff",
"=",
"GeoRaster2",
".",
"open",
"(",
"dest_url",
")",
"return",
"geotiff"
] |
Save as Cloud Optimized GeoTiff object to a new file.
:param dest_url: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: dict, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
the list of creation_options can be found here https://www.gdal.org/frmt_gtiff.html
:return: new GeoRaster of the tiled object
|
[
"Save",
"as",
"Cloud",
"Optimized",
"GeoTiff",
"object",
"to",
"a",
"new",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1773-L1794
|
14,546
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._get_window_out_shape
|
def _get_window_out_shape(self, bands, window, xsize, ysize):
"""Get the outshape of a window.
this method is only used inside get_window to calculate the out_shape
"""
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 / ysize
xsize = math.ceil(window.width / ratio)
elif xsize is None and ysize is None:
ysize = math.ceil(window.height)
xsize = math.ceil(window.width)
return (len(bands), ysize, xsize)
|
python
|
def _get_window_out_shape(self, bands, window, xsize, ysize):
"""Get the outshape of a window.
this method is only used inside get_window to calculate the out_shape
"""
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 / ysize
xsize = math.ceil(window.width / ratio)
elif xsize is None and ysize is None:
ysize = math.ceil(window.height)
xsize = math.ceil(window.width)
return (len(bands), ysize, xsize)
|
[
"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",
"/",
"ysize",
"xsize",
"=",
"math",
".",
"ceil",
"(",
"window",
".",
"width",
"/",
"ratio",
")",
"elif",
"xsize",
"is",
"None",
"and",
"ysize",
"is",
"None",
":",
"ysize",
"=",
"math",
".",
"ceil",
"(",
"window",
".",
"height",
")",
"xsize",
"=",
"math",
".",
"ceil",
"(",
"window",
".",
"width",
")",
"return",
"(",
"len",
"(",
"bands",
")",
",",
"ysize",
",",
"xsize",
")"
] |
Get the outshape of a window.
this method is only used inside get_window to calculate the out_shape
|
[
"Get",
"the",
"outshape",
"of",
"a",
"window",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1796-L1811
|
14,547
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._read_with_mask
|
def _read_with_mask(raster, masked):
""" returns if we should read from rasterio using the 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
return masked
|
python
|
def _read_with_mask(raster, masked):
""" returns if we should read from rasterio using the 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
return masked
|
[
"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",
"return",
"masked"
] |
returns if we should read from rasterio using the masked
|
[
"returns",
"if",
"we",
"should",
"read",
"from",
"rasterio",
"using",
"the",
"masked"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1814-L1821
|
14,548
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.get_window
|
def get_window(self, window, bands=None,
xsize=None, ysize=None,
resampling=Resampling.cubic, masked=None, affine=None
):
"""Get window from raster.
:param window: requested window
:param bands: list of indices of requested bads, default None which returns all bands
:param xsize: tile x size default None, for full resolution pass None
:param ysize: tile y size default None, for full resolution pass None
:param resampling: which Resampling to use on reading, default Resampling.cubic
:param masked: if True uses the maks, if False doesn't use the mask, if None looks to see if there is a mask,
if mask exists using it, the default None
:return: GeoRaster2 of tile
"""
bands = bands or list(range(1, self.num_bands + 1))
# requested_out_shape and out_shape are different for out of bounds window
out_shape = self._get_window_out_shape(bands, window, xsize, ysize)
try:
read_params = {
"window": window,
"resampling": resampling,
"boundless": True,
"out_shape": out_shape,
}
# to handle get_window / get_tile of in memory rasters
filename = self._raster_backed_by_a_file()._filename
with self._raster_opener(filename) as raster: # type: rasterio.io.DatasetReader
read_params["masked"] = self._read_with_mask(raster, masked)
array = raster.read(bands, **read_params)
nodata = 0 if not np.ma.isMaskedArray(array) else None
affine = affine or self._calculate_new_affine(window, out_shape[2], out_shape[1])
raster = self.copy_with(image=array, affine=affine, nodata=nodata)
return raster
except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_HttpResponseError) as e:
raise GeoRaster2IOError(e)
|
python
|
def get_window(self, window, bands=None,
xsize=None, ysize=None,
resampling=Resampling.cubic, masked=None, affine=None
):
"""Get window from raster.
:param window: requested window
:param bands: list of indices of requested bads, default None which returns all bands
:param xsize: tile x size default None, for full resolution pass None
:param ysize: tile y size default None, for full resolution pass None
:param resampling: which Resampling to use on reading, default Resampling.cubic
:param masked: if True uses the maks, if False doesn't use the mask, if None looks to see if there is a mask,
if mask exists using it, the default None
:return: GeoRaster2 of tile
"""
bands = bands or list(range(1, self.num_bands + 1))
# requested_out_shape and out_shape are different for out of bounds window
out_shape = self._get_window_out_shape(bands, window, xsize, ysize)
try:
read_params = {
"window": window,
"resampling": resampling,
"boundless": True,
"out_shape": out_shape,
}
# to handle get_window / get_tile of in memory rasters
filename = self._raster_backed_by_a_file()._filename
with self._raster_opener(filename) as raster: # type: rasterio.io.DatasetReader
read_params["masked"] = self._read_with_mask(raster, masked)
array = raster.read(bands, **read_params)
nodata = 0 if not np.ma.isMaskedArray(array) else None
affine = affine or self._calculate_new_affine(window, out_shape[2], out_shape[1])
raster = self.copy_with(image=array, affine=affine, nodata=nodata)
return raster
except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_HttpResponseError) as e:
raise GeoRaster2IOError(e)
|
[
"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_shape and out_shape are different for out of bounds window",
"out_shape",
"=",
"self",
".",
"_get_window_out_shape",
"(",
"bands",
",",
"window",
",",
"xsize",
",",
"ysize",
")",
"try",
":",
"read_params",
"=",
"{",
"\"window\"",
":",
"window",
",",
"\"resampling\"",
":",
"resampling",
",",
"\"boundless\"",
":",
"True",
",",
"\"out_shape\"",
":",
"out_shape",
",",
"}",
"# to handle get_window / get_tile of in memory rasters",
"filename",
"=",
"self",
".",
"_raster_backed_by_a_file",
"(",
")",
".",
"_filename",
"with",
"self",
".",
"_raster_opener",
"(",
"filename",
")",
"as",
"raster",
":",
"# type: rasterio.io.DatasetReader",
"read_params",
"[",
"\"masked\"",
"]",
"=",
"self",
".",
"_read_with_mask",
"(",
"raster",
",",
"masked",
")",
"array",
"=",
"raster",
".",
"read",
"(",
"bands",
",",
"*",
"*",
"read_params",
")",
"nodata",
"=",
"0",
"if",
"not",
"np",
".",
"ma",
".",
"isMaskedArray",
"(",
"array",
")",
"else",
"None",
"affine",
"=",
"affine",
"or",
"self",
".",
"_calculate_new_affine",
"(",
"window",
",",
"out_shape",
"[",
"2",
"]",
",",
"out_shape",
"[",
"1",
"]",
")",
"raster",
"=",
"self",
".",
"copy_with",
"(",
"image",
"=",
"array",
",",
"affine",
"=",
"affine",
",",
"nodata",
"=",
"nodata",
")",
"return",
"raster",
"except",
"(",
"rasterio",
".",
"errors",
".",
"RasterioIOError",
",",
"rasterio",
".",
"_err",
".",
"CPLE_HttpResponseError",
")",
"as",
"e",
":",
"raise",
"GeoRaster2IOError",
"(",
"e",
")"
] |
Get window from raster.
:param window: requested window
:param bands: list of indices of requested bads, default None which returns all bands
:param xsize: tile x size default None, for full resolution pass None
:param ysize: tile y size default None, for full resolution pass None
:param resampling: which Resampling to use on reading, default Resampling.cubic
:param masked: if True uses the maks, if False doesn't use the mask, if None looks to see if there is a mask,
if mask exists using it, the default None
:return: GeoRaster2 of tile
|
[
"Get",
"window",
"from",
"raster",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1823-L1862
|
14,549
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2._get_tile_when_web_mercator_crs
|
def _get_tile_when_web_mercator_crs(self, x_tile, y_tile, zoom,
bands=None, masked=None,
resampling=Resampling.cubic):
""" The reason we want to treat this case in a special way
is that there are cases where the rater is aligned so you need to be precise
on which raster you want
"""
roi = GeoVector.from_xyz(x_tile, y_tile, zoom)
coordinates = roi.get_bounds(WEB_MERCATOR_CRS)
window = self._window(coordinates, to_round=False)
bands = bands or list(range(1, self.num_bands + 1))
# we know the affine the result should produce becuase we know where
# it is located by the xyz, therefore we calculate it here
ratio = MERCATOR_RESOLUTION_MAPPING[zoom] / self.resolution()
# the affine should be calculated before rounding the window values
affine = self.window_transform(window)
affine = affine * Affine.scale(ratio, ratio)
window = Window(round(window.col_off),
round(window.row_off),
round(window.width),
round(window.height))
return self.get_window(window, bands=bands, xsize=256, ysize=256, masked=masked, affine=affine)
|
python
|
def _get_tile_when_web_mercator_crs(self, x_tile, y_tile, zoom,
bands=None, masked=None,
resampling=Resampling.cubic):
""" The reason we want to treat this case in a special way
is that there are cases where the rater is aligned so you need to be precise
on which raster you want
"""
roi = GeoVector.from_xyz(x_tile, y_tile, zoom)
coordinates = roi.get_bounds(WEB_MERCATOR_CRS)
window = self._window(coordinates, to_round=False)
bands = bands or list(range(1, self.num_bands + 1))
# we know the affine the result should produce becuase we know where
# it is located by the xyz, therefore we calculate it here
ratio = MERCATOR_RESOLUTION_MAPPING[zoom] / self.resolution()
# the affine should be calculated before rounding the window values
affine = self.window_transform(window)
affine = affine * Affine.scale(ratio, ratio)
window = Window(round(window.col_off),
round(window.row_off),
round(window.width),
round(window.height))
return self.get_window(window, bands=bands, xsize=256, ysize=256, masked=masked, affine=affine)
|
[
"def",
"_get_tile_when_web_mercator_crs",
"(",
"self",
",",
"x_tile",
",",
"y_tile",
",",
"zoom",
",",
"bands",
"=",
"None",
",",
"masked",
"=",
"None",
",",
"resampling",
"=",
"Resampling",
".",
"cubic",
")",
":",
"roi",
"=",
"GeoVector",
".",
"from_xyz",
"(",
"x_tile",
",",
"y_tile",
",",
"zoom",
")",
"coordinates",
"=",
"roi",
".",
"get_bounds",
"(",
"WEB_MERCATOR_CRS",
")",
"window",
"=",
"self",
".",
"_window",
"(",
"coordinates",
",",
"to_round",
"=",
"False",
")",
"bands",
"=",
"bands",
"or",
"list",
"(",
"range",
"(",
"1",
",",
"self",
".",
"num_bands",
"+",
"1",
")",
")",
"# we know the affine the result should produce becuase we know where",
"# it is located by the xyz, therefore we calculate it here",
"ratio",
"=",
"MERCATOR_RESOLUTION_MAPPING",
"[",
"zoom",
"]",
"/",
"self",
".",
"resolution",
"(",
")",
"# the affine should be calculated before rounding the window values",
"affine",
"=",
"self",
".",
"window_transform",
"(",
"window",
")",
"affine",
"=",
"affine",
"*",
"Affine",
".",
"scale",
"(",
"ratio",
",",
"ratio",
")",
"window",
"=",
"Window",
"(",
"round",
"(",
"window",
".",
"col_off",
")",
",",
"round",
"(",
"window",
".",
"row_off",
")",
",",
"round",
"(",
"window",
".",
"width",
")",
",",
"round",
"(",
"window",
".",
"height",
")",
")",
"return",
"self",
".",
"get_window",
"(",
"window",
",",
"bands",
"=",
"bands",
",",
"xsize",
"=",
"256",
",",
"ysize",
"=",
"256",
",",
"masked",
"=",
"masked",
",",
"affine",
"=",
"affine",
")"
] |
The reason we want to treat this case in a special way
is that there are cases where the rater is aligned so you need to be precise
on which raster you want
|
[
"The",
"reason",
"we",
"want",
"to",
"treat",
"this",
"case",
"in",
"a",
"special",
"way",
"is",
"that",
"there",
"are",
"cases",
"where",
"the",
"rater",
"is",
"aligned",
"so",
"you",
"need",
"to",
"be",
"precise",
"on",
"which",
"raster",
"you",
"want"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1864-L1887
|
14,550
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.get_tile
|
def get_tile(self, x_tile, y_tile, zoom,
bands=None, masked=None, resampling=Resampling.cubic):
"""Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indices of requested bands, default None which returns all bands
:param resampling: reprojection resampling method, default `cubic`
:return: GeoRaster2 of tile in WEB_MERCATOR_CRS
You can use TELLURIC_GET_TILE_BUFFER env variable to control the number of pixels surrounding
the vector you should fetch when using this method on a raster that is not in WEB_MERCATOR_CRS
default to 10
"""
if self.crs == WEB_MERCATOR_CRS:
return self._get_tile_when_web_mercator_crs(x_tile, y_tile, zoom, bands, masked, resampling)
roi = GeoVector.from_xyz(x_tile, y_tile, zoom)
left, bottom, right, top = roi.get_bounds(WEB_MERCATOR_CRS)
new_affine = rasterio.warp.calculate_default_transform(WEB_MERCATOR_CRS, self.crs,
256, 256, left, bottom, right, top)[0]
new_resolution = resolution_from_affine(new_affine)
buffer_ratio = int(os.environ.get("TELLURIC_GET_TILE_BUFFER", 10))
roi_buffer = roi.buffer(math.sqrt(roi.area * buffer_ratio / 100))
raster = self.crop(roi_buffer, resolution=new_resolution, masked=masked,
bands=bands, resampling=resampling)
raster = raster.reproject(dst_crs=WEB_MERCATOR_CRS, resolution=MERCATOR_RESOLUTION_MAPPING[zoom],
dst_bounds=roi_buffer.get_bounds(WEB_MERCATOR_CRS),
resampling=Resampling.cubic_spline)
# raster = raster.get_tile(x_tile, y_tile, zoom, bands, masked, resampling)
raster = raster.crop(roi).resize(dest_width=256, dest_height=256)
return raster
|
python
|
def get_tile(self, x_tile, y_tile, zoom,
bands=None, masked=None, resampling=Resampling.cubic):
"""Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indices of requested bands, default None which returns all bands
:param resampling: reprojection resampling method, default `cubic`
:return: GeoRaster2 of tile in WEB_MERCATOR_CRS
You can use TELLURIC_GET_TILE_BUFFER env variable to control the number of pixels surrounding
the vector you should fetch when using this method on a raster that is not in WEB_MERCATOR_CRS
default to 10
"""
if self.crs == WEB_MERCATOR_CRS:
return self._get_tile_when_web_mercator_crs(x_tile, y_tile, zoom, bands, masked, resampling)
roi = GeoVector.from_xyz(x_tile, y_tile, zoom)
left, bottom, right, top = roi.get_bounds(WEB_MERCATOR_CRS)
new_affine = rasterio.warp.calculate_default_transform(WEB_MERCATOR_CRS, self.crs,
256, 256, left, bottom, right, top)[0]
new_resolution = resolution_from_affine(new_affine)
buffer_ratio = int(os.environ.get("TELLURIC_GET_TILE_BUFFER", 10))
roi_buffer = roi.buffer(math.sqrt(roi.area * buffer_ratio / 100))
raster = self.crop(roi_buffer, resolution=new_resolution, masked=masked,
bands=bands, resampling=resampling)
raster = raster.reproject(dst_crs=WEB_MERCATOR_CRS, resolution=MERCATOR_RESOLUTION_MAPPING[zoom],
dst_bounds=roi_buffer.get_bounds(WEB_MERCATOR_CRS),
resampling=Resampling.cubic_spline)
# raster = raster.get_tile(x_tile, y_tile, zoom, bands, masked, resampling)
raster = raster.crop(roi).resize(dest_width=256, dest_height=256)
return raster
|
[
"def",
"get_tile",
"(",
"self",
",",
"x_tile",
",",
"y_tile",
",",
"zoom",
",",
"bands",
"=",
"None",
",",
"masked",
"=",
"None",
",",
"resampling",
"=",
"Resampling",
".",
"cubic",
")",
":",
"if",
"self",
".",
"crs",
"==",
"WEB_MERCATOR_CRS",
":",
"return",
"self",
".",
"_get_tile_when_web_mercator_crs",
"(",
"x_tile",
",",
"y_tile",
",",
"zoom",
",",
"bands",
",",
"masked",
",",
"resampling",
")",
"roi",
"=",
"GeoVector",
".",
"from_xyz",
"(",
"x_tile",
",",
"y_tile",
",",
"zoom",
")",
"left",
",",
"bottom",
",",
"right",
",",
"top",
"=",
"roi",
".",
"get_bounds",
"(",
"WEB_MERCATOR_CRS",
")",
"new_affine",
"=",
"rasterio",
".",
"warp",
".",
"calculate_default_transform",
"(",
"WEB_MERCATOR_CRS",
",",
"self",
".",
"crs",
",",
"256",
",",
"256",
",",
"left",
",",
"bottom",
",",
"right",
",",
"top",
")",
"[",
"0",
"]",
"new_resolution",
"=",
"resolution_from_affine",
"(",
"new_affine",
")",
"buffer_ratio",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"TELLURIC_GET_TILE_BUFFER\"",
",",
"10",
")",
")",
"roi_buffer",
"=",
"roi",
".",
"buffer",
"(",
"math",
".",
"sqrt",
"(",
"roi",
".",
"area",
"*",
"buffer_ratio",
"/",
"100",
")",
")",
"raster",
"=",
"self",
".",
"crop",
"(",
"roi_buffer",
",",
"resolution",
"=",
"new_resolution",
",",
"masked",
"=",
"masked",
",",
"bands",
"=",
"bands",
",",
"resampling",
"=",
"resampling",
")",
"raster",
"=",
"raster",
".",
"reproject",
"(",
"dst_crs",
"=",
"WEB_MERCATOR_CRS",
",",
"resolution",
"=",
"MERCATOR_RESOLUTION_MAPPING",
"[",
"zoom",
"]",
",",
"dst_bounds",
"=",
"roi_buffer",
".",
"get_bounds",
"(",
"WEB_MERCATOR_CRS",
")",
",",
"resampling",
"=",
"Resampling",
".",
"cubic_spline",
")",
"# raster = raster.get_tile(x_tile, y_tile, zoom, bands, masked, resampling)",
"raster",
"=",
"raster",
".",
"crop",
"(",
"roi",
")",
".",
"resize",
"(",
"dest_width",
"=",
"256",
",",
"dest_height",
"=",
"256",
")",
"return",
"raster"
] |
Convert mercator tile to raster window.
:param x_tile: x coordinate of tile
:param y_tile: y coordinate of tile
:param zoom: zoom level
:param bands: list of indices of requested bands, default None which returns all bands
:param resampling: reprojection resampling method, default `cubic`
:return: GeoRaster2 of tile in WEB_MERCATOR_CRS
You can use TELLURIC_GET_TILE_BUFFER env variable to control the number of pixels surrounding
the vector you should fetch when using this method on a raster that is not in WEB_MERCATOR_CRS
default to 10
|
[
"Convert",
"mercator",
"tile",
"to",
"raster",
"window",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1889-L1922
|
14,551
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.colorize
|
def colorize(self, colormap, band_name=None, vmin=None, vmax=None):
"""Apply a colormap on a selected band.
colormap list: https://matplotlib.org/examples/color/colormaps_reference.html
Parameters
----------
colormap : str
Colormap name from this list https://matplotlib.org/examples/color/colormaps_reference.html
band_name : str, optional
Name of band to colorize, if none the first band will be used
vmin, vmax : int, optional
minimum and maximum range for normalizing array values, if None actual raster values will be used
Returns
-------
GeoRaster2
"""
vmin = vmin if vmin is not None else min(self.min())
vmax = vmax if vmax is not None else max(self.max())
cmap = matplotlib.cm.get_cmap(colormap) # type: matplotlib.colors.Colormap
band_index = 0
if band_name is None:
if self.num_bands > 1:
warnings.warn("Using the first band to colorize the raster", GeoRaster2Warning)
else:
band_index = self.band_names.index(band_name)
normalized = (self.image[band_index, :, :] - vmin) / (vmax - vmin)
# Colormap instances are used to convert data values (floats)
# to RGBA color that the respective Colormap
#
# https://matplotlib.org/_modules/matplotlib/colors.html#Colormap
image_data = cmap(normalized)
image_data = image_data[:, :, 0:3]
# convert floats [0,1] to uint8 [0,255]
image_data = image_data * 255
image_data = image_data.astype(np.uint8)
image_data = np.rollaxis(image_data, 2)
# force nodata where it was in original raster:
mask = _join_masks_from_masked_array(self.image)
mask = np.stack([mask[0, :, :]] * 3)
array = np.ma.array(image_data.data, mask=mask).filled(0) # type: np.ndarray
array = np.ma.array(array, mask=mask)
return self.copy_with(image=array, band_names=['red', 'green', 'blue'])
|
python
|
def colorize(self, colormap, band_name=None, vmin=None, vmax=None):
"""Apply a colormap on a selected band.
colormap list: https://matplotlib.org/examples/color/colormaps_reference.html
Parameters
----------
colormap : str
Colormap name from this list https://matplotlib.org/examples/color/colormaps_reference.html
band_name : str, optional
Name of band to colorize, if none the first band will be used
vmin, vmax : int, optional
minimum and maximum range for normalizing array values, if None actual raster values will be used
Returns
-------
GeoRaster2
"""
vmin = vmin if vmin is not None else min(self.min())
vmax = vmax if vmax is not None else max(self.max())
cmap = matplotlib.cm.get_cmap(colormap) # type: matplotlib.colors.Colormap
band_index = 0
if band_name is None:
if self.num_bands > 1:
warnings.warn("Using the first band to colorize the raster", GeoRaster2Warning)
else:
band_index = self.band_names.index(band_name)
normalized = (self.image[band_index, :, :] - vmin) / (vmax - vmin)
# Colormap instances are used to convert data values (floats)
# to RGBA color that the respective Colormap
#
# https://matplotlib.org/_modules/matplotlib/colors.html#Colormap
image_data = cmap(normalized)
image_data = image_data[:, :, 0:3]
# convert floats [0,1] to uint8 [0,255]
image_data = image_data * 255
image_data = image_data.astype(np.uint8)
image_data = np.rollaxis(image_data, 2)
# force nodata where it was in original raster:
mask = _join_masks_from_masked_array(self.image)
mask = np.stack([mask[0, :, :]] * 3)
array = np.ma.array(image_data.data, mask=mask).filled(0) # type: np.ndarray
array = np.ma.array(array, mask=mask)
return self.copy_with(image=array, band_names=['red', 'green', 'blue'])
|
[
"def",
"colorize",
"(",
"self",
",",
"colormap",
",",
"band_name",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"vmin",
"=",
"vmin",
"if",
"vmin",
"is",
"not",
"None",
"else",
"min",
"(",
"self",
".",
"min",
"(",
")",
")",
"vmax",
"=",
"vmax",
"if",
"vmax",
"is",
"not",
"None",
"else",
"max",
"(",
"self",
".",
"max",
"(",
")",
")",
"cmap",
"=",
"matplotlib",
".",
"cm",
".",
"get_cmap",
"(",
"colormap",
")",
"# type: matplotlib.colors.Colormap",
"band_index",
"=",
"0",
"if",
"band_name",
"is",
"None",
":",
"if",
"self",
".",
"num_bands",
">",
"1",
":",
"warnings",
".",
"warn",
"(",
"\"Using the first band to colorize the raster\"",
",",
"GeoRaster2Warning",
")",
"else",
":",
"band_index",
"=",
"self",
".",
"band_names",
".",
"index",
"(",
"band_name",
")",
"normalized",
"=",
"(",
"self",
".",
"image",
"[",
"band_index",
",",
":",
",",
":",
"]",
"-",
"vmin",
")",
"/",
"(",
"vmax",
"-",
"vmin",
")",
"# Colormap instances are used to convert data values (floats)",
"# to RGBA color that the respective Colormap",
"#",
"# https://matplotlib.org/_modules/matplotlib/colors.html#Colormap",
"image_data",
"=",
"cmap",
"(",
"normalized",
")",
"image_data",
"=",
"image_data",
"[",
":",
",",
":",
",",
"0",
":",
"3",
"]",
"# convert floats [0,1] to uint8 [0,255]",
"image_data",
"=",
"image_data",
"*",
"255",
"image_data",
"=",
"image_data",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"image_data",
"=",
"np",
".",
"rollaxis",
"(",
"image_data",
",",
"2",
")",
"# force nodata where it was in original raster:",
"mask",
"=",
"_join_masks_from_masked_array",
"(",
"self",
".",
"image",
")",
"mask",
"=",
"np",
".",
"stack",
"(",
"[",
"mask",
"[",
"0",
",",
":",
",",
":",
"]",
"]",
"*",
"3",
")",
"array",
"=",
"np",
".",
"ma",
".",
"array",
"(",
"image_data",
".",
"data",
",",
"mask",
"=",
"mask",
")",
".",
"filled",
"(",
"0",
")",
"# type: np.ndarray",
"array",
"=",
"np",
".",
"ma",
".",
"array",
"(",
"array",
",",
"mask",
"=",
"mask",
")",
"return",
"self",
".",
"copy_with",
"(",
"image",
"=",
"array",
",",
"band_names",
"=",
"[",
"'red'",
",",
"'green'",
",",
"'blue'",
"]",
")"
] |
Apply a colormap on a selected band.
colormap list: https://matplotlib.org/examples/color/colormaps_reference.html
Parameters
----------
colormap : str
Colormap name from this list https://matplotlib.org/examples/color/colormaps_reference.html
band_name : str, optional
Name of band to colorize, if none the first band will be used
vmin, vmax : int, optional
minimum and maximum range for normalizing array values, if None actual raster values will be used
Returns
-------
GeoRaster2
|
[
"Apply",
"a",
"colormap",
"on",
"a",
"selected",
"band",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1933-L1986
|
14,552
|
satellogic/telluric
|
telluric/georaster.py
|
GeoRaster2.chunks
|
def chunks(self, shape=256, pad=False):
"""This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optional
The shape of the chunk. Default: 256.
pad : bool, optional
When set to True all rasters will have the same shape, when False
the edge rasters will have a shape less than the requested shape,
according to what the raster actually had. Defaults to False.
Returns
-------
out: RasterChunk
The iterator that has the raster and the offsets in it.
"""
_self = self._raster_backed_by_a_file()
if isinstance(shape, int):
shape = (shape, shape)
(width, height) = shape
col_steps = int(_self.width / width)
row_steps = int(_self.height / height)
# when we the raster has an axis in which the shape is multipication
# of the requested shape we don't need an extra step with window equal zero
# in other cases we do need the extra step to get the reminder of the content
col_extra_step = 1 if _self.width % width > 0 else 0
row_extra_step = 1 if _self.height % height > 0 else 0
for col_step in range(0, col_steps + col_extra_step):
col_off = col_step * width
if not pad and col_step == col_steps:
window_width = _self.width % width
else:
window_width = width
for row_step in range(0, row_steps + row_extra_step):
row_off = row_step * height
if not pad and row_step == row_steps:
window_height = _self.height % height
else:
window_height = height
window = Window(col_off=col_off, row_off=row_off, width=window_width, height=window_height)
cur_raster = _self.get_window(window)
yield RasterChunk(raster=cur_raster, offsets=(col_off, row_off))
|
python
|
def chunks(self, shape=256, pad=False):
"""This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optional
The shape of the chunk. Default: 256.
pad : bool, optional
When set to True all rasters will have the same shape, when False
the edge rasters will have a shape less than the requested shape,
according to what the raster actually had. Defaults to False.
Returns
-------
out: RasterChunk
The iterator that has the raster and the offsets in it.
"""
_self = self._raster_backed_by_a_file()
if isinstance(shape, int):
shape = (shape, shape)
(width, height) = shape
col_steps = int(_self.width / width)
row_steps = int(_self.height / height)
# when we the raster has an axis in which the shape is multipication
# of the requested shape we don't need an extra step with window equal zero
# in other cases we do need the extra step to get the reminder of the content
col_extra_step = 1 if _self.width % width > 0 else 0
row_extra_step = 1 if _self.height % height > 0 else 0
for col_step in range(0, col_steps + col_extra_step):
col_off = col_step * width
if not pad and col_step == col_steps:
window_width = _self.width % width
else:
window_width = width
for row_step in range(0, row_steps + row_extra_step):
row_off = row_step * height
if not pad and row_step == row_steps:
window_height = _self.height % height
else:
window_height = height
window = Window(col_off=col_off, row_off=row_off, width=window_width, height=window_height)
cur_raster = _self.get_window(window)
yield RasterChunk(raster=cur_raster, offsets=(col_off, row_off))
|
[
"def",
"chunks",
"(",
"self",
",",
"shape",
"=",
"256",
",",
"pad",
"=",
"False",
")",
":",
"_self",
"=",
"self",
".",
"_raster_backed_by_a_file",
"(",
")",
"if",
"isinstance",
"(",
"shape",
",",
"int",
")",
":",
"shape",
"=",
"(",
"shape",
",",
"shape",
")",
"(",
"width",
",",
"height",
")",
"=",
"shape",
"col_steps",
"=",
"int",
"(",
"_self",
".",
"width",
"/",
"width",
")",
"row_steps",
"=",
"int",
"(",
"_self",
".",
"height",
"/",
"height",
")",
"# when we the raster has an axis in which the shape is multipication",
"# of the requested shape we don't need an extra step with window equal zero",
"# in other cases we do need the extra step to get the reminder of the content",
"col_extra_step",
"=",
"1",
"if",
"_self",
".",
"width",
"%",
"width",
">",
"0",
"else",
"0",
"row_extra_step",
"=",
"1",
"if",
"_self",
".",
"height",
"%",
"height",
">",
"0",
"else",
"0",
"for",
"col_step",
"in",
"range",
"(",
"0",
",",
"col_steps",
"+",
"col_extra_step",
")",
":",
"col_off",
"=",
"col_step",
"*",
"width",
"if",
"not",
"pad",
"and",
"col_step",
"==",
"col_steps",
":",
"window_width",
"=",
"_self",
".",
"width",
"%",
"width",
"else",
":",
"window_width",
"=",
"width",
"for",
"row_step",
"in",
"range",
"(",
"0",
",",
"row_steps",
"+",
"row_extra_step",
")",
":",
"row_off",
"=",
"row_step",
"*",
"height",
"if",
"not",
"pad",
"and",
"row_step",
"==",
"row_steps",
":",
"window_height",
"=",
"_self",
".",
"height",
"%",
"height",
"else",
":",
"window_height",
"=",
"height",
"window",
"=",
"Window",
"(",
"col_off",
"=",
"col_off",
",",
"row_off",
"=",
"row_off",
",",
"width",
"=",
"window_width",
",",
"height",
"=",
"window_height",
")",
"cur_raster",
"=",
"_self",
".",
"get_window",
"(",
"window",
")",
"yield",
"RasterChunk",
"(",
"raster",
"=",
"cur_raster",
",",
"offsets",
"=",
"(",
"col_off",
",",
"row_off",
")",
")"
] |
This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optional
The shape of the chunk. Default: 256.
pad : bool, optional
When set to True all rasters will have the same shape, when False
the edge rasters will have a shape less than the requested shape,
according to what the raster actually had. Defaults to False.
Returns
-------
out: RasterChunk
The iterator that has the raster and the offsets in it.
|
[
"This",
"method",
"returns",
"GeoRaster",
"chunks",
"out",
"of",
"the",
"original",
"raster",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1998-L2048
|
14,553
|
satellogic/telluric
|
telluric/collections.py
|
dissolve
|
def dissolve(collection, aggfunc=None):
# type: (BaseCollection, Optional[Callable[[list], Any]]) -> GeoFeature
"""Dissolves features contained in a FeatureCollection and applies an aggregation
function to its properties.
"""
new_properties = {}
if aggfunc:
temp_properties = defaultdict(list) # type: DefaultDict[Any, Any]
for feature in collection:
for key, value in feature.attributes.items():
temp_properties[key].append(value)
for key, values in temp_properties.items():
try:
new_properties[key] = aggfunc(values)
except Exception:
# We just do not use these results
pass
return GeoFeature(collection.cascaded_union, new_properties)
|
python
|
def dissolve(collection, aggfunc=None):
# type: (BaseCollection, Optional[Callable[[list], Any]]) -> GeoFeature
"""Dissolves features contained in a FeatureCollection and applies an aggregation
function to its properties.
"""
new_properties = {}
if aggfunc:
temp_properties = defaultdict(list) # type: DefaultDict[Any, Any]
for feature in collection:
for key, value in feature.attributes.items():
temp_properties[key].append(value)
for key, values in temp_properties.items():
try:
new_properties[key] = aggfunc(values)
except Exception:
# We just do not use these results
pass
return GeoFeature(collection.cascaded_union, new_properties)
|
[
"def",
"dissolve",
"(",
"collection",
",",
"aggfunc",
"=",
"None",
")",
":",
"# type: (BaseCollection, Optional[Callable[[list], Any]]) -> GeoFeature",
"new_properties",
"=",
"{",
"}",
"if",
"aggfunc",
":",
"temp_properties",
"=",
"defaultdict",
"(",
"list",
")",
"# type: DefaultDict[Any, Any]",
"for",
"feature",
"in",
"collection",
":",
"for",
"key",
",",
"value",
"in",
"feature",
".",
"attributes",
".",
"items",
"(",
")",
":",
"temp_properties",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")",
"for",
"key",
",",
"values",
"in",
"temp_properties",
".",
"items",
"(",
")",
":",
"try",
":",
"new_properties",
"[",
"key",
"]",
"=",
"aggfunc",
"(",
"values",
")",
"except",
"Exception",
":",
"# We just do not use these results",
"pass",
"return",
"GeoFeature",
"(",
"collection",
".",
"cascaded_union",
",",
"new_properties",
")"
] |
Dissolves features contained in a FeatureCollection and applies an aggregation
function to its properties.
|
[
"Dissolves",
"features",
"contained",
"in",
"a",
"FeatureCollection",
"and",
"applies",
"an",
"aggregation",
"function",
"to",
"its",
"properties",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L34-L55
|
14,554
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.filter
|
def filter(self, intersects):
"""Filter results that intersect a given GeoFeature or Vector.
"""
try:
crs = self.crs
vector = intersects.geometry if isinstance(intersects, GeoFeature) else intersects
prepared_shape = prep(vector.get_shape(crs))
hits = []
for feature in self:
target_shape = feature.geometry.get_shape(crs)
if prepared_shape.overlaps(target_shape) or prepared_shape.intersects(target_shape):
hits.append(feature)
except IndexError:
hits = []
return FeatureCollection(hits)
|
python
|
def filter(self, intersects):
"""Filter results that intersect a given GeoFeature or Vector.
"""
try:
crs = self.crs
vector = intersects.geometry if isinstance(intersects, GeoFeature) else intersects
prepared_shape = prep(vector.get_shape(crs))
hits = []
for feature in self:
target_shape = feature.geometry.get_shape(crs)
if prepared_shape.overlaps(target_shape) or prepared_shape.intersects(target_shape):
hits.append(feature)
except IndexError:
hits = []
return FeatureCollection(hits)
|
[
"def",
"filter",
"(",
"self",
",",
"intersects",
")",
":",
"try",
":",
"crs",
"=",
"self",
".",
"crs",
"vector",
"=",
"intersects",
".",
"geometry",
"if",
"isinstance",
"(",
"intersects",
",",
"GeoFeature",
")",
"else",
"intersects",
"prepared_shape",
"=",
"prep",
"(",
"vector",
".",
"get_shape",
"(",
"crs",
")",
")",
"hits",
"=",
"[",
"]",
"for",
"feature",
"in",
"self",
":",
"target_shape",
"=",
"feature",
".",
"geometry",
".",
"get_shape",
"(",
"crs",
")",
"if",
"prepared_shape",
".",
"overlaps",
"(",
"target_shape",
")",
"or",
"prepared_shape",
".",
"intersects",
"(",
"target_shape",
")",
":",
"hits",
".",
"append",
"(",
"feature",
")",
"except",
"IndexError",
":",
"hits",
"=",
"[",
"]",
"return",
"FeatureCollection",
"(",
"hits",
")"
] |
Filter results that intersect a given GeoFeature or Vector.
|
[
"Filter",
"results",
"that",
"intersect",
"a",
"given",
"GeoFeature",
"or",
"Vector",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L137-L155
|
14,555
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.sort
|
def sort(self, by, desc=False):
"""Sorts by given property or function, ascending or descending order.
Parameters
----------
by : str or callable
If string, property by which to sort.
If callable, it should receive a GeoFeature a return a value by which to sort.
desc : bool, optional
Descending sort, default to False (ascending).
"""
if callable(by):
key = by
else:
def key(feature):
return feature[by]
sorted_features = sorted(list(self), reverse=desc, key=key)
return self.__class__(sorted_features)
|
python
|
def sort(self, by, desc=False):
"""Sorts by given property or function, ascending or descending order.
Parameters
----------
by : str or callable
If string, property by which to sort.
If callable, it should receive a GeoFeature a return a value by which to sort.
desc : bool, optional
Descending sort, default to False (ascending).
"""
if callable(by):
key = by
else:
def key(feature):
return feature[by]
sorted_features = sorted(list(self), reverse=desc, key=key)
return self.__class__(sorted_features)
|
[
"def",
"sort",
"(",
"self",
",",
"by",
",",
"desc",
"=",
"False",
")",
":",
"if",
"callable",
"(",
"by",
")",
":",
"key",
"=",
"by",
"else",
":",
"def",
"key",
"(",
"feature",
")",
":",
"return",
"feature",
"[",
"by",
"]",
"sorted_features",
"=",
"sorted",
"(",
"list",
"(",
"self",
")",
",",
"reverse",
"=",
"desc",
",",
"key",
"=",
"key",
")",
"return",
"self",
".",
"__class__",
"(",
"sorted_features",
")"
] |
Sorts by given property or function, ascending or descending order.
Parameters
----------
by : str or callable
If string, property by which to sort.
If callable, it should receive a GeoFeature a return a value by which to sort.
desc : bool, optional
Descending sort, default to False (ascending).
|
[
"Sorts",
"by",
"given",
"property",
"or",
"function",
"ascending",
"or",
"descending",
"order",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L157-L176
|
14,556
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.groupby
|
def groupby(self, by):
# type: (Union[str, Callable[[GeoFeature], str]]) -> _CollectionGroupBy
"""Groups collection using a value of a property.
Parameters
----------
by : str or callable
If string, name of the property by which to group.
If callable, should receive a GeoFeature and return the category.
Returns
-------
_CollectionGroupBy
"""
results = OrderedDict() # type: OrderedDict[str, list]
for feature in self:
if callable(by):
value = by(feature)
else:
value = feature[by]
results.setdefault(value, []).append(feature)
if hasattr(self, "_schema"):
# I am doing this to trick mypy, is there a better way?
# calling self._schema generates a mypy problem
schema = getattr(self, "_schema")
return _CollectionGroupBy(results, schema=schema)
|
python
|
def groupby(self, by):
# type: (Union[str, Callable[[GeoFeature], str]]) -> _CollectionGroupBy
"""Groups collection using a value of a property.
Parameters
----------
by : str or callable
If string, name of the property by which to group.
If callable, should receive a GeoFeature and return the category.
Returns
-------
_CollectionGroupBy
"""
results = OrderedDict() # type: OrderedDict[str, list]
for feature in self:
if callable(by):
value = by(feature)
else:
value = feature[by]
results.setdefault(value, []).append(feature)
if hasattr(self, "_schema"):
# I am doing this to trick mypy, is there a better way?
# calling self._schema generates a mypy problem
schema = getattr(self, "_schema")
return _CollectionGroupBy(results, schema=schema)
|
[
"def",
"groupby",
"(",
"self",
",",
"by",
")",
":",
"# type: (Union[str, Callable[[GeoFeature], str]]) -> _CollectionGroupBy",
"results",
"=",
"OrderedDict",
"(",
")",
"# type: OrderedDict[str, list]",
"for",
"feature",
"in",
"self",
":",
"if",
"callable",
"(",
"by",
")",
":",
"value",
"=",
"by",
"(",
"feature",
")",
"else",
":",
"value",
"=",
"feature",
"[",
"by",
"]",
"results",
".",
"setdefault",
"(",
"value",
",",
"[",
"]",
")",
".",
"append",
"(",
"feature",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"_schema\"",
")",
":",
"# I am doing this to trick mypy, is there a better way?",
"# calling self._schema generates a mypy problem",
"schema",
"=",
"getattr",
"(",
"self",
",",
"\"_schema\"",
")",
"return",
"_CollectionGroupBy",
"(",
"results",
",",
"schema",
"=",
"schema",
")"
] |
Groups collection using a value of a property.
Parameters
----------
by : str or callable
If string, name of the property by which to group.
If callable, should receive a GeoFeature and return the category.
Returns
-------
_CollectionGroupBy
|
[
"Groups",
"collection",
"using",
"a",
"value",
"of",
"a",
"property",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L178-L207
|
14,557
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.dissolve
|
def dissolve(self, by=None, aggfunc=None):
# type: (Optional[str], Optional[Callable]) -> FeatureCollection
"""Dissolve geometries and rasters within `groupby`.
"""
if by:
agg = partial(dissolve, aggfunc=aggfunc) # type: Callable[[BaseCollection], GeoFeature]
return self.groupby(by).agg(agg)
else:
return FeatureCollection([dissolve(self, aggfunc)])
|
python
|
def dissolve(self, by=None, aggfunc=None):
# type: (Optional[str], Optional[Callable]) -> FeatureCollection
"""Dissolve geometries and rasters within `groupby`.
"""
if by:
agg = partial(dissolve, aggfunc=aggfunc) # type: Callable[[BaseCollection], GeoFeature]
return self.groupby(by).agg(agg)
else:
return FeatureCollection([dissolve(self, aggfunc)])
|
[
"def",
"dissolve",
"(",
"self",
",",
"by",
"=",
"None",
",",
"aggfunc",
"=",
"None",
")",
":",
"# type: (Optional[str], Optional[Callable]) -> FeatureCollection",
"if",
"by",
":",
"agg",
"=",
"partial",
"(",
"dissolve",
",",
"aggfunc",
"=",
"aggfunc",
")",
"# type: Callable[[BaseCollection], GeoFeature]",
"return",
"self",
".",
"groupby",
"(",
"by",
")",
".",
"agg",
"(",
"agg",
")",
"else",
":",
"return",
"FeatureCollection",
"(",
"[",
"dissolve",
"(",
"self",
",",
"aggfunc",
")",
"]",
")"
] |
Dissolve geometries and rasters within `groupby`.
|
[
"Dissolve",
"geometries",
"and",
"rasters",
"within",
"groupby",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L209-L219
|
14,558
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.rasterize
|
def rasterize(self, dest_resolution, *, polygonize_width=0, crs=WEB_MERCATOR_CRS, fill_value=None,
bounds=None, dtype=None, **polygonize_kwargs):
"""Binarize a FeatureCollection and produce a raster with the target resolution.
Parameters
----------
dest_resolution: float
Resolution in units of the CRS.
polygonize_width : int, optional
Width for the polygonized features (lines and points) in pixels, default to 0 (they won't appear).
crs : ~rasterio.crs.CRS, dict (optional)
Coordinate system, default to :py:data:`telluric.constants.WEB_MERCATOR_CRS`.
fill_value : float or function, optional
Value that represents data, default to None (will default to :py:data:`telluric.rasterization.FILL_VALUE`.
If given a function, it must accept a single :py:class:`~telluric.features.GeoFeature` and return a numeric
value.
nodata_value : float, optional
Nodata value, default to None (will default to :py:data:`telluric.rasterization.NODATA_VALUE`.
bounds : GeoVector, optional
Optional bounds for the target image, default to None (will use the FeatureCollection convex hull).
dtype : numpy.dtype, optional
dtype of the result, required only if fill_value is a function.
polygonize_kwargs : dict
Extra parameters to the polygonize function.
"""
# Avoid circular imports
from telluric.georaster import merge_all, MergeStrategy
from telluric.rasterization import rasterize, NODATA_DEPRECATION_WARNING
# Compute the size in real units and polygonize the features
if not isinstance(polygonize_width, int):
raise TypeError("The width in pixels must be an integer")
if polygonize_kwargs.pop("nodata_value", None):
warnings.warn(NODATA_DEPRECATION_WARNING, DeprecationWarning)
# If the pixels width is 1, render points as squares to avoid missing data
if polygonize_width == 1:
polygonize_kwargs.update(cap_style_point=CAP_STYLE.square)
# Reproject collection to target CRS
if (
self.crs is not None and
self.crs != crs
):
reprojected = self.reproject(crs)
else:
reprojected = self
width = polygonize_width * dest_resolution
polygonized = [feature.polygonize(width, **polygonize_kwargs) for feature in reprojected]
# Discard the empty features
shapes = [feature.geometry.get_shape(crs) for feature in polygonized
if not feature.is_empty]
if bounds is None:
bounds = self.envelope
if bounds.area == 0.0:
raise ValueError("Specify non-empty ROI")
if not len(self):
fill_value = None
if callable(fill_value):
if dtype is None:
raise ValueError("dtype must be specified for multivalue rasterization")
rasters = []
for feature in self:
rasters.append(feature.geometry.rasterize(
dest_resolution, fill_value=fill_value(feature), bounds=bounds, dtype=dtype, crs=crs)
)
return merge_all(rasters, bounds.reproject(crs), dest_resolution, merge_strategy=MergeStrategy.INTERSECTION)
else:
return rasterize(shapes, crs, bounds.get_shape(crs), dest_resolution, fill_value=fill_value, dtype=dtype)
|
python
|
def rasterize(self, dest_resolution, *, polygonize_width=0, crs=WEB_MERCATOR_CRS, fill_value=None,
bounds=None, dtype=None, **polygonize_kwargs):
"""Binarize a FeatureCollection and produce a raster with the target resolution.
Parameters
----------
dest_resolution: float
Resolution in units of the CRS.
polygonize_width : int, optional
Width for the polygonized features (lines and points) in pixels, default to 0 (they won't appear).
crs : ~rasterio.crs.CRS, dict (optional)
Coordinate system, default to :py:data:`telluric.constants.WEB_MERCATOR_CRS`.
fill_value : float or function, optional
Value that represents data, default to None (will default to :py:data:`telluric.rasterization.FILL_VALUE`.
If given a function, it must accept a single :py:class:`~telluric.features.GeoFeature` and return a numeric
value.
nodata_value : float, optional
Nodata value, default to None (will default to :py:data:`telluric.rasterization.NODATA_VALUE`.
bounds : GeoVector, optional
Optional bounds for the target image, default to None (will use the FeatureCollection convex hull).
dtype : numpy.dtype, optional
dtype of the result, required only if fill_value is a function.
polygonize_kwargs : dict
Extra parameters to the polygonize function.
"""
# Avoid circular imports
from telluric.georaster import merge_all, MergeStrategy
from telluric.rasterization import rasterize, NODATA_DEPRECATION_WARNING
# Compute the size in real units and polygonize the features
if not isinstance(polygonize_width, int):
raise TypeError("The width in pixels must be an integer")
if polygonize_kwargs.pop("nodata_value", None):
warnings.warn(NODATA_DEPRECATION_WARNING, DeprecationWarning)
# If the pixels width is 1, render points as squares to avoid missing data
if polygonize_width == 1:
polygonize_kwargs.update(cap_style_point=CAP_STYLE.square)
# Reproject collection to target CRS
if (
self.crs is not None and
self.crs != crs
):
reprojected = self.reproject(crs)
else:
reprojected = self
width = polygonize_width * dest_resolution
polygonized = [feature.polygonize(width, **polygonize_kwargs) for feature in reprojected]
# Discard the empty features
shapes = [feature.geometry.get_shape(crs) for feature in polygonized
if not feature.is_empty]
if bounds is None:
bounds = self.envelope
if bounds.area == 0.0:
raise ValueError("Specify non-empty ROI")
if not len(self):
fill_value = None
if callable(fill_value):
if dtype is None:
raise ValueError("dtype must be specified for multivalue rasterization")
rasters = []
for feature in self:
rasters.append(feature.geometry.rasterize(
dest_resolution, fill_value=fill_value(feature), bounds=bounds, dtype=dtype, crs=crs)
)
return merge_all(rasters, bounds.reproject(crs), dest_resolution, merge_strategy=MergeStrategy.INTERSECTION)
else:
return rasterize(shapes, crs, bounds.get_shape(crs), dest_resolution, fill_value=fill_value, dtype=dtype)
|
[
"def",
"rasterize",
"(",
"self",
",",
"dest_resolution",
",",
"*",
",",
"polygonize_width",
"=",
"0",
",",
"crs",
"=",
"WEB_MERCATOR_CRS",
",",
"fill_value",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"polygonize_kwargs",
")",
":",
"# Avoid circular imports",
"from",
"telluric",
".",
"georaster",
"import",
"merge_all",
",",
"MergeStrategy",
"from",
"telluric",
".",
"rasterization",
"import",
"rasterize",
",",
"NODATA_DEPRECATION_WARNING",
"# Compute the size in real units and polygonize the features",
"if",
"not",
"isinstance",
"(",
"polygonize_width",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"The width in pixels must be an integer\"",
")",
"if",
"polygonize_kwargs",
".",
"pop",
"(",
"\"nodata_value\"",
",",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"NODATA_DEPRECATION_WARNING",
",",
"DeprecationWarning",
")",
"# If the pixels width is 1, render points as squares to avoid missing data",
"if",
"polygonize_width",
"==",
"1",
":",
"polygonize_kwargs",
".",
"update",
"(",
"cap_style_point",
"=",
"CAP_STYLE",
".",
"square",
")",
"# Reproject collection to target CRS",
"if",
"(",
"self",
".",
"crs",
"is",
"not",
"None",
"and",
"self",
".",
"crs",
"!=",
"crs",
")",
":",
"reprojected",
"=",
"self",
".",
"reproject",
"(",
"crs",
")",
"else",
":",
"reprojected",
"=",
"self",
"width",
"=",
"polygonize_width",
"*",
"dest_resolution",
"polygonized",
"=",
"[",
"feature",
".",
"polygonize",
"(",
"width",
",",
"*",
"*",
"polygonize_kwargs",
")",
"for",
"feature",
"in",
"reprojected",
"]",
"# Discard the empty features",
"shapes",
"=",
"[",
"feature",
".",
"geometry",
".",
"get_shape",
"(",
"crs",
")",
"for",
"feature",
"in",
"polygonized",
"if",
"not",
"feature",
".",
"is_empty",
"]",
"if",
"bounds",
"is",
"None",
":",
"bounds",
"=",
"self",
".",
"envelope",
"if",
"bounds",
".",
"area",
"==",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"Specify non-empty ROI\"",
")",
"if",
"not",
"len",
"(",
"self",
")",
":",
"fill_value",
"=",
"None",
"if",
"callable",
"(",
"fill_value",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"dtype must be specified for multivalue rasterization\"",
")",
"rasters",
"=",
"[",
"]",
"for",
"feature",
"in",
"self",
":",
"rasters",
".",
"append",
"(",
"feature",
".",
"geometry",
".",
"rasterize",
"(",
"dest_resolution",
",",
"fill_value",
"=",
"fill_value",
"(",
"feature",
")",
",",
"bounds",
"=",
"bounds",
",",
"dtype",
"=",
"dtype",
",",
"crs",
"=",
"crs",
")",
")",
"return",
"merge_all",
"(",
"rasters",
",",
"bounds",
".",
"reproject",
"(",
"crs",
")",
",",
"dest_resolution",
",",
"merge_strategy",
"=",
"MergeStrategy",
".",
"INTERSECTION",
")",
"else",
":",
"return",
"rasterize",
"(",
"shapes",
",",
"crs",
",",
"bounds",
".",
"get_shape",
"(",
"crs",
")",
",",
"dest_resolution",
",",
"fill_value",
"=",
"fill_value",
",",
"dtype",
"=",
"dtype",
")"
] |
Binarize a FeatureCollection and produce a raster with the target resolution.
Parameters
----------
dest_resolution: float
Resolution in units of the CRS.
polygonize_width : int, optional
Width for the polygonized features (lines and points) in pixels, default to 0 (they won't appear).
crs : ~rasterio.crs.CRS, dict (optional)
Coordinate system, default to :py:data:`telluric.constants.WEB_MERCATOR_CRS`.
fill_value : float or function, optional
Value that represents data, default to None (will default to :py:data:`telluric.rasterization.FILL_VALUE`.
If given a function, it must accept a single :py:class:`~telluric.features.GeoFeature` and return a numeric
value.
nodata_value : float, optional
Nodata value, default to None (will default to :py:data:`telluric.rasterization.NODATA_VALUE`.
bounds : GeoVector, optional
Optional bounds for the target image, default to None (will use the FeatureCollection convex hull).
dtype : numpy.dtype, optional
dtype of the result, required only if fill_value is a function.
polygonize_kwargs : dict
Extra parameters to the polygonize function.
|
[
"Binarize",
"a",
"FeatureCollection",
"and",
"produce",
"a",
"raster",
"with",
"the",
"target",
"resolution",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L227-L306
|
14,559
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.save
|
def save(self, filename, driver=None, schema=None):
"""Saves collection to file.
"""
if driver is None:
driver = DRIVERS.get(os.path.splitext(filename)[-1])
if schema is None:
schema = self.schema
if driver == "GeoJSON":
# Workaround for https://github.com/Toblerity/Fiona/issues/438
# https://stackoverflow.com/a/27045091/554319
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
crs = WGS84_CRS
else:
crs = self.crs
with fiona.open(filename, 'w', driver=driver, schema=schema, crs=crs) as sink:
for feature in self:
new_feature = self._adapt_feature_before_write(feature)
sink.write(new_feature.to_record(crs))
|
python
|
def save(self, filename, driver=None, schema=None):
"""Saves collection to file.
"""
if driver is None:
driver = DRIVERS.get(os.path.splitext(filename)[-1])
if schema is None:
schema = self.schema
if driver == "GeoJSON":
# Workaround for https://github.com/Toblerity/Fiona/issues/438
# https://stackoverflow.com/a/27045091/554319
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
crs = WGS84_CRS
else:
crs = self.crs
with fiona.open(filename, 'w', driver=driver, schema=schema, crs=crs) as sink:
for feature in self:
new_feature = self._adapt_feature_before_write(feature)
sink.write(new_feature.to_record(crs))
|
[
"def",
"save",
"(",
"self",
",",
"filename",
",",
"driver",
"=",
"None",
",",
"schema",
"=",
"None",
")",
":",
"if",
"driver",
"is",
"None",
":",
"driver",
"=",
"DRIVERS",
".",
"get",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"-",
"1",
"]",
")",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"self",
".",
"schema",
"if",
"driver",
"==",
"\"GeoJSON\"",
":",
"# Workaround for https://github.com/Toblerity/Fiona/issues/438",
"# https://stackoverflow.com/a/27045091/554319",
"with",
"contextlib",
".",
"suppress",
"(",
"FileNotFoundError",
")",
":",
"os",
".",
"remove",
"(",
"filename",
")",
"crs",
"=",
"WGS84_CRS",
"else",
":",
"crs",
"=",
"self",
".",
"crs",
"with",
"fiona",
".",
"open",
"(",
"filename",
",",
"'w'",
",",
"driver",
"=",
"driver",
",",
"schema",
"=",
"schema",
",",
"crs",
"=",
"crs",
")",
"as",
"sink",
":",
"for",
"feature",
"in",
"self",
":",
"new_feature",
"=",
"self",
".",
"_adapt_feature_before_write",
"(",
"feature",
")",
"sink",
".",
"write",
"(",
"new_feature",
".",
"to_record",
"(",
"crs",
")",
")"
] |
Saves collection to file.
|
[
"Saves",
"collection",
"to",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L311-L334
|
14,560
|
satellogic/telluric
|
telluric/collections.py
|
BaseCollection.apply
|
def apply(self, **kwargs):
"""Return a new FeatureCollection with the results of applying the statements in the arguments to each element.
"""
def _apply(f):
properties = copy.deepcopy(f.properties)
for prop, value in kwargs.items():
if callable(value):
properties[prop] = value(f)
else:
properties[prop] = value
return f.copy_with(properties=properties)
new_fc = self.map(_apply)
new_schema = self.schema.copy()
property_names_set = kwargs.keys()
prop_types_map = FeatureCollection.guess_types_by_feature(new_fc[0], property_names_set)
for key, value_type in prop_types_map.items():
# already defined attribute that we just override will have the same position as before
# new attributes will be appened
new_schema["properties"][key] = FIELD_TYPES_MAP_REV.get(value_type, 'str')
new_fc._schema = new_schema
return new_fc
|
python
|
def apply(self, **kwargs):
"""Return a new FeatureCollection with the results of applying the statements in the arguments to each element.
"""
def _apply(f):
properties = copy.deepcopy(f.properties)
for prop, value in kwargs.items():
if callable(value):
properties[prop] = value(f)
else:
properties[prop] = value
return f.copy_with(properties=properties)
new_fc = self.map(_apply)
new_schema = self.schema.copy()
property_names_set = kwargs.keys()
prop_types_map = FeatureCollection.guess_types_by_feature(new_fc[0], property_names_set)
for key, value_type in prop_types_map.items():
# already defined attribute that we just override will have the same position as before
# new attributes will be appened
new_schema["properties"][key] = FIELD_TYPES_MAP_REV.get(value_type, 'str')
new_fc._schema = new_schema
return new_fc
|
[
"def",
"apply",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_apply",
"(",
"f",
")",
":",
"properties",
"=",
"copy",
".",
"deepcopy",
"(",
"f",
".",
"properties",
")",
"for",
"prop",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"callable",
"(",
"value",
")",
":",
"properties",
"[",
"prop",
"]",
"=",
"value",
"(",
"f",
")",
"else",
":",
"properties",
"[",
"prop",
"]",
"=",
"value",
"return",
"f",
".",
"copy_with",
"(",
"properties",
"=",
"properties",
")",
"new_fc",
"=",
"self",
".",
"map",
"(",
"_apply",
")",
"new_schema",
"=",
"self",
".",
"schema",
".",
"copy",
"(",
")",
"property_names_set",
"=",
"kwargs",
".",
"keys",
"(",
")",
"prop_types_map",
"=",
"FeatureCollection",
".",
"guess_types_by_feature",
"(",
"new_fc",
"[",
"0",
"]",
",",
"property_names_set",
")",
"for",
"key",
",",
"value_type",
"in",
"prop_types_map",
".",
"items",
"(",
")",
":",
"# already defined attribute that we just override will have the same position as before",
"# new attributes will be appened",
"new_schema",
"[",
"\"properties\"",
"]",
"[",
"key",
"]",
"=",
"FIELD_TYPES_MAP_REV",
".",
"get",
"(",
"value_type",
",",
"'str'",
")",
"new_fc",
".",
"_schema",
"=",
"new_schema",
"return",
"new_fc"
] |
Return a new FeatureCollection with the results of applying the statements in the arguments to each element.
|
[
"Return",
"a",
"new",
"FeatureCollection",
"with",
"the",
"results",
"of",
"applying",
"the",
"statements",
"in",
"the",
"arguments",
"to",
"each",
"element",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L341-L363
|
14,561
|
satellogic/telluric
|
telluric/collections.py
|
FeatureCollection.validate
|
def validate(self):
"""
if schema exists we run shape file validation code of fiona by trying to save to in MemoryFile
"""
if self._schema is not None:
with MemoryFile() as memfile:
with memfile.open(driver="ESRI Shapefile", schema=self.schema) as target:
for _item in self._results:
# getting rid of the assets that don't behave well becasue of in memroy rasters
item = GeoFeature(_item.geometry, _item.properties)
target.write(item.to_record(item.crs))
|
python
|
def validate(self):
"""
if schema exists we run shape file validation code of fiona by trying to save to in MemoryFile
"""
if self._schema is not None:
with MemoryFile() as memfile:
with memfile.open(driver="ESRI Shapefile", schema=self.schema) as target:
for _item in self._results:
# getting rid of the assets that don't behave well becasue of in memroy rasters
item = GeoFeature(_item.geometry, _item.properties)
target.write(item.to_record(item.crs))
|
[
"def",
"validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_schema",
"is",
"not",
"None",
":",
"with",
"MemoryFile",
"(",
")",
"as",
"memfile",
":",
"with",
"memfile",
".",
"open",
"(",
"driver",
"=",
"\"ESRI Shapefile\"",
",",
"schema",
"=",
"self",
".",
"schema",
")",
"as",
"target",
":",
"for",
"_item",
"in",
"self",
".",
"_results",
":",
"# getting rid of the assets that don't behave well becasue of in memroy rasters",
"item",
"=",
"GeoFeature",
"(",
"_item",
".",
"geometry",
",",
"_item",
".",
"properties",
")",
"target",
".",
"write",
"(",
"item",
".",
"to_record",
"(",
"item",
".",
"crs",
")",
")"
] |
if schema exists we run shape file validation code of fiona by trying to save to in MemoryFile
|
[
"if",
"schema",
"exists",
"we",
"run",
"shape",
"file",
"validation",
"code",
"of",
"fiona",
"by",
"trying",
"to",
"save",
"to",
"in",
"MemoryFile"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L386-L396
|
14,562
|
satellogic/telluric
|
telluric/collections.py
|
FileCollection.open
|
def open(cls, filename, crs=None):
"""Creates a FileCollection from a file in disk.
Parameters
----------
filename : str
Path of the file to read.
crs : CRS
overrides the crs of the collection, this funtion will not reprojects
"""
with fiona.Env():
with fiona.open(filename, 'r') as source:
original_crs = CRS(source.crs)
schema = source.schema
length = len(source)
crs = crs or original_crs
ret_val = cls(filename, crs, schema, length)
return ret_val
|
python
|
def open(cls, filename, crs=None):
"""Creates a FileCollection from a file in disk.
Parameters
----------
filename : str
Path of the file to read.
crs : CRS
overrides the crs of the collection, this funtion will not reprojects
"""
with fiona.Env():
with fiona.open(filename, 'r') as source:
original_crs = CRS(source.crs)
schema = source.schema
length = len(source)
crs = crs or original_crs
ret_val = cls(filename, crs, schema, length)
return ret_val
|
[
"def",
"open",
"(",
"cls",
",",
"filename",
",",
"crs",
"=",
"None",
")",
":",
"with",
"fiona",
".",
"Env",
"(",
")",
":",
"with",
"fiona",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"source",
":",
"original_crs",
"=",
"CRS",
"(",
"source",
".",
"crs",
")",
"schema",
"=",
"source",
".",
"schema",
"length",
"=",
"len",
"(",
"source",
")",
"crs",
"=",
"crs",
"or",
"original_crs",
"ret_val",
"=",
"cls",
"(",
"filename",
",",
"crs",
",",
"schema",
",",
"length",
")",
"return",
"ret_val"
] |
Creates a FileCollection from a file in disk.
Parameters
----------
filename : str
Path of the file to read.
crs : CRS
overrides the crs of the collection, this funtion will not reprojects
|
[
"Creates",
"a",
"FileCollection",
"from",
"a",
"file",
"in",
"disk",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L524-L542
|
14,563
|
satellogic/telluric
|
telluric/collections.py
|
_CollectionGroupBy.filter
|
def filter(self, func):
# type: (Callable[[BaseCollection], bool]) -> _CollectionGroupBy
"""Filter out Groups based on filtering function.
The function should get a FeatureCollection and return True to leave in the Group and False to take it out.
"""
results = OrderedDict() # type: OrderedDict
for name, group in self:
if func(group):
results[name] = group
return self.__class__(results)
|
python
|
def filter(self, func):
# type: (Callable[[BaseCollection], bool]) -> _CollectionGroupBy
"""Filter out Groups based on filtering function.
The function should get a FeatureCollection and return True to leave in the Group and False to take it out.
"""
results = OrderedDict() # type: OrderedDict
for name, group in self:
if func(group):
results[name] = group
return self.__class__(results)
|
[
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"# type: (Callable[[BaseCollection], bool]) -> _CollectionGroupBy",
"results",
"=",
"OrderedDict",
"(",
")",
"# type: OrderedDict",
"for",
"name",
",",
"group",
"in",
"self",
":",
"if",
"func",
"(",
"group",
")",
":",
"results",
"[",
"name",
"]",
"=",
"group",
"return",
"self",
".",
"__class__",
"(",
"results",
")"
] |
Filter out Groups based on filtering function.
The function should get a FeatureCollection and return True to leave in the Group and False to take it out.
|
[
"Filter",
"out",
"Groups",
"based",
"on",
"filtering",
"function",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/collections.py#L636-L647
|
14,564
|
satellogic/telluric
|
telluric/context.py
|
reset_context
|
def reset_context(**options):
"""Reset context to default."""
local_context._options = {}
local_context._options.update(options)
log.debug("New TelluricContext context %r created", local_context._options)
|
python
|
def reset_context(**options):
"""Reset context to default."""
local_context._options = {}
local_context._options.update(options)
log.debug("New TelluricContext context %r created", local_context._options)
|
[
"def",
"reset_context",
"(",
"*",
"*",
"options",
")",
":",
"local_context",
".",
"_options",
"=",
"{",
"}",
"local_context",
".",
"_options",
".",
"update",
"(",
"options",
")",
"log",
".",
"debug",
"(",
"\"New TelluricContext context %r created\"",
",",
"local_context",
".",
"_options",
")"
] |
Reset context to default.
|
[
"Reset",
"context",
"to",
"default",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/context.py#L131-L135
|
14,565
|
satellogic/telluric
|
telluric/context.py
|
get_context
|
def get_context():
"""Get a mapping of current options."""
if not local_context._options:
raise TelluricContextError("TelluricContext context not exists")
else:
log.debug("Got a copy of context %r options", local_context._options)
return local_context._options.copy()
|
python
|
def get_context():
"""Get a mapping of current options."""
if not local_context._options:
raise TelluricContextError("TelluricContext context not exists")
else:
log.debug("Got a copy of context %r options", local_context._options)
return local_context._options.copy()
|
[
"def",
"get_context",
"(",
")",
":",
"if",
"not",
"local_context",
".",
"_options",
":",
"raise",
"TelluricContextError",
"(",
"\"TelluricContext context not exists\"",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"Got a copy of context %r options\"",
",",
"local_context",
".",
"_options",
")",
"return",
"local_context",
".",
"_options",
".",
"copy",
"(",
")"
] |
Get a mapping of current options.
|
[
"Get",
"a",
"mapping",
"of",
"current",
"options",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/context.py#L138-L144
|
14,566
|
satellogic/telluric
|
telluric/context.py
|
set_context
|
def set_context(**options):
"""Set options in the existing context."""
if not local_context._options:
raise TelluricContextError("TelluricContext context not exists")
else:
local_context._options.update(options)
log.debug("Updated existing %r with options %r", local_context._options, options)
|
python
|
def set_context(**options):
"""Set options in the existing context."""
if not local_context._options:
raise TelluricContextError("TelluricContext context not exists")
else:
local_context._options.update(options)
log.debug("Updated existing %r with options %r", local_context._options, options)
|
[
"def",
"set_context",
"(",
"*",
"*",
"options",
")",
":",
"if",
"not",
"local_context",
".",
"_options",
":",
"raise",
"TelluricContextError",
"(",
"\"TelluricContext context not exists\"",
")",
"else",
":",
"local_context",
".",
"_options",
".",
"update",
"(",
"options",
")",
"log",
".",
"debug",
"(",
"\"Updated existing %r with options %r\"",
",",
"local_context",
".",
"_options",
",",
"options",
")"
] |
Set options in the existing context.
|
[
"Set",
"options",
"in",
"the",
"existing",
"context",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/context.py#L147-L153
|
14,567
|
satellogic/telluric
|
telluric/features.py
|
transform_properties
|
def transform_properties(properties, schema):
"""Transform properties types according to a schema.
Parameters
----------
properties : dict
Properties to transform.
schema : dict
Fiona schema containing the types.
"""
new_properties = properties.copy()
for prop_value, (prop_name, prop_type) in zip(new_properties.values(), schema["properties"].items()):
if prop_value is None:
continue
elif prop_type == "time":
new_properties[prop_name] = parse_date(prop_value).time()
elif prop_type == "date":
new_properties[prop_name] = parse_date(prop_value).date()
elif prop_type == "datetime":
new_properties[prop_name] = parse_date(prop_value)
return new_properties
|
python
|
def transform_properties(properties, schema):
"""Transform properties types according to a schema.
Parameters
----------
properties : dict
Properties to transform.
schema : dict
Fiona schema containing the types.
"""
new_properties = properties.copy()
for prop_value, (prop_name, prop_type) in zip(new_properties.values(), schema["properties"].items()):
if prop_value is None:
continue
elif prop_type == "time":
new_properties[prop_name] = parse_date(prop_value).time()
elif prop_type == "date":
new_properties[prop_name] = parse_date(prop_value).date()
elif prop_type == "datetime":
new_properties[prop_name] = parse_date(prop_value)
return new_properties
|
[
"def",
"transform_properties",
"(",
"properties",
",",
"schema",
")",
":",
"new_properties",
"=",
"properties",
".",
"copy",
"(",
")",
"for",
"prop_value",
",",
"(",
"prop_name",
",",
"prop_type",
")",
"in",
"zip",
"(",
"new_properties",
".",
"values",
"(",
")",
",",
"schema",
"[",
"\"properties\"",
"]",
".",
"items",
"(",
")",
")",
":",
"if",
"prop_value",
"is",
"None",
":",
"continue",
"elif",
"prop_type",
"==",
"\"time\"",
":",
"new_properties",
"[",
"prop_name",
"]",
"=",
"parse_date",
"(",
"prop_value",
")",
".",
"time",
"(",
")",
"elif",
"prop_type",
"==",
"\"date\"",
":",
"new_properties",
"[",
"prop_name",
"]",
"=",
"parse_date",
"(",
"prop_value",
")",
".",
"date",
"(",
")",
"elif",
"prop_type",
"==",
"\"datetime\"",
":",
"new_properties",
"[",
"prop_name",
"]",
"=",
"parse_date",
"(",
"prop_value",
")",
"return",
"new_properties"
] |
Transform properties types according to a schema.
Parameters
----------
properties : dict
Properties to transform.
schema : dict
Fiona schema containing the types.
|
[
"Transform",
"properties",
"types",
"according",
"to",
"a",
"schema",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L22-L44
|
14,568
|
satellogic/telluric
|
telluric/features.py
|
serialize_properties
|
def serialize_properties(properties):
"""Serialize properties.
Parameters
----------
properties : dict
Properties to serialize.
"""
new_properties = properties.copy()
for attr_name, attr_value in new_properties.items():
if isinstance(attr_value, datetime):
new_properties[attr_name] = attr_value.isoformat()
elif not isinstance(attr_value, (dict, list, tuple, str, int, float, bool, type(None))):
# Property is not JSON-serializable according to this table
# https://docs.python.org/3.4/library/json.html#json.JSONEncoder
# so we convert to string
new_properties[attr_name] = str(attr_value)
return new_properties
|
python
|
def serialize_properties(properties):
"""Serialize properties.
Parameters
----------
properties : dict
Properties to serialize.
"""
new_properties = properties.copy()
for attr_name, attr_value in new_properties.items():
if isinstance(attr_value, datetime):
new_properties[attr_name] = attr_value.isoformat()
elif not isinstance(attr_value, (dict, list, tuple, str, int, float, bool, type(None))):
# Property is not JSON-serializable according to this table
# https://docs.python.org/3.4/library/json.html#json.JSONEncoder
# so we convert to string
new_properties[attr_name] = str(attr_value)
return new_properties
|
[
"def",
"serialize_properties",
"(",
"properties",
")",
":",
"new_properties",
"=",
"properties",
".",
"copy",
"(",
")",
"for",
"attr_name",
",",
"attr_value",
"in",
"new_properties",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"attr_value",
",",
"datetime",
")",
":",
"new_properties",
"[",
"attr_name",
"]",
"=",
"attr_value",
".",
"isoformat",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"attr_value",
",",
"(",
"dict",
",",
"list",
",",
"tuple",
",",
"str",
",",
"int",
",",
"float",
",",
"bool",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"# Property is not JSON-serializable according to this table",
"# https://docs.python.org/3.4/library/json.html#json.JSONEncoder",
"# so we convert to string",
"new_properties",
"[",
"attr_name",
"]",
"=",
"str",
"(",
"attr_value",
")",
"return",
"new_properties"
] |
Serialize properties.
Parameters
----------
properties : dict
Properties to serialize.
|
[
"Serialize",
"properties",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L47-L65
|
14,569
|
satellogic/telluric
|
telluric/features.py
|
GeoFeature.from_record
|
def from_record(cls, record, crs, schema=None):
"""Create GeoFeature from a record."""
properties = cls._to_properties(record, schema)
vector = GeoVector(shape(record['geometry']), crs)
if record.get('raster'):
assets = {k: dict(type=RASTER_TYPE, product='visual', **v) for k, v in record.get('raster').items()}
else:
assets = record.get('assets', {})
return cls(vector, properties, assets)
|
python
|
def from_record(cls, record, crs, schema=None):
"""Create GeoFeature from a record."""
properties = cls._to_properties(record, schema)
vector = GeoVector(shape(record['geometry']), crs)
if record.get('raster'):
assets = {k: dict(type=RASTER_TYPE, product='visual', **v) for k, v in record.get('raster').items()}
else:
assets = record.get('assets', {})
return cls(vector, properties, assets)
|
[
"def",
"from_record",
"(",
"cls",
",",
"record",
",",
"crs",
",",
"schema",
"=",
"None",
")",
":",
"properties",
"=",
"cls",
".",
"_to_properties",
"(",
"record",
",",
"schema",
")",
"vector",
"=",
"GeoVector",
"(",
"shape",
"(",
"record",
"[",
"'geometry'",
"]",
")",
",",
"crs",
")",
"if",
"record",
".",
"get",
"(",
"'raster'",
")",
":",
"assets",
"=",
"{",
"k",
":",
"dict",
"(",
"type",
"=",
"RASTER_TYPE",
",",
"product",
"=",
"'visual'",
",",
"*",
"*",
"v",
")",
"for",
"k",
",",
"v",
"in",
"record",
".",
"get",
"(",
"'raster'",
")",
".",
"items",
"(",
")",
"}",
"else",
":",
"assets",
"=",
"record",
".",
"get",
"(",
"'assets'",
",",
"{",
"}",
")",
"return",
"cls",
"(",
"vector",
",",
"properties",
",",
"assets",
")"
] |
Create GeoFeature from a record.
|
[
"Create",
"GeoFeature",
"from",
"a",
"record",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L126-L134
|
14,570
|
satellogic/telluric
|
telluric/features.py
|
GeoFeature.copy_with
|
def copy_with(self, geometry=None, properties=None, assets=None):
"""Generate a new GeoFeature with different geometry or preperties."""
def copy_assets_object(asset):
obj = asset.get("__object")
if hasattr("copy", obj):
new_obj = obj.copy()
if obj:
asset["__object"] = new_obj
geometry = geometry or self.geometry.copy()
new_properties = copy.deepcopy(self.properties)
if properties:
new_properties.update(properties)
if not assets:
assets = copy.deepcopy(self.assets)
map(copy_assets_object, assets.values())
else:
assets = {}
return self.__class__(geometry, new_properties, assets)
|
python
|
def copy_with(self, geometry=None, properties=None, assets=None):
"""Generate a new GeoFeature with different geometry or preperties."""
def copy_assets_object(asset):
obj = asset.get("__object")
if hasattr("copy", obj):
new_obj = obj.copy()
if obj:
asset["__object"] = new_obj
geometry = geometry or self.geometry.copy()
new_properties = copy.deepcopy(self.properties)
if properties:
new_properties.update(properties)
if not assets:
assets = copy.deepcopy(self.assets)
map(copy_assets_object, assets.values())
else:
assets = {}
return self.__class__(geometry, new_properties, assets)
|
[
"def",
"copy_with",
"(",
"self",
",",
"geometry",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"assets",
"=",
"None",
")",
":",
"def",
"copy_assets_object",
"(",
"asset",
")",
":",
"obj",
"=",
"asset",
".",
"get",
"(",
"\"__object\"",
")",
"if",
"hasattr",
"(",
"\"copy\"",
",",
"obj",
")",
":",
"new_obj",
"=",
"obj",
".",
"copy",
"(",
")",
"if",
"obj",
":",
"asset",
"[",
"\"__object\"",
"]",
"=",
"new_obj",
"geometry",
"=",
"geometry",
"or",
"self",
".",
"geometry",
".",
"copy",
"(",
")",
"new_properties",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"properties",
")",
"if",
"properties",
":",
"new_properties",
".",
"update",
"(",
"properties",
")",
"if",
"not",
"assets",
":",
"assets",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"assets",
")",
"map",
"(",
"copy_assets_object",
",",
"assets",
".",
"values",
"(",
")",
")",
"else",
":",
"assets",
"=",
"{",
"}",
"return",
"self",
".",
"__class__",
"(",
"geometry",
",",
"new_properties",
",",
"assets",
")"
] |
Generate a new GeoFeature with different geometry or preperties.
|
[
"Generate",
"a",
"new",
"GeoFeature",
"with",
"different",
"geometry",
"or",
"preperties",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L262-L280
|
14,571
|
satellogic/telluric
|
telluric/features.py
|
GeoFeature.from_raster
|
def from_raster(cls, raster, properties, product='visual'):
"""Initialize a GeoFeature object with a GeoRaster
Parameters
----------
raster : GeoRaster
the raster in the feature
properties : dict
Properties.
product : str
product associated to the raster
"""
footprint = raster.footprint()
assets = raster.to_assets(product=product)
return cls(footprint, properties, assets)
|
python
|
def from_raster(cls, raster, properties, product='visual'):
"""Initialize a GeoFeature object with a GeoRaster
Parameters
----------
raster : GeoRaster
the raster in the feature
properties : dict
Properties.
product : str
product associated to the raster
"""
footprint = raster.footprint()
assets = raster.to_assets(product=product)
return cls(footprint, properties, assets)
|
[
"def",
"from_raster",
"(",
"cls",
",",
"raster",
",",
"properties",
",",
"product",
"=",
"'visual'",
")",
":",
"footprint",
"=",
"raster",
".",
"footprint",
"(",
")",
"assets",
"=",
"raster",
".",
"to_assets",
"(",
"product",
"=",
"product",
")",
"return",
"cls",
"(",
"footprint",
",",
"properties",
",",
"assets",
")"
] |
Initialize a GeoFeature object with a GeoRaster
Parameters
----------
raster : GeoRaster
the raster in the feature
properties : dict
Properties.
product : str
product associated to the raster
|
[
"Initialize",
"a",
"GeoFeature",
"object",
"with",
"a",
"GeoRaster"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L287-L301
|
14,572
|
satellogic/telluric
|
telluric/features.py
|
GeoFeature.has_raster
|
def has_raster(self):
"""True if any of the assets is type 'raster'."""
return any(asset.get('type') == RASTER_TYPE for asset in self.assets.values())
|
python
|
def has_raster(self):
"""True if any of the assets is type 'raster'."""
return any(asset.get('type') == RASTER_TYPE for asset in self.assets.values())
|
[
"def",
"has_raster",
"(",
"self",
")",
":",
"return",
"any",
"(",
"asset",
".",
"get",
"(",
"'type'",
")",
"==",
"RASTER_TYPE",
"for",
"asset",
"in",
"self",
".",
"assets",
".",
"values",
"(",
")",
")"
] |
True if any of the assets is type 'raster'.
|
[
"True",
"if",
"any",
"of",
"the",
"assets",
"is",
"type",
"raster",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L304-L306
|
14,573
|
satellogic/telluric
|
telluric/util/projections.py
|
transform
|
def transform(shape, source_crs, destination_crs=None, src_affine=None, dst_affine=None):
"""Transforms shape from one CRS to another.
Parameters
----------
shape : shapely.geometry.base.BaseGeometry
Shape to transform.
source_crs : dict or str
Source CRS in the form of key/value pairs or proj4 string.
destination_crs : dict or str, optional
Destination CRS, EPSG:4326 if not given.
src_affine: Affine, optional.
input shape in relative to this affine
dst_affine: Affine, optional.
output shape in relative to this affine
Returns
-------
shapely.geometry.base.BaseGeometry
Transformed shape.
"""
if destination_crs is None:
destination_crs = WGS84_CRS
if src_affine is not None:
shape = ops.transform(lambda r, q: ~src_affine * (r, q), shape)
shape = generate_transform(source_crs, destination_crs)(shape)
if dst_affine is not None:
shape = ops.transform(lambda r, q: dst_affine * (r, q), shape)
return shape
|
python
|
def transform(shape, source_crs, destination_crs=None, src_affine=None, dst_affine=None):
"""Transforms shape from one CRS to another.
Parameters
----------
shape : shapely.geometry.base.BaseGeometry
Shape to transform.
source_crs : dict or str
Source CRS in the form of key/value pairs or proj4 string.
destination_crs : dict or str, optional
Destination CRS, EPSG:4326 if not given.
src_affine: Affine, optional.
input shape in relative to this affine
dst_affine: Affine, optional.
output shape in relative to this affine
Returns
-------
shapely.geometry.base.BaseGeometry
Transformed shape.
"""
if destination_crs is None:
destination_crs = WGS84_CRS
if src_affine is not None:
shape = ops.transform(lambda r, q: ~src_affine * (r, q), shape)
shape = generate_transform(source_crs, destination_crs)(shape)
if dst_affine is not None:
shape = ops.transform(lambda r, q: dst_affine * (r, q), shape)
return shape
|
[
"def",
"transform",
"(",
"shape",
",",
"source_crs",
",",
"destination_crs",
"=",
"None",
",",
"src_affine",
"=",
"None",
",",
"dst_affine",
"=",
"None",
")",
":",
"if",
"destination_crs",
"is",
"None",
":",
"destination_crs",
"=",
"WGS84_CRS",
"if",
"src_affine",
"is",
"not",
"None",
":",
"shape",
"=",
"ops",
".",
"transform",
"(",
"lambda",
"r",
",",
"q",
":",
"~",
"src_affine",
"*",
"(",
"r",
",",
"q",
")",
",",
"shape",
")",
"shape",
"=",
"generate_transform",
"(",
"source_crs",
",",
"destination_crs",
")",
"(",
"shape",
")",
"if",
"dst_affine",
"is",
"not",
"None",
":",
"shape",
"=",
"ops",
".",
"transform",
"(",
"lambda",
"r",
",",
"q",
":",
"dst_affine",
"*",
"(",
"r",
",",
"q",
")",
",",
"shape",
")",
"return",
"shape"
] |
Transforms shape from one CRS to another.
Parameters
----------
shape : shapely.geometry.base.BaseGeometry
Shape to transform.
source_crs : dict or str
Source CRS in the form of key/value pairs or proj4 string.
destination_crs : dict or str, optional
Destination CRS, EPSG:4326 if not given.
src_affine: Affine, optional.
input shape in relative to this affine
dst_affine: Affine, optional.
output shape in relative to this affine
Returns
-------
shapely.geometry.base.BaseGeometry
Transformed shape.
|
[
"Transforms",
"shape",
"from",
"one",
"CRS",
"to",
"another",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/projections.py#L24-L57
|
14,574
|
satellogic/telluric
|
telluric/plotting.py
|
simple_plot
|
def simple_plot(feature, *, mp=None, **map_kwargs):
"""Plots a GeoVector in a simple Folium map.
For more complex and customizable plots using Jupyter widgets,
use the plot function instead.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
"""
# This import is here to avoid cyclic references
from telluric.collections import BaseCollection
if mp is None:
mp = folium.Map(tiles="Stamen Terrain", **map_kwargs)
if feature.is_empty:
warnings.warn("The geometry is empty.")
else:
if isinstance(feature, BaseCollection):
feature = feature[:SIMPLE_PLOT_MAX_ROWS]
folium.GeoJson(mapping(feature), name='geojson', overlay=True).add_to(mp)
shape = feature.envelope.get_shape(WGS84_CRS)
mp.fit_bounds([shape.bounds[:1:-1], shape.bounds[1::-1]])
return mp
|
python
|
def simple_plot(feature, *, mp=None, **map_kwargs):
"""Plots a GeoVector in a simple Folium map.
For more complex and customizable plots using Jupyter widgets,
use the plot function instead.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
"""
# This import is here to avoid cyclic references
from telluric.collections import BaseCollection
if mp is None:
mp = folium.Map(tiles="Stamen Terrain", **map_kwargs)
if feature.is_empty:
warnings.warn("The geometry is empty.")
else:
if isinstance(feature, BaseCollection):
feature = feature[:SIMPLE_PLOT_MAX_ROWS]
folium.GeoJson(mapping(feature), name='geojson', overlay=True).add_to(mp)
shape = feature.envelope.get_shape(WGS84_CRS)
mp.fit_bounds([shape.bounds[:1:-1], shape.bounds[1::-1]])
return mp
|
[
"def",
"simple_plot",
"(",
"feature",
",",
"*",
",",
"mp",
"=",
"None",
",",
"*",
"*",
"map_kwargs",
")",
":",
"# This import is here to avoid cyclic references",
"from",
"telluric",
".",
"collections",
"import",
"BaseCollection",
"if",
"mp",
"is",
"None",
":",
"mp",
"=",
"folium",
".",
"Map",
"(",
"tiles",
"=",
"\"Stamen Terrain\"",
",",
"*",
"*",
"map_kwargs",
")",
"if",
"feature",
".",
"is_empty",
":",
"warnings",
".",
"warn",
"(",
"\"The geometry is empty.\"",
")",
"else",
":",
"if",
"isinstance",
"(",
"feature",
",",
"BaseCollection",
")",
":",
"feature",
"=",
"feature",
"[",
":",
"SIMPLE_PLOT_MAX_ROWS",
"]",
"folium",
".",
"GeoJson",
"(",
"mapping",
"(",
"feature",
")",
",",
"name",
"=",
"'geojson'",
",",
"overlay",
"=",
"True",
")",
".",
"add_to",
"(",
"mp",
")",
"shape",
"=",
"feature",
".",
"envelope",
".",
"get_shape",
"(",
"WGS84_CRS",
")",
"mp",
".",
"fit_bounds",
"(",
"[",
"shape",
".",
"bounds",
"[",
":",
"1",
":",
"-",
"1",
"]",
",",
"shape",
".",
"bounds",
"[",
"1",
":",
":",
"-",
"1",
"]",
"]",
")",
"return",
"mp"
] |
Plots a GeoVector in a simple Folium map.
For more complex and customizable plots using Jupyter widgets,
use the plot function instead.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
|
[
"Plots",
"a",
"GeoVector",
"in",
"a",
"simple",
"Folium",
"map",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/plotting.py#L24-L53
|
14,575
|
satellogic/telluric
|
telluric/plotting.py
|
zoom_level_from_geometry
|
def zoom_level_from_geometry(geometry, splits=4):
"""Generate optimum zoom level for geometry.
Notes
-----
The obvious solution would be
>>> mercantile.bounding_tile(*geometry.get_shape(WGS84_CRS).bounds).z
However, if the geometry is split between two or four tiles,
the resulting zoom level might be too big.
"""
# This import is here to avoid cyclic references
from telluric.vectors import generate_tile_coordinates
# We split the geometry and compute the zoom level for each chunk
levels = []
for chunk in generate_tile_coordinates(geometry, (splits, splits)):
levels.append(mercantile.bounding_tile(*chunk.get_shape(WGS84_CRS).bounds).z)
# We now return the median value using the median_low function, which
# always picks the result from the list
return median_low(levels)
|
python
|
def zoom_level_from_geometry(geometry, splits=4):
"""Generate optimum zoom level for geometry.
Notes
-----
The obvious solution would be
>>> mercantile.bounding_tile(*geometry.get_shape(WGS84_CRS).bounds).z
However, if the geometry is split between two or four tiles,
the resulting zoom level might be too big.
"""
# This import is here to avoid cyclic references
from telluric.vectors import generate_tile_coordinates
# We split the geometry and compute the zoom level for each chunk
levels = []
for chunk in generate_tile_coordinates(geometry, (splits, splits)):
levels.append(mercantile.bounding_tile(*chunk.get_shape(WGS84_CRS).bounds).z)
# We now return the median value using the median_low function, which
# always picks the result from the list
return median_low(levels)
|
[
"def",
"zoom_level_from_geometry",
"(",
"geometry",
",",
"splits",
"=",
"4",
")",
":",
"# This import is here to avoid cyclic references",
"from",
"telluric",
".",
"vectors",
"import",
"generate_tile_coordinates",
"# We split the geometry and compute the zoom level for each chunk",
"levels",
"=",
"[",
"]",
"for",
"chunk",
"in",
"generate_tile_coordinates",
"(",
"geometry",
",",
"(",
"splits",
",",
"splits",
")",
")",
":",
"levels",
".",
"append",
"(",
"mercantile",
".",
"bounding_tile",
"(",
"*",
"chunk",
".",
"get_shape",
"(",
"WGS84_CRS",
")",
".",
"bounds",
")",
".",
"z",
")",
"# We now return the median value using the median_low function, which",
"# always picks the result from the list",
"return",
"median_low",
"(",
"levels",
")"
] |
Generate optimum zoom level for geometry.
Notes
-----
The obvious solution would be
>>> mercantile.bounding_tile(*geometry.get_shape(WGS84_CRS).bounds).z
However, if the geometry is split between two or four tiles,
the resulting zoom level might be too big.
|
[
"Generate",
"optimum",
"zoom",
"level",
"for",
"geometry",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/plotting.py#L56-L79
|
14,576
|
satellogic/telluric
|
telluric/plotting.py
|
layer_from_element
|
def layer_from_element(element, style_function=None):
"""Return Leaflet layer from shape.
Parameters
----------
element : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
"""
# This import is here to avoid cyclic references
from telluric.collections import BaseCollection
if isinstance(element, BaseCollection):
styled_element = element.map(lambda feat: style_element(feat, style_function))
else:
styled_element = style_element(element, style_function)
return GeoJSON(data=mapping(styled_element), name='GeoJSON')
|
python
|
def layer_from_element(element, style_function=None):
"""Return Leaflet layer from shape.
Parameters
----------
element : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
"""
# This import is here to avoid cyclic references
from telluric.collections import BaseCollection
if isinstance(element, BaseCollection):
styled_element = element.map(lambda feat: style_element(feat, style_function))
else:
styled_element = style_element(element, style_function)
return GeoJSON(data=mapping(styled_element), name='GeoJSON')
|
[
"def",
"layer_from_element",
"(",
"element",
",",
"style_function",
"=",
"None",
")",
":",
"# This import is here to avoid cyclic references",
"from",
"telluric",
".",
"collections",
"import",
"BaseCollection",
"if",
"isinstance",
"(",
"element",
",",
"BaseCollection",
")",
":",
"styled_element",
"=",
"element",
".",
"map",
"(",
"lambda",
"feat",
":",
"style_element",
"(",
"feat",
",",
"style_function",
")",
")",
"else",
":",
"styled_element",
"=",
"style_element",
"(",
"element",
",",
"style_function",
")",
"return",
"GeoJSON",
"(",
"data",
"=",
"mapping",
"(",
"styled_element",
")",
",",
"name",
"=",
"'GeoJSON'",
")"
] |
Return Leaflet layer from shape.
Parameters
----------
element : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
|
[
"Return",
"Leaflet",
"layer",
"from",
"shape",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/plotting.py#L96-L114
|
14,577
|
satellogic/telluric
|
telluric/plotting.py
|
plot
|
def plot(feature, mp=None, style_function=None, **map_kwargs):
"""Plots a GeoVector in an ipyleaflet map.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
mp : ipyleaflet.Map, optional
Map in which to plot, default to None (creates a new one).
style_function : func
Function that returns an style dictionary for
map_kwargs : kwargs, optional
Extra parameters to send to ipyleaflet.Map.
"""
map_kwargs.setdefault('basemap', basemaps.Stamen.Terrain)
if feature.is_empty:
warnings.warn("The geometry is empty.")
mp = Map(**map_kwargs) if mp is None else mp
else:
if mp is None:
center = feature.envelope.centroid.reproject(WGS84_CRS)
zoom = zoom_level_from_geometry(feature.envelope)
mp = Map(center=(center.y, center.x), zoom=zoom, **map_kwargs)
mp.add_layer(layer_from_element(feature, style_function))
return mp
|
python
|
def plot(feature, mp=None, style_function=None, **map_kwargs):
"""Plots a GeoVector in an ipyleaflet map.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
mp : ipyleaflet.Map, optional
Map in which to plot, default to None (creates a new one).
style_function : func
Function that returns an style dictionary for
map_kwargs : kwargs, optional
Extra parameters to send to ipyleaflet.Map.
"""
map_kwargs.setdefault('basemap', basemaps.Stamen.Terrain)
if feature.is_empty:
warnings.warn("The geometry is empty.")
mp = Map(**map_kwargs) if mp is None else mp
else:
if mp is None:
center = feature.envelope.centroid.reproject(WGS84_CRS)
zoom = zoom_level_from_geometry(feature.envelope)
mp = Map(center=(center.y, center.x), zoom=zoom, **map_kwargs)
mp.add_layer(layer_from_element(feature, style_function))
return mp
|
[
"def",
"plot",
"(",
"feature",
",",
"mp",
"=",
"None",
",",
"style_function",
"=",
"None",
",",
"*",
"*",
"map_kwargs",
")",
":",
"map_kwargs",
".",
"setdefault",
"(",
"'basemap'",
",",
"basemaps",
".",
"Stamen",
".",
"Terrain",
")",
"if",
"feature",
".",
"is_empty",
":",
"warnings",
".",
"warn",
"(",
"\"The geometry is empty.\"",
")",
"mp",
"=",
"Map",
"(",
"*",
"*",
"map_kwargs",
")",
"if",
"mp",
"is",
"None",
"else",
"mp",
"else",
":",
"if",
"mp",
"is",
"None",
":",
"center",
"=",
"feature",
".",
"envelope",
".",
"centroid",
".",
"reproject",
"(",
"WGS84_CRS",
")",
"zoom",
"=",
"zoom_level_from_geometry",
"(",
"feature",
".",
"envelope",
")",
"mp",
"=",
"Map",
"(",
"center",
"=",
"(",
"center",
".",
"y",
",",
"center",
".",
"x",
")",
",",
"zoom",
"=",
"zoom",
",",
"*",
"*",
"map_kwargs",
")",
"mp",
".",
"add_layer",
"(",
"layer_from_element",
"(",
"feature",
",",
"style_function",
")",
")",
"return",
"mp"
] |
Plots a GeoVector in an ipyleaflet map.
Parameters
----------
feature : telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection
Data to plot.
mp : ipyleaflet.Map, optional
Map in which to plot, default to None (creates a new one).
style_function : func
Function that returns an style dictionary for
map_kwargs : kwargs, optional
Extra parameters to send to ipyleaflet.Map.
|
[
"Plots",
"a",
"GeoVector",
"in",
"an",
"ipyleaflet",
"map",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/plotting.py#L117-L146
|
14,578
|
satellogic/telluric
|
telluric/util/tileserver_utils.py
|
tileserver_optimized_raster
|
def tileserver_optimized_raster(src, dest):
""" This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster in a cog way.
You could take the dest file upload it to a web server that supports ranges and user GeoRaster.get_tile
on it,
You are geranteed that you will get as minimal data as possible
"""
src_raster = tl.GeoRaster2.open(src)
bounding_box = src_raster.footprint().get_shape(tl.constants.WGS84_CRS).bounds
tile = mercantile.bounding_tile(*bounding_box)
dest_resolution = mercator_upper_zoom_level(src_raster)
bounds = tl.GeoVector.from_xyz(tile.x, tile.y, tile.z).get_bounds(tl.constants.WEB_MERCATOR_CRS)
create_options = {
"tiled": "YES",
"blocksize": 256,
"compress": "DEFLATE",
"photometric": "MINISBLACK"
}
with TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'temp.tif')
warp(src, temp_file, dst_crs=tl.constants.WEB_MERCATOR_CRS, resolution=dest_resolution,
dst_bounds=bounds, create_options=create_options)
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=True, GDAL_TIFF_OVR_BLOCKSIZE=256):
resampling = rasterio.enums.Resampling.gauss
with rasterio.open(temp_file, 'r+') as tmp_raster:
factors = _calc_overviews_factors(tmp_raster)
tmp_raster.build_overviews(factors, resampling=resampling)
tmp_raster.update_tags(ns='rio_overview', resampling=resampling.name)
telluric_tags = _get_telluric_tags(src)
if telluric_tags:
tmp_raster.update_tags(**telluric_tags)
rasterio_sh.copy(temp_file, dest,
COPY_SRC_OVERVIEWS=True, tiled=True,
compress='DEFLATE', photometric='MINISBLACK')
|
python
|
def tileserver_optimized_raster(src, dest):
""" This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster in a cog way.
You could take the dest file upload it to a web server that supports ranges and user GeoRaster.get_tile
on it,
You are geranteed that you will get as minimal data as possible
"""
src_raster = tl.GeoRaster2.open(src)
bounding_box = src_raster.footprint().get_shape(tl.constants.WGS84_CRS).bounds
tile = mercantile.bounding_tile(*bounding_box)
dest_resolution = mercator_upper_zoom_level(src_raster)
bounds = tl.GeoVector.from_xyz(tile.x, tile.y, tile.z).get_bounds(tl.constants.WEB_MERCATOR_CRS)
create_options = {
"tiled": "YES",
"blocksize": 256,
"compress": "DEFLATE",
"photometric": "MINISBLACK"
}
with TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'temp.tif')
warp(src, temp_file, dst_crs=tl.constants.WEB_MERCATOR_CRS, resolution=dest_resolution,
dst_bounds=bounds, create_options=create_options)
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=True, GDAL_TIFF_OVR_BLOCKSIZE=256):
resampling = rasterio.enums.Resampling.gauss
with rasterio.open(temp_file, 'r+') as tmp_raster:
factors = _calc_overviews_factors(tmp_raster)
tmp_raster.build_overviews(factors, resampling=resampling)
tmp_raster.update_tags(ns='rio_overview', resampling=resampling.name)
telluric_tags = _get_telluric_tags(src)
if telluric_tags:
tmp_raster.update_tags(**telluric_tags)
rasterio_sh.copy(temp_file, dest,
COPY_SRC_OVERVIEWS=True, tiled=True,
compress='DEFLATE', photometric='MINISBLACK')
|
[
"def",
"tileserver_optimized_raster",
"(",
"src",
",",
"dest",
")",
":",
"src_raster",
"=",
"tl",
".",
"GeoRaster2",
".",
"open",
"(",
"src",
")",
"bounding_box",
"=",
"src_raster",
".",
"footprint",
"(",
")",
".",
"get_shape",
"(",
"tl",
".",
"constants",
".",
"WGS84_CRS",
")",
".",
"bounds",
"tile",
"=",
"mercantile",
".",
"bounding_tile",
"(",
"*",
"bounding_box",
")",
"dest_resolution",
"=",
"mercator_upper_zoom_level",
"(",
"src_raster",
")",
"bounds",
"=",
"tl",
".",
"GeoVector",
".",
"from_xyz",
"(",
"tile",
".",
"x",
",",
"tile",
".",
"y",
",",
"tile",
".",
"z",
")",
".",
"get_bounds",
"(",
"tl",
".",
"constants",
".",
"WEB_MERCATOR_CRS",
")",
"create_options",
"=",
"{",
"\"tiled\"",
":",
"\"YES\"",
",",
"\"blocksize\"",
":",
"256",
",",
"\"compress\"",
":",
"\"DEFLATE\"",
",",
"\"photometric\"",
":",
"\"MINISBLACK\"",
"}",
"with",
"TemporaryDirectory",
"(",
")",
"as",
"temp_dir",
":",
"temp_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'temp.tif'",
")",
"warp",
"(",
"src",
",",
"temp_file",
",",
"dst_crs",
"=",
"tl",
".",
"constants",
".",
"WEB_MERCATOR_CRS",
",",
"resolution",
"=",
"dest_resolution",
",",
"dst_bounds",
"=",
"bounds",
",",
"create_options",
"=",
"create_options",
")",
"with",
"rasterio",
".",
"Env",
"(",
"GDAL_TIFF_INTERNAL_MASK",
"=",
"True",
",",
"GDAL_TIFF_OVR_BLOCKSIZE",
"=",
"256",
")",
":",
"resampling",
"=",
"rasterio",
".",
"enums",
".",
"Resampling",
".",
"gauss",
"with",
"rasterio",
".",
"open",
"(",
"temp_file",
",",
"'r+'",
")",
"as",
"tmp_raster",
":",
"factors",
"=",
"_calc_overviews_factors",
"(",
"tmp_raster",
")",
"tmp_raster",
".",
"build_overviews",
"(",
"factors",
",",
"resampling",
"=",
"resampling",
")",
"tmp_raster",
".",
"update_tags",
"(",
"ns",
"=",
"'rio_overview'",
",",
"resampling",
"=",
"resampling",
".",
"name",
")",
"telluric_tags",
"=",
"_get_telluric_tags",
"(",
"src",
")",
"if",
"telluric_tags",
":",
"tmp_raster",
".",
"update_tags",
"(",
"*",
"*",
"telluric_tags",
")",
"rasterio_sh",
".",
"copy",
"(",
"temp_file",
",",
"dest",
",",
"COPY_SRC_OVERVIEWS",
"=",
"True",
",",
"tiled",
"=",
"True",
",",
"compress",
"=",
"'DEFLATE'",
",",
"photometric",
"=",
"'MINISBLACK'",
")"
] |
This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster in a cog way.
You could take the dest file upload it to a web server that supports ranges and user GeoRaster.get_tile
on it,
You are geranteed that you will get as minimal data as possible
|
[
"This",
"method",
"converts",
"a",
"raster",
"to",
"a",
"tileserver",
"optimized",
"raster",
".",
"The",
"method",
"will",
"reproject",
"the",
"raster",
"to",
"align",
"to",
"the",
"xyz",
"system",
"in",
"resolution",
"and",
"projection",
"It",
"will",
"also",
"create",
"overviews",
"And",
"finally",
"it",
"will",
"arragne",
"the",
"raster",
"in",
"a",
"cog",
"way",
".",
"You",
"could",
"take",
"the",
"dest",
"file",
"upload",
"it",
"to",
"a",
"web",
"server",
"that",
"supports",
"ranges",
"and",
"user",
"GeoRaster",
".",
"get_tile",
"on",
"it",
"You",
"are",
"geranteed",
"that",
"you",
"will",
"get",
"as",
"minimal",
"data",
"as",
"possible"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/tileserver_utils.py#L20-L58
|
14,579
|
satellogic/telluric
|
telluric/vectors.py
|
get_dimension
|
def get_dimension(geometry):
"""Gets the dimension of a Fiona-like geometry element."""
coordinates = geometry["coordinates"]
type_ = geometry["type"]
if type_ in ('Point',):
return len(coordinates)
elif type_ in ('LineString', 'MultiPoint'):
return len(coordinates[0])
elif type_ in ('Polygon', 'MultiLineString'):
return len(coordinates[0][0])
elif type_ in ('MultiPolygon',):
return len(coordinates[0][0][0])
else:
raise ValueError("Invalid type '{}'".format(type_))
|
python
|
def get_dimension(geometry):
"""Gets the dimension of a Fiona-like geometry element."""
coordinates = geometry["coordinates"]
type_ = geometry["type"]
if type_ in ('Point',):
return len(coordinates)
elif type_ in ('LineString', 'MultiPoint'):
return len(coordinates[0])
elif type_ in ('Polygon', 'MultiLineString'):
return len(coordinates[0][0])
elif type_ in ('MultiPolygon',):
return len(coordinates[0][0][0])
else:
raise ValueError("Invalid type '{}'".format(type_))
|
[
"def",
"get_dimension",
"(",
"geometry",
")",
":",
"coordinates",
"=",
"geometry",
"[",
"\"coordinates\"",
"]",
"type_",
"=",
"geometry",
"[",
"\"type\"",
"]",
"if",
"type_",
"in",
"(",
"'Point'",
",",
")",
":",
"return",
"len",
"(",
"coordinates",
")",
"elif",
"type_",
"in",
"(",
"'LineString'",
",",
"'MultiPoint'",
")",
":",
"return",
"len",
"(",
"coordinates",
"[",
"0",
"]",
")",
"elif",
"type_",
"in",
"(",
"'Polygon'",
",",
"'MultiLineString'",
")",
":",
"return",
"len",
"(",
"coordinates",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"elif",
"type_",
"in",
"(",
"'MultiPolygon'",
",",
")",
":",
"return",
"len",
"(",
"coordinates",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid type '{}'\"",
".",
"format",
"(",
"type_",
")",
")"
] |
Gets the dimension of a Fiona-like geometry element.
|
[
"Gets",
"the",
"dimension",
"of",
"a",
"Fiona",
"-",
"like",
"geometry",
"element",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L82-L95
|
14,580
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.from_geojson
|
def from_geojson(cls, filename):
"""Load vector from geojson."""
with open(filename) as fd:
geometry = json.load(fd)
if 'type' not in geometry:
raise TypeError("%s is not a valid geojson." % (filename,))
return cls(to_shape(geometry), WGS84_CRS)
|
python
|
def from_geojson(cls, filename):
"""Load vector from geojson."""
with open(filename) as fd:
geometry = json.load(fd)
if 'type' not in geometry:
raise TypeError("%s is not a valid geojson." % (filename,))
return cls(to_shape(geometry), WGS84_CRS)
|
[
"def",
"from_geojson",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"geometry",
"=",
"json",
".",
"load",
"(",
"fd",
")",
"if",
"'type'",
"not",
"in",
"geometry",
":",
"raise",
"TypeError",
"(",
"\"%s is not a valid geojson.\"",
"%",
"(",
"filename",
",",
")",
")",
"return",
"cls",
"(",
"to_shape",
"(",
"geometry",
")",
",",
"WGS84_CRS",
")"
] |
Load vector from geojson.
|
[
"Load",
"vector",
"from",
"geojson",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L296-L304
|
14,581
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.to_geojson
|
def to_geojson(self, filename):
"""Save vector as geojson."""
with open(filename, 'w') as fd:
json.dump(self.to_record(WGS84_CRS), fd)
|
python
|
def to_geojson(self, filename):
"""Save vector as geojson."""
with open(filename, 'w') as fd:
json.dump(self.to_record(WGS84_CRS), fd)
|
[
"def",
"to_geojson",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fd",
":",
"json",
".",
"dump",
"(",
"self",
".",
"to_record",
"(",
"WGS84_CRS",
")",
",",
"fd",
")"
] |
Save vector as geojson.
|
[
"Save",
"vector",
"as",
"geojson",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L306-L309
|
14,582
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.from_bounds
|
def from_bounds(cls, xmin, ymin, xmax, ymax, crs=DEFAULT_CRS):
"""Creates GeoVector object from bounds.
Parameters
----------
xmin, ymin, xmax, ymax : float
Bounds of the GeoVector. Also (east, south, north, west).
crs : ~rasterio.crs.CRS, dict
Projection, default to :py:data:`telluric.constants.DEFAULT_CRS`.
Examples
--------
>>> from telluric import GeoVector
>>> GeoVector.from_bounds(xmin=0, ymin=0, xmax=1, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
>>> GeoVector.from_bounds(xmin=0, xmax=1, ymin=0, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
"""
return cls(Polygon.from_bounds(xmin, ymin, xmax, ymax), crs)
|
python
|
def from_bounds(cls, xmin, ymin, xmax, ymax, crs=DEFAULT_CRS):
"""Creates GeoVector object from bounds.
Parameters
----------
xmin, ymin, xmax, ymax : float
Bounds of the GeoVector. Also (east, south, north, west).
crs : ~rasterio.crs.CRS, dict
Projection, default to :py:data:`telluric.constants.DEFAULT_CRS`.
Examples
--------
>>> from telluric import GeoVector
>>> GeoVector.from_bounds(xmin=0, ymin=0, xmax=1, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
>>> GeoVector.from_bounds(xmin=0, xmax=1, ymin=0, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
"""
return cls(Polygon.from_bounds(xmin, ymin, xmax, ymax), crs)
|
[
"def",
"from_bounds",
"(",
"cls",
",",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"crs",
"=",
"DEFAULT_CRS",
")",
":",
"return",
"cls",
"(",
"Polygon",
".",
"from_bounds",
"(",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
")",
",",
"crs",
")"
] |
Creates GeoVector object from bounds.
Parameters
----------
xmin, ymin, xmax, ymax : float
Bounds of the GeoVector. Also (east, south, north, west).
crs : ~rasterio.crs.CRS, dict
Projection, default to :py:data:`telluric.constants.DEFAULT_CRS`.
Examples
--------
>>> from telluric import GeoVector
>>> GeoVector.from_bounds(xmin=0, ymin=0, xmax=1, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
>>> GeoVector.from_bounds(xmin=0, xmax=1, ymin=0, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
|
[
"Creates",
"GeoVector",
"object",
"from",
"bounds",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L328-L347
|
14,583
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.from_xyz
|
def from_xyz(cls, x, y, z):
"""Creates GeoVector from Mercator slippy map values.
"""
bb = xy_bounds(x, y, z)
return cls.from_bounds(xmin=bb.left, ymin=bb.bottom,
xmax=bb.right, ymax=bb.top,
crs=WEB_MERCATOR_CRS)
|
python
|
def from_xyz(cls, x, y, z):
"""Creates GeoVector from Mercator slippy map values.
"""
bb = xy_bounds(x, y, z)
return cls.from_bounds(xmin=bb.left, ymin=bb.bottom,
xmax=bb.right, ymax=bb.top,
crs=WEB_MERCATOR_CRS)
|
[
"def",
"from_xyz",
"(",
"cls",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"bb",
"=",
"xy_bounds",
"(",
"x",
",",
"y",
",",
"z",
")",
"return",
"cls",
".",
"from_bounds",
"(",
"xmin",
"=",
"bb",
".",
"left",
",",
"ymin",
"=",
"bb",
".",
"bottom",
",",
"xmax",
"=",
"bb",
".",
"right",
",",
"ymax",
"=",
"bb",
".",
"top",
",",
"crs",
"=",
"WEB_MERCATOR_CRS",
")"
] |
Creates GeoVector from Mercator slippy map values.
|
[
"Creates",
"GeoVector",
"from",
"Mercator",
"slippy",
"map",
"values",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L350-L357
|
14,584
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.cascaded_union
|
def cascaded_union(cls, vectors, dst_crs, prevalidate=False):
# type: (list, CRS, bool) -> GeoVector
"""Generate a GeoVector from the cascade union of the impute vectors."""
try:
shapes = [geometry.get_shape(dst_crs) for geometry in vectors]
if prevalidate:
if not all([sh.is_valid for sh in shapes]):
warnings.warn(
"Some invalid shapes found, discarding them."
)
except IndexError:
crs = DEFAULT_CRS
shapes = []
return cls(
cascaded_union([sh for sh in shapes if sh.is_valid]).simplify(0),
crs=dst_crs
)
|
python
|
def cascaded_union(cls, vectors, dst_crs, prevalidate=False):
# type: (list, CRS, bool) -> GeoVector
"""Generate a GeoVector from the cascade union of the impute vectors."""
try:
shapes = [geometry.get_shape(dst_crs) for geometry in vectors]
if prevalidate:
if not all([sh.is_valid for sh in shapes]):
warnings.warn(
"Some invalid shapes found, discarding them."
)
except IndexError:
crs = DEFAULT_CRS
shapes = []
return cls(
cascaded_union([sh for sh in shapes if sh.is_valid]).simplify(0),
crs=dst_crs
)
|
[
"def",
"cascaded_union",
"(",
"cls",
",",
"vectors",
",",
"dst_crs",
",",
"prevalidate",
"=",
"False",
")",
":",
"# type: (list, CRS, bool) -> GeoVector",
"try",
":",
"shapes",
"=",
"[",
"geometry",
".",
"get_shape",
"(",
"dst_crs",
")",
"for",
"geometry",
"in",
"vectors",
"]",
"if",
"prevalidate",
":",
"if",
"not",
"all",
"(",
"[",
"sh",
".",
"is_valid",
"for",
"sh",
"in",
"shapes",
"]",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Some invalid shapes found, discarding them.\"",
")",
"except",
"IndexError",
":",
"crs",
"=",
"DEFAULT_CRS",
"shapes",
"=",
"[",
"]",
"return",
"cls",
"(",
"cascaded_union",
"(",
"[",
"sh",
"for",
"sh",
"in",
"shapes",
"if",
"sh",
".",
"is_valid",
"]",
")",
".",
"simplify",
"(",
"0",
")",
",",
"crs",
"=",
"dst_crs",
")"
] |
Generate a GeoVector from the cascade union of the impute vectors.
|
[
"Generate",
"a",
"GeoVector",
"from",
"the",
"cascade",
"union",
"of",
"the",
"impute",
"vectors",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L384-L403
|
14,585
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.from_record
|
def from_record(cls, record, crs):
"""Load vector from record."""
if 'type' not in record:
raise TypeError("The data isn't a valid record.")
return cls(to_shape(record), crs)
|
python
|
def from_record(cls, record, crs):
"""Load vector from record."""
if 'type' not in record:
raise TypeError("The data isn't a valid record.")
return cls(to_shape(record), crs)
|
[
"def",
"from_record",
"(",
"cls",
",",
"record",
",",
"crs",
")",
":",
"if",
"'type'",
"not",
"in",
"record",
":",
"raise",
"TypeError",
"(",
"\"The data isn't a valid record.\"",
")",
"return",
"cls",
"(",
"to_shape",
"(",
"record",
")",
",",
"crs",
")"
] |
Load vector from record.
|
[
"Load",
"vector",
"from",
"record",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L444-L449
|
14,586
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.get_bounding_box
|
def get_bounding_box(self, crs):
"""Gets bounding box as GeoVector in a specified CRS."""
return self.from_bounds(*self.get_bounds(crs), crs=crs)
|
python
|
def get_bounding_box(self, crs):
"""Gets bounding box as GeoVector in a specified CRS."""
return self.from_bounds(*self.get_bounds(crs), crs=crs)
|
[
"def",
"get_bounding_box",
"(",
"self",
",",
"crs",
")",
":",
"return",
"self",
".",
"from_bounds",
"(",
"*",
"self",
".",
"get_bounds",
"(",
"crs",
")",
",",
"crs",
"=",
"crs",
")"
] |
Gets bounding box as GeoVector in a specified CRS.
|
[
"Gets",
"bounding",
"box",
"as",
"GeoVector",
"in",
"a",
"specified",
"CRS",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L464-L466
|
14,587
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.polygonize
|
def polygonize(self, width, cap_style_line=CAP_STYLE.flat, cap_style_point=CAP_STYLE.round):
"""Turns line or point into a buffered polygon."""
shape = self._shape
if isinstance(shape, (LineString, MultiLineString)):
return self.__class__(
shape.buffer(width / 2, cap_style=cap_style_line),
self.crs
)
elif isinstance(shape, (Point, MultiPoint)):
return self.__class__(
shape.buffer(width / 2, cap_style=cap_style_point),
self.crs
)
else:
return self
|
python
|
def polygonize(self, width, cap_style_line=CAP_STYLE.flat, cap_style_point=CAP_STYLE.round):
"""Turns line or point into a buffered polygon."""
shape = self._shape
if isinstance(shape, (LineString, MultiLineString)):
return self.__class__(
shape.buffer(width / 2, cap_style=cap_style_line),
self.crs
)
elif isinstance(shape, (Point, MultiPoint)):
return self.__class__(
shape.buffer(width / 2, cap_style=cap_style_point),
self.crs
)
else:
return self
|
[
"def",
"polygonize",
"(",
"self",
",",
"width",
",",
"cap_style_line",
"=",
"CAP_STYLE",
".",
"flat",
",",
"cap_style_point",
"=",
"CAP_STYLE",
".",
"round",
")",
":",
"shape",
"=",
"self",
".",
"_shape",
"if",
"isinstance",
"(",
"shape",
",",
"(",
"LineString",
",",
"MultiLineString",
")",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"shape",
".",
"buffer",
"(",
"width",
"/",
"2",
",",
"cap_style",
"=",
"cap_style_line",
")",
",",
"self",
".",
"crs",
")",
"elif",
"isinstance",
"(",
"shape",
",",
"(",
"Point",
",",
"MultiPoint",
")",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"shape",
".",
"buffer",
"(",
"width",
"/",
"2",
",",
"cap_style",
"=",
"cap_style_point",
")",
",",
"self",
".",
"crs",
")",
"else",
":",
"return",
"self"
] |
Turns line or point into a buffered polygon.
|
[
"Turns",
"line",
"or",
"point",
"into",
"a",
"buffered",
"polygon",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L504-L518
|
14,588
|
satellogic/telluric
|
telluric/vectors.py
|
GeoVector.tiles
|
def tiles(self, zooms, truncate=False):
"""
Iterator over the tiles intersecting the bounding box of the vector
Parameters
----------
zooms : int or sequence of int
One or more zoom levels.
truncate : bool, optional
Whether or not to truncate inputs to web mercator limits.
Yields
------
mercantile.Tile object (`namedtuple` with x, y, z)
"""
west, south, east, north = self.get_bounds(WGS84_CRS)
return tiles(west, south, east, north, zooms, truncate)
|
python
|
def tiles(self, zooms, truncate=False):
"""
Iterator over the tiles intersecting the bounding box of the vector
Parameters
----------
zooms : int or sequence of int
One or more zoom levels.
truncate : bool, optional
Whether or not to truncate inputs to web mercator limits.
Yields
------
mercantile.Tile object (`namedtuple` with x, y, z)
"""
west, south, east, north = self.get_bounds(WGS84_CRS)
return tiles(west, south, east, north, zooms, truncate)
|
[
"def",
"tiles",
"(",
"self",
",",
"zooms",
",",
"truncate",
"=",
"False",
")",
":",
"west",
",",
"south",
",",
"east",
",",
"north",
"=",
"self",
".",
"get_bounds",
"(",
"WGS84_CRS",
")",
"return",
"tiles",
"(",
"west",
",",
"south",
",",
"east",
",",
"north",
",",
"zooms",
",",
"truncate",
")"
] |
Iterator over the tiles intersecting the bounding box of the vector
Parameters
----------
zooms : int or sequence of int
One or more zoom levels.
truncate : bool, optional
Whether or not to truncate inputs to web mercator limits.
Yields
------
mercantile.Tile object (`namedtuple` with x, y, z)
|
[
"Iterator",
"over",
"the",
"tiles",
"intersecting",
"the",
"bounding",
"box",
"of",
"the",
"vector"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L520-L536
|
14,589
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
_join_masks_from_masked_array
|
def _join_masks_from_masked_array(data):
"""Union of masks."""
if not isinstance(data.mask, np.ndarray):
# workaround to handle mask compressed to single value
mask = np.empty(data.data.shape, dtype=np.bool)
mask.fill(data.mask)
return mask
mask = data.mask[0].copy()
for i in range(1, len(data.mask)):
mask = np.logical_or(mask, data.mask[i])
return mask[np.newaxis, :, :]
|
python
|
def _join_masks_from_masked_array(data):
"""Union of masks."""
if not isinstance(data.mask, np.ndarray):
# workaround to handle mask compressed to single value
mask = np.empty(data.data.shape, dtype=np.bool)
mask.fill(data.mask)
return mask
mask = data.mask[0].copy()
for i in range(1, len(data.mask)):
mask = np.logical_or(mask, data.mask[i])
return mask[np.newaxis, :, :]
|
[
"def",
"_join_masks_from_masked_array",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
".",
"mask",
",",
"np",
".",
"ndarray",
")",
":",
"# workaround to handle mask compressed to single value",
"mask",
"=",
"np",
".",
"empty",
"(",
"data",
".",
"data",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"mask",
".",
"fill",
"(",
"data",
".",
"mask",
")",
"return",
"mask",
"mask",
"=",
"data",
".",
"mask",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"data",
".",
"mask",
")",
")",
":",
"mask",
"=",
"np",
".",
"logical_or",
"(",
"mask",
",",
"data",
".",
"mask",
"[",
"i",
"]",
")",
"return",
"mask",
"[",
"np",
".",
"newaxis",
",",
":",
",",
":",
"]"
] |
Union of masks.
|
[
"Union",
"of",
"masks",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L27-L37
|
14,590
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
_creation_options_for_cog
|
def _creation_options_for_cog(creation_options, source_profile, blocksize):
"""
it uses the profile of the source raster, override anything using the creation_options
and guarantees we will have tiled raster and blocksize
"""
if not(creation_options):
creation_options = {}
creation_options["blocksize"] = blocksize
creation_options["tiled"] = True
defaults = {"nodata": None, "compress": "lzw"}
for key in ["nodata", "compress"]:
if key not in creation_options:
creation_options[key] = source_profile.get(key, defaults.get(key))
return creation_options
|
python
|
def _creation_options_for_cog(creation_options, source_profile, blocksize):
"""
it uses the profile of the source raster, override anything using the creation_options
and guarantees we will have tiled raster and blocksize
"""
if not(creation_options):
creation_options = {}
creation_options["blocksize"] = blocksize
creation_options["tiled"] = True
defaults = {"nodata": None, "compress": "lzw"}
for key in ["nodata", "compress"]:
if key not in creation_options:
creation_options[key] = source_profile.get(key, defaults.get(key))
return creation_options
|
[
"def",
"_creation_options_for_cog",
"(",
"creation_options",
",",
"source_profile",
",",
"blocksize",
")",
":",
"if",
"not",
"(",
"creation_options",
")",
":",
"creation_options",
"=",
"{",
"}",
"creation_options",
"[",
"\"blocksize\"",
"]",
"=",
"blocksize",
"creation_options",
"[",
"\"tiled\"",
"]",
"=",
"True",
"defaults",
"=",
"{",
"\"nodata\"",
":",
"None",
",",
"\"compress\"",
":",
"\"lzw\"",
"}",
"for",
"key",
"in",
"[",
"\"nodata\"",
",",
"\"compress\"",
"]",
":",
"if",
"key",
"not",
"in",
"creation_options",
":",
"creation_options",
"[",
"key",
"]",
"=",
"source_profile",
".",
"get",
"(",
"key",
",",
"defaults",
".",
"get",
"(",
"key",
")",
")",
"return",
"creation_options"
] |
it uses the profile of the source raster, override anything using the creation_options
and guarantees we will have tiled raster and blocksize
|
[
"it",
"uses",
"the",
"profile",
"of",
"the",
"source",
"raster",
"override",
"anything",
"using",
"the",
"creation_options",
"and",
"guarantees",
"we",
"will",
"have",
"tiled",
"raster",
"and",
"blocksize"
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L70-L84
|
14,591
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
convert_to_cog
|
def convert_to_cog(source_file, destination_file, resampling=rasterio.enums.Resampling.gauss, blocksize=256,
overview_blocksize=256, creation_options=None):
"""Convert source file to a Cloud Optimized GeoTiff new file.
:param source_file: path to the original raster
:param destination_file: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: <dictioanry>, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
"""
with rasterio.open(source_file) as src:
# creation_options overrides proile
source_profile = src.profile
creation_options = _creation_options_for_cog(creation_options, source_profile, blocksize)
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=True, GDAL_TIFF_OVR_BLOCKSIZE=overview_blocksize):
with TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'temp.tif')
rasterio_sh.copy(source_file, temp_file, **creation_options)
with rasterio.open(temp_file, 'r+') as dest:
factors = _calc_overviews_factors(dest)
dest.build_overviews(factors, resampling=resampling)
dest.update_tags(ns='rio_overview', resampling=resampling.name)
telluric_tags = _get_telluric_tags(source_file)
if telluric_tags:
dest.update_tags(**telluric_tags)
rasterio_sh.copy(temp_file, destination_file,
COPY_SRC_OVERVIEWS=True, **creation_options)
|
python
|
def convert_to_cog(source_file, destination_file, resampling=rasterio.enums.Resampling.gauss, blocksize=256,
overview_blocksize=256, creation_options=None):
"""Convert source file to a Cloud Optimized GeoTiff new file.
:param source_file: path to the original raster
:param destination_file: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: <dictioanry>, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
"""
with rasterio.open(source_file) as src:
# creation_options overrides proile
source_profile = src.profile
creation_options = _creation_options_for_cog(creation_options, source_profile, blocksize)
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=True, GDAL_TIFF_OVR_BLOCKSIZE=overview_blocksize):
with TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'temp.tif')
rasterio_sh.copy(source_file, temp_file, **creation_options)
with rasterio.open(temp_file, 'r+') as dest:
factors = _calc_overviews_factors(dest)
dest.build_overviews(factors, resampling=resampling)
dest.update_tags(ns='rio_overview', resampling=resampling.name)
telluric_tags = _get_telluric_tags(source_file)
if telluric_tags:
dest.update_tags(**telluric_tags)
rasterio_sh.copy(temp_file, destination_file,
COPY_SRC_OVERVIEWS=True, **creation_options)
|
[
"def",
"convert_to_cog",
"(",
"source_file",
",",
"destination_file",
",",
"resampling",
"=",
"rasterio",
".",
"enums",
".",
"Resampling",
".",
"gauss",
",",
"blocksize",
"=",
"256",
",",
"overview_blocksize",
"=",
"256",
",",
"creation_options",
"=",
"None",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"source_file",
")",
"as",
"src",
":",
"# creation_options overrides proile",
"source_profile",
"=",
"src",
".",
"profile",
"creation_options",
"=",
"_creation_options_for_cog",
"(",
"creation_options",
",",
"source_profile",
",",
"blocksize",
")",
"with",
"rasterio",
".",
"Env",
"(",
"GDAL_TIFF_INTERNAL_MASK",
"=",
"True",
",",
"GDAL_TIFF_OVR_BLOCKSIZE",
"=",
"overview_blocksize",
")",
":",
"with",
"TemporaryDirectory",
"(",
")",
"as",
"temp_dir",
":",
"temp_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'temp.tif'",
")",
"rasterio_sh",
".",
"copy",
"(",
"source_file",
",",
"temp_file",
",",
"*",
"*",
"creation_options",
")",
"with",
"rasterio",
".",
"open",
"(",
"temp_file",
",",
"'r+'",
")",
"as",
"dest",
":",
"factors",
"=",
"_calc_overviews_factors",
"(",
"dest",
")",
"dest",
".",
"build_overviews",
"(",
"factors",
",",
"resampling",
"=",
"resampling",
")",
"dest",
".",
"update_tags",
"(",
"ns",
"=",
"'rio_overview'",
",",
"resampling",
"=",
"resampling",
".",
"name",
")",
"telluric_tags",
"=",
"_get_telluric_tags",
"(",
"source_file",
")",
"if",
"telluric_tags",
":",
"dest",
".",
"update_tags",
"(",
"*",
"*",
"telluric_tags",
")",
"rasterio_sh",
".",
"copy",
"(",
"temp_file",
",",
"destination_file",
",",
"COPY_SRC_OVERVIEWS",
"=",
"True",
",",
"*",
"*",
"creation_options",
")"
] |
Convert source file to a Cloud Optimized GeoTiff new file.
:param source_file: path to the original raster
:param destination_file: path to the new raster
:param resampling: which Resampling to use on reading, default Resampling.gauss
:param blocksize: the size of the blocks default 256
:param overview_blocksize: the block size of the overviews, default 256
:param creation_options: <dictioanry>, options that can override the source raster profile,
notice that you can't override tiled=True, and the blocksize
|
[
"Convert",
"source",
"file",
"to",
"a",
"Cloud",
"Optimized",
"GeoTiff",
"new",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L87-L119
|
14,592
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
warp
|
def warp(source_file, destination_file, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, src_nodata=None, dst_nodata=None,
target_aligned_pixels=False, check_invert_proj=True,
creation_options=None, resampling=Resampling.cubic, **kwargs):
"""Warp a raster dataset.
Parameters
------------
source_file: str, file object or pathlib.Path object
Source file.
destination_file: str, file object or pathlib.Path object
Destination file.
dst_crs: rasterio.crs.CRS, optional
Target coordinate reference system.
resolution: tuple (x resolution, y resolution) or float, optional
Target resolution, in units of target coordinate reference
system.
dimensions: tuple (width, height), optional
Output file size in pixels and lines.
src_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from source bounds
(in source georeferenced units).
dst_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from destination bounds
(in destination georeferenced units).
src_nodata: int, float, or nan, optional
Manually overridden source nodata.
dst_nodata: int, float, or nan, optional
Manually overridden destination nodata.
target_aligned_pixels: bool, optional
Align the output bounds based on the resolution.
Default is `False`.
check_invert_proj: bool, optional
Constrain output to valid coordinate region in dst_crs.
Default is `True`.
creation_options: dict, optional
Custom creation options.
resampling: rasterio.enums.Resampling
Reprojection resampling method. Default is `cubic`.
kwargs: optional
Additional arguments passed to transformation function.
Returns
---------
out: None
Output is written to destination.
"""
with rasterio.Env(CHECK_WITH_INVERT_PROJ=check_invert_proj):
with rasterio.open(source_file) as src:
out_kwargs = src.profile.copy()
dst_crs, dst_transform, dst_width, dst_height = calc_transform(
src, dst_crs, resolution, dimensions,
src_bounds, dst_bounds, target_aligned_pixels)
# If src_nodata is not None, update the dst metadata NODATA
# value to src_nodata (will be overridden by dst_nodata if it is not None.
if src_nodata is not None:
# Update the destination NODATA value
out_kwargs.update({
'nodata': src_nodata
})
# Validate a manually set destination NODATA value.
if dst_nodata is not None:
if src_nodata is None and src.meta['nodata'] is None:
raise ValueError('src_nodata must be provided because dst_nodata is not None')
else:
out_kwargs.update({'nodata': dst_nodata})
out_kwargs.update({
'crs': dst_crs,
'transform': dst_transform,
'width': dst_width,
'height': dst_height
})
# Adjust block size if necessary.
if ('blockxsize' in out_kwargs and
dst_width < out_kwargs['blockxsize']):
del out_kwargs['blockxsize']
if ('blockysize' in out_kwargs and
dst_height < out_kwargs['blockysize']):
del out_kwargs['blockysize']
if creation_options is not None:
out_kwargs.update(**creation_options)
with rasterio.open(destination_file, 'w', **out_kwargs) as dst:
reproject(
source=rasterio.band(src, src.indexes),
destination=rasterio.band(dst, dst.indexes),
src_transform=src.transform,
src_crs=src.crs,
src_nodata=src_nodata,
dst_transform=out_kwargs['transform'],
dst_crs=out_kwargs['crs'],
dst_nodata=dst_nodata,
resampling=resampling,
**kwargs)
|
python
|
def warp(source_file, destination_file, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, src_nodata=None, dst_nodata=None,
target_aligned_pixels=False, check_invert_proj=True,
creation_options=None, resampling=Resampling.cubic, **kwargs):
"""Warp a raster dataset.
Parameters
------------
source_file: str, file object or pathlib.Path object
Source file.
destination_file: str, file object or pathlib.Path object
Destination file.
dst_crs: rasterio.crs.CRS, optional
Target coordinate reference system.
resolution: tuple (x resolution, y resolution) or float, optional
Target resolution, in units of target coordinate reference
system.
dimensions: tuple (width, height), optional
Output file size in pixels and lines.
src_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from source bounds
(in source georeferenced units).
dst_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from destination bounds
(in destination georeferenced units).
src_nodata: int, float, or nan, optional
Manually overridden source nodata.
dst_nodata: int, float, or nan, optional
Manually overridden destination nodata.
target_aligned_pixels: bool, optional
Align the output bounds based on the resolution.
Default is `False`.
check_invert_proj: bool, optional
Constrain output to valid coordinate region in dst_crs.
Default is `True`.
creation_options: dict, optional
Custom creation options.
resampling: rasterio.enums.Resampling
Reprojection resampling method. Default is `cubic`.
kwargs: optional
Additional arguments passed to transformation function.
Returns
---------
out: None
Output is written to destination.
"""
with rasterio.Env(CHECK_WITH_INVERT_PROJ=check_invert_proj):
with rasterio.open(source_file) as src:
out_kwargs = src.profile.copy()
dst_crs, dst_transform, dst_width, dst_height = calc_transform(
src, dst_crs, resolution, dimensions,
src_bounds, dst_bounds, target_aligned_pixels)
# If src_nodata is not None, update the dst metadata NODATA
# value to src_nodata (will be overridden by dst_nodata if it is not None.
if src_nodata is not None:
# Update the destination NODATA value
out_kwargs.update({
'nodata': src_nodata
})
# Validate a manually set destination NODATA value.
if dst_nodata is not None:
if src_nodata is None and src.meta['nodata'] is None:
raise ValueError('src_nodata must be provided because dst_nodata is not None')
else:
out_kwargs.update({'nodata': dst_nodata})
out_kwargs.update({
'crs': dst_crs,
'transform': dst_transform,
'width': dst_width,
'height': dst_height
})
# Adjust block size if necessary.
if ('blockxsize' in out_kwargs and
dst_width < out_kwargs['blockxsize']):
del out_kwargs['blockxsize']
if ('blockysize' in out_kwargs and
dst_height < out_kwargs['blockysize']):
del out_kwargs['blockysize']
if creation_options is not None:
out_kwargs.update(**creation_options)
with rasterio.open(destination_file, 'w', **out_kwargs) as dst:
reproject(
source=rasterio.band(src, src.indexes),
destination=rasterio.band(dst, dst.indexes),
src_transform=src.transform,
src_crs=src.crs,
src_nodata=src_nodata,
dst_transform=out_kwargs['transform'],
dst_crs=out_kwargs['crs'],
dst_nodata=dst_nodata,
resampling=resampling,
**kwargs)
|
[
"def",
"warp",
"(",
"source_file",
",",
"destination_file",
",",
"dst_crs",
"=",
"None",
",",
"resolution",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"src_bounds",
"=",
"None",
",",
"dst_bounds",
"=",
"None",
",",
"src_nodata",
"=",
"None",
",",
"dst_nodata",
"=",
"None",
",",
"target_aligned_pixels",
"=",
"False",
",",
"check_invert_proj",
"=",
"True",
",",
"creation_options",
"=",
"None",
",",
"resampling",
"=",
"Resampling",
".",
"cubic",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rasterio",
".",
"Env",
"(",
"CHECK_WITH_INVERT_PROJ",
"=",
"check_invert_proj",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"source_file",
")",
"as",
"src",
":",
"out_kwargs",
"=",
"src",
".",
"profile",
".",
"copy",
"(",
")",
"dst_crs",
",",
"dst_transform",
",",
"dst_width",
",",
"dst_height",
"=",
"calc_transform",
"(",
"src",
",",
"dst_crs",
",",
"resolution",
",",
"dimensions",
",",
"src_bounds",
",",
"dst_bounds",
",",
"target_aligned_pixels",
")",
"# If src_nodata is not None, update the dst metadata NODATA",
"# value to src_nodata (will be overridden by dst_nodata if it is not None.",
"if",
"src_nodata",
"is",
"not",
"None",
":",
"# Update the destination NODATA value",
"out_kwargs",
".",
"update",
"(",
"{",
"'nodata'",
":",
"src_nodata",
"}",
")",
"# Validate a manually set destination NODATA value.",
"if",
"dst_nodata",
"is",
"not",
"None",
":",
"if",
"src_nodata",
"is",
"None",
"and",
"src",
".",
"meta",
"[",
"'nodata'",
"]",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'src_nodata must be provided because dst_nodata is not None'",
")",
"else",
":",
"out_kwargs",
".",
"update",
"(",
"{",
"'nodata'",
":",
"dst_nodata",
"}",
")",
"out_kwargs",
".",
"update",
"(",
"{",
"'crs'",
":",
"dst_crs",
",",
"'transform'",
":",
"dst_transform",
",",
"'width'",
":",
"dst_width",
",",
"'height'",
":",
"dst_height",
"}",
")",
"# Adjust block size if necessary.",
"if",
"(",
"'blockxsize'",
"in",
"out_kwargs",
"and",
"dst_width",
"<",
"out_kwargs",
"[",
"'blockxsize'",
"]",
")",
":",
"del",
"out_kwargs",
"[",
"'blockxsize'",
"]",
"if",
"(",
"'blockysize'",
"in",
"out_kwargs",
"and",
"dst_height",
"<",
"out_kwargs",
"[",
"'blockysize'",
"]",
")",
":",
"del",
"out_kwargs",
"[",
"'blockysize'",
"]",
"if",
"creation_options",
"is",
"not",
"None",
":",
"out_kwargs",
".",
"update",
"(",
"*",
"*",
"creation_options",
")",
"with",
"rasterio",
".",
"open",
"(",
"destination_file",
",",
"'w'",
",",
"*",
"*",
"out_kwargs",
")",
"as",
"dst",
":",
"reproject",
"(",
"source",
"=",
"rasterio",
".",
"band",
"(",
"src",
",",
"src",
".",
"indexes",
")",
",",
"destination",
"=",
"rasterio",
".",
"band",
"(",
"dst",
",",
"dst",
".",
"indexes",
")",
",",
"src_transform",
"=",
"src",
".",
"transform",
",",
"src_crs",
"=",
"src",
".",
"crs",
",",
"src_nodata",
"=",
"src_nodata",
",",
"dst_transform",
"=",
"out_kwargs",
"[",
"'transform'",
"]",
",",
"dst_crs",
"=",
"out_kwargs",
"[",
"'crs'",
"]",
",",
"dst_nodata",
"=",
"dst_nodata",
",",
"resampling",
"=",
"resampling",
",",
"*",
"*",
"kwargs",
")"
] |
Warp a raster dataset.
Parameters
------------
source_file: str, file object or pathlib.Path object
Source file.
destination_file: str, file object or pathlib.Path object
Destination file.
dst_crs: rasterio.crs.CRS, optional
Target coordinate reference system.
resolution: tuple (x resolution, y resolution) or float, optional
Target resolution, in units of target coordinate reference
system.
dimensions: tuple (width, height), optional
Output file size in pixels and lines.
src_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from source bounds
(in source georeferenced units).
dst_bounds: tuple (xmin, ymin, xmax, ymax), optional
Georeferenced extent of output file from destination bounds
(in destination georeferenced units).
src_nodata: int, float, or nan, optional
Manually overridden source nodata.
dst_nodata: int, float, or nan, optional
Manually overridden destination nodata.
target_aligned_pixels: bool, optional
Align the output bounds based on the resolution.
Default is `False`.
check_invert_proj: bool, optional
Constrain output to valid coordinate region in dst_crs.
Default is `True`.
creation_options: dict, optional
Custom creation options.
resampling: rasterio.enums.Resampling
Reprojection resampling method. Default is `cubic`.
kwargs: optional
Additional arguments passed to transformation function.
Returns
---------
out: None
Output is written to destination.
|
[
"Warp",
"a",
"raster",
"dataset",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L261-L360
|
14,593
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
build_overviews
|
def build_overviews(source_file, factors=None, minsize=256, external=False,
blocksize=256, interleave='pixel', compress='lzw',
resampling=Resampling.gauss, **kwargs):
"""Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
------------
source_file : str, file object or pathlib.Path object
Source file.
factors : list, optional
A list of integral overview levels to build.
minsize : int, optional
Maximum width or height of the smallest overview level. Only taken into account
if explicit factors are not specified. Defaults to `256`.
external : bool, optional
Can be set to `True` to force external overviews in the GeoTIFF (.ovr) format.
Default is False.
blocksize : int, optional
The block size (tile width and height) used for overviews. Should be a
power-of-two value between 64 and 4096. Default value is `256`.
interleave : str, optional
Interleaving. Default value is `pixel`.
compress : str, optional
Set the compression to use. Default is `lzw`.
resampling : rasterio.enums.Resampling
Resampling method. Default is `gauss`.
kwargs : optional
Additional arguments passed to rasterio.Env.
Returns
---------
out: None
Original file is altered or external .ovr can be created.
"""
with rasterio.open(source_file, 'r+') as dst:
if factors is None:
factors = _calc_overviews_factors(
SimpleNamespace(width=dst.width, height=dst.height), minsize)
with rasterio.Env(
GDAL_TIFF_OVR_BLOCKSIZE=blocksize,
INTERLEAVE_OVERVIEW=interleave,
COMPRESS_OVERVIEW=compress,
TIFF_USE_OVR=external,
**kwargs
):
dst.build_overviews(factors, resampling)
|
python
|
def build_overviews(source_file, factors=None, minsize=256, external=False,
blocksize=256, interleave='pixel', compress='lzw',
resampling=Resampling.gauss, **kwargs):
"""Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
------------
source_file : str, file object or pathlib.Path object
Source file.
factors : list, optional
A list of integral overview levels to build.
minsize : int, optional
Maximum width or height of the smallest overview level. Only taken into account
if explicit factors are not specified. Defaults to `256`.
external : bool, optional
Can be set to `True` to force external overviews in the GeoTIFF (.ovr) format.
Default is False.
blocksize : int, optional
The block size (tile width and height) used for overviews. Should be a
power-of-two value between 64 and 4096. Default value is `256`.
interleave : str, optional
Interleaving. Default value is `pixel`.
compress : str, optional
Set the compression to use. Default is `lzw`.
resampling : rasterio.enums.Resampling
Resampling method. Default is `gauss`.
kwargs : optional
Additional arguments passed to rasterio.Env.
Returns
---------
out: None
Original file is altered or external .ovr can be created.
"""
with rasterio.open(source_file, 'r+') as dst:
if factors is None:
factors = _calc_overviews_factors(
SimpleNamespace(width=dst.width, height=dst.height), minsize)
with rasterio.Env(
GDAL_TIFF_OVR_BLOCKSIZE=blocksize,
INTERLEAVE_OVERVIEW=interleave,
COMPRESS_OVERVIEW=compress,
TIFF_USE_OVR=external,
**kwargs
):
dst.build_overviews(factors, resampling)
|
[
"def",
"build_overviews",
"(",
"source_file",
",",
"factors",
"=",
"None",
",",
"minsize",
"=",
"256",
",",
"external",
"=",
"False",
",",
"blocksize",
"=",
"256",
",",
"interleave",
"=",
"'pixel'",
",",
"compress",
"=",
"'lzw'",
",",
"resampling",
"=",
"Resampling",
".",
"gauss",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"source_file",
",",
"'r+'",
")",
"as",
"dst",
":",
"if",
"factors",
"is",
"None",
":",
"factors",
"=",
"_calc_overviews_factors",
"(",
"SimpleNamespace",
"(",
"width",
"=",
"dst",
".",
"width",
",",
"height",
"=",
"dst",
".",
"height",
")",
",",
"minsize",
")",
"with",
"rasterio",
".",
"Env",
"(",
"GDAL_TIFF_OVR_BLOCKSIZE",
"=",
"blocksize",
",",
"INTERLEAVE_OVERVIEW",
"=",
"interleave",
",",
"COMPRESS_OVERVIEW",
"=",
"compress",
",",
"TIFF_USE_OVR",
"=",
"external",
",",
"*",
"*",
"kwargs",
")",
":",
"dst",
".",
"build_overviews",
"(",
"factors",
",",
"resampling",
")"
] |
Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
------------
source_file : str, file object or pathlib.Path object
Source file.
factors : list, optional
A list of integral overview levels to build.
minsize : int, optional
Maximum width or height of the smallest overview level. Only taken into account
if explicit factors are not specified. Defaults to `256`.
external : bool, optional
Can be set to `True` to force external overviews in the GeoTIFF (.ovr) format.
Default is False.
blocksize : int, optional
The block size (tile width and height) used for overviews. Should be a
power-of-two value between 64 and 4096. Default value is `256`.
interleave : str, optional
Interleaving. Default value is `pixel`.
compress : str, optional
Set the compression to use. Default is `lzw`.
resampling : rasterio.enums.Resampling
Resampling method. Default is `gauss`.
kwargs : optional
Additional arguments passed to rasterio.Env.
Returns
---------
out: None
Original file is altered or external .ovr can be created.
|
[
"Build",
"overviews",
"at",
"one",
"or",
"more",
"decimation",
"factors",
"for",
"all",
"bands",
"of",
"the",
"dataset",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L363-L411
|
14,594
|
satellogic/telluric
|
telluric/util/raster_utils.py
|
build_vrt
|
def build_vrt(source_file, destination_file, **kwargs):
"""Make a VRT XML document and write it in file.
Parameters
----------
source_file : str, file object or pathlib.Path object
Source file.
destination_file : str
Destination file.
kwargs : optional
Additional arguments passed to rasterio.vrt._boundless_vrt_doc
Returns
-------
out : str
The path to the destination file.
"""
with rasterio.open(source_file) as src:
vrt_doc = boundless_vrt_doc(src, **kwargs).tostring()
with open(destination_file, 'wb') as dst:
dst.write(vrt_doc)
return destination_file
|
python
|
def build_vrt(source_file, destination_file, **kwargs):
"""Make a VRT XML document and write it in file.
Parameters
----------
source_file : str, file object or pathlib.Path object
Source file.
destination_file : str
Destination file.
kwargs : optional
Additional arguments passed to rasterio.vrt._boundless_vrt_doc
Returns
-------
out : str
The path to the destination file.
"""
with rasterio.open(source_file) as src:
vrt_doc = boundless_vrt_doc(src, **kwargs).tostring()
with open(destination_file, 'wb') as dst:
dst.write(vrt_doc)
return destination_file
|
[
"def",
"build_vrt",
"(",
"source_file",
",",
"destination_file",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"source_file",
")",
"as",
"src",
":",
"vrt_doc",
"=",
"boundless_vrt_doc",
"(",
"src",
",",
"*",
"*",
"kwargs",
")",
".",
"tostring",
"(",
")",
"with",
"open",
"(",
"destination_file",
",",
"'wb'",
")",
"as",
"dst",
":",
"dst",
".",
"write",
"(",
"vrt_doc",
")",
"return",
"destination_file"
] |
Make a VRT XML document and write it in file.
Parameters
----------
source_file : str, file object or pathlib.Path object
Source file.
destination_file : str
Destination file.
kwargs : optional
Additional arguments passed to rasterio.vrt._boundless_vrt_doc
Returns
-------
out : str
The path to the destination file.
|
[
"Make",
"a",
"VRT",
"XML",
"document",
"and",
"write",
"it",
"in",
"file",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/raster_utils.py#L414-L437
|
14,595
|
satellogic/telluric
|
telluric/util/histogram.py
|
stretch_histogram
|
def stretch_histogram(img, dark_clip_percentile=None, bright_clip_percentile=None,
dark_clip_value=None, bright_clip_value=None, ignore_zero=True):
"""Stretch img histogram.
2 possible modes: by percentile (pass dark/bright_clip_percentile), or by value (pass dark/bright_clip_value)
:param dark_clip_percentile: percent of pixels that will be saturated to min_value
:param bright_clip_percentile: percent of pixels that will be saturated to max_value
:param dark_clip_value: all values below this will be saturated to min_value
:param bright_clip_value: all values above this will be saturated to max_value
:param ignore_zero: if true, pixels with value 0 are ignored in stretch calculation
:returns image (same shape as 'img')
"""
# verify stretching method is specified:
if (dark_clip_percentile is not None and dark_clip_value is not None) or \
(bright_clip_percentile is not None and bright_clip_value is not None):
raise KeyError('Provided parameters for both by-percentile and by-value stretch, need only one of those.')
# the default stretching:
if dark_clip_percentile is None and dark_clip_value is None:
dark_clip_percentile = 0.001
if bright_clip_percentile is None and bright_clip_value is None:
bright_clip_percentile = 0.001
if dark_clip_percentile is not None:
dark_clip_value = np.percentile(img[img != 0] if ignore_zero else img, 100 * dark_clip_percentile)
if bright_clip_percentile is not None:
bright_clip_value = np.percentile(img[img != 0] if ignore_zero else img, 100 * (1 - bright_clip_percentile))
dst_min = np.iinfo(img.dtype).min
dst_max = np.iinfo(img.dtype).max
if bright_clip_value == dark_clip_value:
raise HistogramStretchingError
gain = (dst_max - dst_min) / (bright_clip_value - dark_clip_value)
offset = -gain * dark_clip_value + dst_min
stretched = np.empty_like(img, dtype=img.dtype)
if len(img.shape) == 2:
stretched[:, :] = np.clip(gain * img[:, :].astype(np.float32) + offset, dst_min, dst_max).astype(img.dtype)
else:
for band in range(img.shape[0]):
stretched[band, :, :] = np.clip(gain * img[band, :, :].astype(np.float32) + offset,
dst_min, dst_max).astype(img.dtype)
return stretched
|
python
|
def stretch_histogram(img, dark_clip_percentile=None, bright_clip_percentile=None,
dark_clip_value=None, bright_clip_value=None, ignore_zero=True):
"""Stretch img histogram.
2 possible modes: by percentile (pass dark/bright_clip_percentile), or by value (pass dark/bright_clip_value)
:param dark_clip_percentile: percent of pixels that will be saturated to min_value
:param bright_clip_percentile: percent of pixels that will be saturated to max_value
:param dark_clip_value: all values below this will be saturated to min_value
:param bright_clip_value: all values above this will be saturated to max_value
:param ignore_zero: if true, pixels with value 0 are ignored in stretch calculation
:returns image (same shape as 'img')
"""
# verify stretching method is specified:
if (dark_clip_percentile is not None and dark_clip_value is not None) or \
(bright_clip_percentile is not None and bright_clip_value is not None):
raise KeyError('Provided parameters for both by-percentile and by-value stretch, need only one of those.')
# the default stretching:
if dark_clip_percentile is None and dark_clip_value is None:
dark_clip_percentile = 0.001
if bright_clip_percentile is None and bright_clip_value is None:
bright_clip_percentile = 0.001
if dark_clip_percentile is not None:
dark_clip_value = np.percentile(img[img != 0] if ignore_zero else img, 100 * dark_clip_percentile)
if bright_clip_percentile is not None:
bright_clip_value = np.percentile(img[img != 0] if ignore_zero else img, 100 * (1 - bright_clip_percentile))
dst_min = np.iinfo(img.dtype).min
dst_max = np.iinfo(img.dtype).max
if bright_clip_value == dark_clip_value:
raise HistogramStretchingError
gain = (dst_max - dst_min) / (bright_clip_value - dark_clip_value)
offset = -gain * dark_clip_value + dst_min
stretched = np.empty_like(img, dtype=img.dtype)
if len(img.shape) == 2:
stretched[:, :] = np.clip(gain * img[:, :].astype(np.float32) + offset, dst_min, dst_max).astype(img.dtype)
else:
for band in range(img.shape[0]):
stretched[band, :, :] = np.clip(gain * img[band, :, :].astype(np.float32) + offset,
dst_min, dst_max).astype(img.dtype)
return stretched
|
[
"def",
"stretch_histogram",
"(",
"img",
",",
"dark_clip_percentile",
"=",
"None",
",",
"bright_clip_percentile",
"=",
"None",
",",
"dark_clip_value",
"=",
"None",
",",
"bright_clip_value",
"=",
"None",
",",
"ignore_zero",
"=",
"True",
")",
":",
"# verify stretching method is specified:",
"if",
"(",
"dark_clip_percentile",
"is",
"not",
"None",
"and",
"dark_clip_value",
"is",
"not",
"None",
")",
"or",
"(",
"bright_clip_percentile",
"is",
"not",
"None",
"and",
"bright_clip_value",
"is",
"not",
"None",
")",
":",
"raise",
"KeyError",
"(",
"'Provided parameters for both by-percentile and by-value stretch, need only one of those.'",
")",
"# the default stretching:",
"if",
"dark_clip_percentile",
"is",
"None",
"and",
"dark_clip_value",
"is",
"None",
":",
"dark_clip_percentile",
"=",
"0.001",
"if",
"bright_clip_percentile",
"is",
"None",
"and",
"bright_clip_value",
"is",
"None",
":",
"bright_clip_percentile",
"=",
"0.001",
"if",
"dark_clip_percentile",
"is",
"not",
"None",
":",
"dark_clip_value",
"=",
"np",
".",
"percentile",
"(",
"img",
"[",
"img",
"!=",
"0",
"]",
"if",
"ignore_zero",
"else",
"img",
",",
"100",
"*",
"dark_clip_percentile",
")",
"if",
"bright_clip_percentile",
"is",
"not",
"None",
":",
"bright_clip_value",
"=",
"np",
".",
"percentile",
"(",
"img",
"[",
"img",
"!=",
"0",
"]",
"if",
"ignore_zero",
"else",
"img",
",",
"100",
"*",
"(",
"1",
"-",
"bright_clip_percentile",
")",
")",
"dst_min",
"=",
"np",
".",
"iinfo",
"(",
"img",
".",
"dtype",
")",
".",
"min",
"dst_max",
"=",
"np",
".",
"iinfo",
"(",
"img",
".",
"dtype",
")",
".",
"max",
"if",
"bright_clip_value",
"==",
"dark_clip_value",
":",
"raise",
"HistogramStretchingError",
"gain",
"=",
"(",
"dst_max",
"-",
"dst_min",
")",
"/",
"(",
"bright_clip_value",
"-",
"dark_clip_value",
")",
"offset",
"=",
"-",
"gain",
"*",
"dark_clip_value",
"+",
"dst_min",
"stretched",
"=",
"np",
".",
"empty_like",
"(",
"img",
",",
"dtype",
"=",
"img",
".",
"dtype",
")",
"if",
"len",
"(",
"img",
".",
"shape",
")",
"==",
"2",
":",
"stretched",
"[",
":",
",",
":",
"]",
"=",
"np",
".",
"clip",
"(",
"gain",
"*",
"img",
"[",
":",
",",
":",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"+",
"offset",
",",
"dst_min",
",",
"dst_max",
")",
".",
"astype",
"(",
"img",
".",
"dtype",
")",
"else",
":",
"for",
"band",
"in",
"range",
"(",
"img",
".",
"shape",
"[",
"0",
"]",
")",
":",
"stretched",
"[",
"band",
",",
":",
",",
":",
"]",
"=",
"np",
".",
"clip",
"(",
"gain",
"*",
"img",
"[",
"band",
",",
":",
",",
":",
"]",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"+",
"offset",
",",
"dst_min",
",",
"dst_max",
")",
".",
"astype",
"(",
"img",
".",
"dtype",
")",
"return",
"stretched"
] |
Stretch img histogram.
2 possible modes: by percentile (pass dark/bright_clip_percentile), or by value (pass dark/bright_clip_value)
:param dark_clip_percentile: percent of pixels that will be saturated to min_value
:param bright_clip_percentile: percent of pixels that will be saturated to max_value
:param dark_clip_value: all values below this will be saturated to min_value
:param bright_clip_value: all values above this will be saturated to max_value
:param ignore_zero: if true, pixels with value 0 are ignored in stretch calculation
:returns image (same shape as 'img')
|
[
"Stretch",
"img",
"histogram",
"."
] |
e752cd3ee71e339f79717e526fde362e80055d9e
|
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/util/histogram.py#L10-L53
|
14,596
|
AndrewAnnex/SpiceyPy
|
getspice.py
|
GetCSPICE._distribution_info
|
def _distribution_info(self):
"""Creates the distribution name and the expected extension for the
CSPICE package and returns it.
:return (distribution, extension) tuple where distribution is the best
guess from the strings available within the platform_urls list
of strings, and extension is either "zip" or "tar.Z" depending
on whether we are dealing with a Windows platform or else.
:rtype: tuple (str, str)
:raises: KeyError if the (system, machine) tuple does not correspond
to any of the supported SpiceyPy environments.
"""
print('Gathering information...')
system = platform.system()
# Cygwin system is CYGWIN-NT-xxx.
system = 'cygwin' if 'CYGWIN' in system else system
processor = platform.processor()
machine = '64bit' if sys.maxsize > 2 ** 32 else '32bit'
print('SYSTEM: ', system)
print('PROCESSOR:', processor)
print('MACHINE: ', machine)
return self._dists[(system, machine)]
|
python
|
def _distribution_info(self):
"""Creates the distribution name and the expected extension for the
CSPICE package and returns it.
:return (distribution, extension) tuple where distribution is the best
guess from the strings available within the platform_urls list
of strings, and extension is either "zip" or "tar.Z" depending
on whether we are dealing with a Windows platform or else.
:rtype: tuple (str, str)
:raises: KeyError if the (system, machine) tuple does not correspond
to any of the supported SpiceyPy environments.
"""
print('Gathering information...')
system = platform.system()
# Cygwin system is CYGWIN-NT-xxx.
system = 'cygwin' if 'CYGWIN' in system else system
processor = platform.processor()
machine = '64bit' if sys.maxsize > 2 ** 32 else '32bit'
print('SYSTEM: ', system)
print('PROCESSOR:', processor)
print('MACHINE: ', machine)
return self._dists[(system, machine)]
|
[
"def",
"_distribution_info",
"(",
"self",
")",
":",
"print",
"(",
"'Gathering information...'",
")",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"# Cygwin system is CYGWIN-NT-xxx.",
"system",
"=",
"'cygwin'",
"if",
"'CYGWIN'",
"in",
"system",
"else",
"system",
"processor",
"=",
"platform",
".",
"processor",
"(",
")",
"machine",
"=",
"'64bit'",
"if",
"sys",
".",
"maxsize",
">",
"2",
"**",
"32",
"else",
"'32bit'",
"print",
"(",
"'SYSTEM: '",
",",
"system",
")",
"print",
"(",
"'PROCESSOR:'",
",",
"processor",
")",
"print",
"(",
"'MACHINE: '",
",",
"machine",
")",
"return",
"self",
".",
"_dists",
"[",
"(",
"system",
",",
"machine",
")",
"]"
] |
Creates the distribution name and the expected extension for the
CSPICE package and returns it.
:return (distribution, extension) tuple where distribution is the best
guess from the strings available within the platform_urls list
of strings, and extension is either "zip" or "tar.Z" depending
on whether we are dealing with a Windows platform or else.
:rtype: tuple (str, str)
:raises: KeyError if the (system, machine) tuple does not correspond
to any of the supported SpiceyPy environments.
|
[
"Creates",
"the",
"distribution",
"name",
"and",
"the",
"expected",
"extension",
"for",
"the",
"CSPICE",
"package",
"and",
"returns",
"it",
"."
] |
fc20a9b9de68b58eed5b332f0c051fb343a6e335
|
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/getspice.py#L153-L180
|
14,597
|
AndrewAnnex/SpiceyPy
|
getspice.py
|
GetCSPICE._download
|
def _download(self):
"""Support function that encapsulates the OpenSSL transfer of the CSPICE
package to the self._local io.ByteIO stream.
:raises RuntimeError if there has been any issue with the HTTPS
communication
.. note::
Handling of CSPICE downloads from HTTPS
---------------------------------------
Some Python distributions may be linked to an old version of OpenSSL
which will not let you connect to NAIF server due to recent SSL cert
upgrades on the JPL servers. Moreover, versions older than
OpenSSL 1.0.1g are known to contain the 'the Heartbleed Bug'.
Therefore this method provides two different implementations for the
HTTPS GET call to the NAIF server to download the required CSPICE
distribution package.
"""
# Use urllib3 (based on PyOpenSSL).
if ssl.OPENSSL_VERSION < 'OpenSSL 1.0.1g':
# Force urllib3 to use pyOpenSSL
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
import certifi
import urllib3
try:
# Search proxy in ENV variables
proxies = {}
for key, value in os.environ.items():
if '_proxy' in key.lower():
proxies[key.lower().replace('_proxy','')] = value
# Create a ProolManager
if 'https' in proxies:
https = urllib3.ProxyManager(proxies['https'],
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
elif 'http' in proxies:
https = urllib3.ProxyManager(proxies['http'],
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
else:
https = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
# Send the request to get the CSPICE package.
response = https.request('GET', self._rcspice,
timeout=urllib3.Timeout(10))
except urllib3.exceptions.HTTPError as err:
raise RuntimeError(err.message)
# Convert the response to io.BytesIO and store it in local memory.
self._local = io.BytesIO(response.data)
# Use the standard urllib (using system OpenSSL).
else:
try:
# Send the request to get the CSPICE package (proxy auto detected).
response = urllib.request.urlopen(self._rcspice, timeout=10)
except urllib.error.URLError as err:
raise RuntimeError(err.reason)
# Convert the response to io.BytesIO and store it in local memory.
self._local = io.BytesIO(response.read())
|
python
|
def _download(self):
"""Support function that encapsulates the OpenSSL transfer of the CSPICE
package to the self._local io.ByteIO stream.
:raises RuntimeError if there has been any issue with the HTTPS
communication
.. note::
Handling of CSPICE downloads from HTTPS
---------------------------------------
Some Python distributions may be linked to an old version of OpenSSL
which will not let you connect to NAIF server due to recent SSL cert
upgrades on the JPL servers. Moreover, versions older than
OpenSSL 1.0.1g are known to contain the 'the Heartbleed Bug'.
Therefore this method provides two different implementations for the
HTTPS GET call to the NAIF server to download the required CSPICE
distribution package.
"""
# Use urllib3 (based on PyOpenSSL).
if ssl.OPENSSL_VERSION < 'OpenSSL 1.0.1g':
# Force urllib3 to use pyOpenSSL
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
import certifi
import urllib3
try:
# Search proxy in ENV variables
proxies = {}
for key, value in os.environ.items():
if '_proxy' in key.lower():
proxies[key.lower().replace('_proxy','')] = value
# Create a ProolManager
if 'https' in proxies:
https = urllib3.ProxyManager(proxies['https'],
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
elif 'http' in proxies:
https = urllib3.ProxyManager(proxies['http'],
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
else:
https = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
# Send the request to get the CSPICE package.
response = https.request('GET', self._rcspice,
timeout=urllib3.Timeout(10))
except urllib3.exceptions.HTTPError as err:
raise RuntimeError(err.message)
# Convert the response to io.BytesIO and store it in local memory.
self._local = io.BytesIO(response.data)
# Use the standard urllib (using system OpenSSL).
else:
try:
# Send the request to get the CSPICE package (proxy auto detected).
response = urllib.request.urlopen(self._rcspice, timeout=10)
except urllib.error.URLError as err:
raise RuntimeError(err.reason)
# Convert the response to io.BytesIO and store it in local memory.
self._local = io.BytesIO(response.read())
|
[
"def",
"_download",
"(",
"self",
")",
":",
"# Use urllib3 (based on PyOpenSSL).",
"if",
"ssl",
".",
"OPENSSL_VERSION",
"<",
"'OpenSSL 1.0.1g'",
":",
"# Force urllib3 to use pyOpenSSL",
"import",
"urllib3",
".",
"contrib",
".",
"pyopenssl",
"urllib3",
".",
"contrib",
".",
"pyopenssl",
".",
"inject_into_urllib3",
"(",
")",
"import",
"certifi",
"import",
"urllib3",
"try",
":",
"# Search proxy in ENV variables",
"proxies",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"'_proxy'",
"in",
"key",
".",
"lower",
"(",
")",
":",
"proxies",
"[",
"key",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'_proxy'",
",",
"''",
")",
"]",
"=",
"value",
"# Create a ProolManager",
"if",
"'https'",
"in",
"proxies",
":",
"https",
"=",
"urllib3",
".",
"ProxyManager",
"(",
"proxies",
"[",
"'https'",
"]",
",",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"elif",
"'http'",
"in",
"proxies",
":",
"https",
"=",
"urllib3",
".",
"ProxyManager",
"(",
"proxies",
"[",
"'http'",
"]",
",",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"else",
":",
"https",
"=",
"urllib3",
".",
"PoolManager",
"(",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"# Send the request to get the CSPICE package.",
"response",
"=",
"https",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"_rcspice",
",",
"timeout",
"=",
"urllib3",
".",
"Timeout",
"(",
"10",
")",
")",
"except",
"urllib3",
".",
"exceptions",
".",
"HTTPError",
"as",
"err",
":",
"raise",
"RuntimeError",
"(",
"err",
".",
"message",
")",
"# Convert the response to io.BytesIO and store it in local memory.",
"self",
".",
"_local",
"=",
"io",
".",
"BytesIO",
"(",
"response",
".",
"data",
")",
"# Use the standard urllib (using system OpenSSL).",
"else",
":",
"try",
":",
"# Send the request to get the CSPICE package (proxy auto detected).",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"self",
".",
"_rcspice",
",",
"timeout",
"=",
"10",
")",
"except",
"urllib",
".",
"error",
".",
"URLError",
"as",
"err",
":",
"raise",
"RuntimeError",
"(",
"err",
".",
"reason",
")",
"# Convert the response to io.BytesIO and store it in local memory.",
"self",
".",
"_local",
"=",
"io",
".",
"BytesIO",
"(",
"response",
".",
"read",
"(",
")",
")"
] |
Support function that encapsulates the OpenSSL transfer of the CSPICE
package to the self._local io.ByteIO stream.
:raises RuntimeError if there has been any issue with the HTTPS
communication
.. note::
Handling of CSPICE downloads from HTTPS
---------------------------------------
Some Python distributions may be linked to an old version of OpenSSL
which will not let you connect to NAIF server due to recent SSL cert
upgrades on the JPL servers. Moreover, versions older than
OpenSSL 1.0.1g are known to contain the 'the Heartbleed Bug'.
Therefore this method provides two different implementations for the
HTTPS GET call to the NAIF server to download the required CSPICE
distribution package.
|
[
"Support",
"function",
"that",
"encapsulates",
"the",
"OpenSSL",
"transfer",
"of",
"the",
"CSPICE",
"package",
"to",
"the",
"self",
".",
"_local",
"io",
".",
"ByteIO",
"stream",
"."
] |
fc20a9b9de68b58eed5b332f0c051fb343a6e335
|
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/getspice.py#L182-L247
|
14,598
|
AndrewAnnex/SpiceyPy
|
getspice.py
|
GetCSPICE._unpack
|
def _unpack(self):
"""Unpacks the CSPICE package on the given root directory. Note that
Package could either be the zipfile.ZipFile class for Windows platforms
or tarfile.TarFile for other platforms.
"""
if self._ext == 'zip':
with ZipFile(self._local, 'r') as archive:
archive.extractall(self._root)
else:
cmd = 'gunzip | tar xC ' + self._root
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
proc.stdin.write(self._local.read())
self._local.close()
|
python
|
def _unpack(self):
"""Unpacks the CSPICE package on the given root directory. Note that
Package could either be the zipfile.ZipFile class for Windows platforms
or tarfile.TarFile for other platforms.
"""
if self._ext == 'zip':
with ZipFile(self._local, 'r') as archive:
archive.extractall(self._root)
else:
cmd = 'gunzip | tar xC ' + self._root
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
proc.stdin.write(self._local.read())
self._local.close()
|
[
"def",
"_unpack",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ext",
"==",
"'zip'",
":",
"with",
"ZipFile",
"(",
"self",
".",
"_local",
",",
"'r'",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"self",
".",
"_root",
")",
"else",
":",
"cmd",
"=",
"'gunzip | tar xC '",
"+",
"self",
".",
"_root",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"proc",
".",
"stdin",
".",
"write",
"(",
"self",
".",
"_local",
".",
"read",
"(",
")",
")",
"self",
".",
"_local",
".",
"close",
"(",
")"
] |
Unpacks the CSPICE package on the given root directory. Note that
Package could either be the zipfile.ZipFile class for Windows platforms
or tarfile.TarFile for other platforms.
|
[
"Unpacks",
"the",
"CSPICE",
"package",
"on",
"the",
"given",
"root",
"directory",
".",
"Note",
"that",
"Package",
"could",
"either",
"be",
"the",
"zipfile",
".",
"ZipFile",
"class",
"for",
"Windows",
"platforms",
"or",
"tarfile",
".",
"TarFile",
"for",
"other",
"platforms",
"."
] |
fc20a9b9de68b58eed5b332f0c051fb343a6e335
|
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/getspice.py#L249-L261
|
14,599
|
AndrewAnnex/SpiceyPy
|
spiceypy/spiceypy.py
|
spiceErrorCheck
|
def spiceErrorCheck(f):
"""
Decorator for spiceypy hooking into spice error system.
If an error is detected, an output similar to outmsg
:type f: builtins.function
:return:
:rtype:
"""
@functools.wraps(f)
def with_errcheck(*args, **kwargs):
try:
res = f(*args, **kwargs)
checkForSpiceError(f)
return res
except:
raise
return with_errcheck
|
python
|
def spiceErrorCheck(f):
"""
Decorator for spiceypy hooking into spice error system.
If an error is detected, an output similar to outmsg
:type f: builtins.function
:return:
:rtype:
"""
@functools.wraps(f)
def with_errcheck(*args, **kwargs):
try:
res = f(*args, **kwargs)
checkForSpiceError(f)
return res
except:
raise
return with_errcheck
|
[
"def",
"spiceErrorCheck",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"with_errcheck",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"res",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"checkForSpiceError",
"(",
"f",
")",
"return",
"res",
"except",
":",
"raise",
"return",
"with_errcheck"
] |
Decorator for spiceypy hooking into spice error system.
If an error is detected, an output similar to outmsg
:type f: builtins.function
:return:
:rtype:
|
[
"Decorator",
"for",
"spiceypy",
"hooking",
"into",
"spice",
"error",
"system",
".",
"If",
"an",
"error",
"is",
"detected",
"an",
"output",
"similar",
"to",
"outmsg"
] |
fc20a9b9de68b58eed5b332f0c051fb343a6e335
|
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L64-L83
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.