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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | spiceFoundExceptionThrower | def spiceFoundExceptionThrower(f):
"""
Decorator for wrapping functions that use status codes
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
if config.catch_false_founds:
found = res[-1]
if isinstance(found, bool) and not found:
raise stypes.SpiceyError("Spice returns not found for function: {}".format(f.__name__), found=found)
elif hasattr(found, '__iter__') and not all(found):
raise stypes.SpiceyError("Spice returns not found in a series of calls for function: {}".format(f.__name__), found=found)
else:
actualres = res[0:-1]
if len(actualres) == 1:
return actualres[0]
else:
return actualres
else:
return res
return wrapper | python | def spiceFoundExceptionThrower(f):
"""
Decorator for wrapping functions that use status codes
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
if config.catch_false_founds:
found = res[-1]
if isinstance(found, bool) and not found:
raise stypes.SpiceyError("Spice returns not found for function: {}".format(f.__name__), found=found)
elif hasattr(found, '__iter__') and not all(found):
raise stypes.SpiceyError("Spice returns not found in a series of calls for function: {}".format(f.__name__), found=found)
else:
actualres = res[0:-1]
if len(actualres) == 1:
return actualres[0]
else:
return actualres
else:
return res
return wrapper | [
"def",
"spiceFoundExceptionThrower",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"config",
".",
"catch_false_founds",
":",
"found",
"=",
"res",
"[",
"-",
"1",
"]",
"if",
"isinstance",
"(",
"found",
",",
"bool",
")",
"and",
"not",
"found",
":",
"raise",
"stypes",
".",
"SpiceyError",
"(",
"\"Spice returns not found for function: {}\"",
".",
"format",
"(",
"f",
".",
"__name__",
")",
",",
"found",
"=",
"found",
")",
"elif",
"hasattr",
"(",
"found",
",",
"'__iter__'",
")",
"and",
"not",
"all",
"(",
"found",
")",
":",
"raise",
"stypes",
".",
"SpiceyError",
"(",
"\"Spice returns not found in a series of calls for function: {}\"",
".",
"format",
"(",
"f",
".",
"__name__",
")",
",",
"found",
"=",
"found",
")",
"else",
":",
"actualres",
"=",
"res",
"[",
"0",
":",
"-",
"1",
"]",
"if",
"len",
"(",
"actualres",
")",
"==",
"1",
":",
"return",
"actualres",
"[",
"0",
"]",
"else",
":",
"return",
"actualres",
"else",
":",
"return",
"res",
"return",
"wrapper"
] | Decorator for wrapping functions that use status codes | [
"Decorator",
"for",
"wrapping",
"functions",
"that",
"use",
"status",
"codes"
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L86-L108 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | appndc | def appndc(item, cell):
"""
Append an item to a character cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndc_c.html
:param item: The item to append.
:type item: str or list
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if isinstance(item, list):
for c in item:
libspice.appndc_c(stypes.stringToCharP(c), cell)
else:
item = stypes.stringToCharP(item)
libspice.appndc_c(item, cell) | python | def appndc(item, cell):
"""
Append an item to a character cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndc_c.html
:param item: The item to append.
:type item: str or list
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if isinstance(item, list):
for c in item:
libspice.appndc_c(stypes.stringToCharP(c), cell)
else:
item = stypes.stringToCharP(item)
libspice.appndc_c(item, cell) | [
"def",
"appndc",
"(",
"item",
",",
"cell",
")",
":",
"assert",
"isinstance",
"(",
"cell",
",",
"stypes",
".",
"SpiceCell",
")",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"c",
"in",
"item",
":",
"libspice",
".",
"appndc_c",
"(",
"stypes",
".",
"stringToCharP",
"(",
"c",
")",
",",
"cell",
")",
"else",
":",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"libspice",
".",
"appndc_c",
"(",
"item",
",",
"cell",
")"
] | Append an item to a character cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndc_c.html
:param item: The item to append.
:type item: str or list
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell | [
"Append",
"an",
"item",
"to",
"a",
"character",
"cell",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L217-L234 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | appndd | def appndd(item, cell):
"""
Append an item to a double precision cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html
:param item: The item to append.
:type item: Union[float,Iterable[float]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if hasattr(item, "__iter__"):
for d in item:
libspice.appndd_c(ctypes.c_double(d), cell)
else:
item = ctypes.c_double(item)
libspice.appndd_c(item, cell) | python | def appndd(item, cell):
"""
Append an item to a double precision cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html
:param item: The item to append.
:type item: Union[float,Iterable[float]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if hasattr(item, "__iter__"):
for d in item:
libspice.appndd_c(ctypes.c_double(d), cell)
else:
item = ctypes.c_double(item)
libspice.appndd_c(item, cell) | [
"def",
"appndd",
"(",
"item",
",",
"cell",
")",
":",
"assert",
"isinstance",
"(",
"cell",
",",
"stypes",
".",
"SpiceCell",
")",
"if",
"hasattr",
"(",
"item",
",",
"\"__iter__\"",
")",
":",
"for",
"d",
"in",
"item",
":",
"libspice",
".",
"appndd_c",
"(",
"ctypes",
".",
"c_double",
"(",
"d",
")",
",",
"cell",
")",
"else",
":",
"item",
"=",
"ctypes",
".",
"c_double",
"(",
"item",
")",
"libspice",
".",
"appndd_c",
"(",
"item",
",",
"cell",
")"
] | Append an item to a double precision cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html
:param item: The item to append.
:type item: Union[float,Iterable[float]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell | [
"Append",
"an",
"item",
"to",
"a",
"double",
"precision",
"cell",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L238-L255 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | appndi | def appndi(item, cell):
"""
Append an item to an integer cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndi_c.html
:param item: The item to append.
:type item: Union[float,Iterable[int]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if hasattr(item, "__iter__"):
for i in item:
libspice.appndi_c(ctypes.c_int(i), cell)
else:
item = ctypes.c_int(item)
libspice.appndi_c(item, cell) | python | def appndi(item, cell):
"""
Append an item to an integer cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndi_c.html
:param item: The item to append.
:type item: Union[float,Iterable[int]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
if hasattr(item, "__iter__"):
for i in item:
libspice.appndi_c(ctypes.c_int(i), cell)
else:
item = ctypes.c_int(item)
libspice.appndi_c(item, cell) | [
"def",
"appndi",
"(",
"item",
",",
"cell",
")",
":",
"assert",
"isinstance",
"(",
"cell",
",",
"stypes",
".",
"SpiceCell",
")",
"if",
"hasattr",
"(",
"item",
",",
"\"__iter__\"",
")",
":",
"for",
"i",
"in",
"item",
":",
"libspice",
".",
"appndi_c",
"(",
"ctypes",
".",
"c_int",
"(",
"i",
")",
",",
"cell",
")",
"else",
":",
"item",
"=",
"ctypes",
".",
"c_int",
"(",
"item",
")",
"libspice",
".",
"appndi_c",
"(",
"item",
",",
"cell",
")"
] | Append an item to an integer cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndi_c.html
:param item: The item to append.
:type item: Union[float,Iterable[int]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell | [
"Append",
"an",
"item",
"to",
"an",
"integer",
"cell",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L259-L276 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | axisar | def axisar(axis, angle):
"""
Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html
:param axis: Rotation axis.
:type axis: 3 Element vector (list, tuple, numpy array)
:param angle: Rotation angle, in radians.
:type angle: float
:return: Rotation matrix corresponding to axis and angle.
:rtype: numpy array ((3, 3))
"""
axis = stypes.toDoubleVector(axis)
angle = ctypes.c_double(angle)
r = stypes.emptyDoubleMatrix()
libspice.axisar_c(axis, angle, r)
return stypes.cMatrixToNumpy(r) | python | def axisar(axis, angle):
"""
Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html
:param axis: Rotation axis.
:type axis: 3 Element vector (list, tuple, numpy array)
:param angle: Rotation angle, in radians.
:type angle: float
:return: Rotation matrix corresponding to axis and angle.
:rtype: numpy array ((3, 3))
"""
axis = stypes.toDoubleVector(axis)
angle = ctypes.c_double(angle)
r = stypes.emptyDoubleMatrix()
libspice.axisar_c(axis, angle, r)
return stypes.cMatrixToNumpy(r) | [
"def",
"axisar",
"(",
"axis",
",",
"angle",
")",
":",
"axis",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"axis",
")",
"angle",
"=",
"ctypes",
".",
"c_double",
"(",
"angle",
")",
"r",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
")",
"libspice",
".",
"axisar_c",
"(",
"axis",
",",
"angle",
",",
"r",
")",
"return",
"stypes",
".",
"cMatrixToNumpy",
"(",
"r",
")"
] | Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html
:param axis: Rotation axis.
:type axis: 3 Element vector (list, tuple, numpy array)
:param angle: Rotation angle, in radians.
:type angle: float
:return: Rotation matrix corresponding to axis and angle.
:rtype: numpy array ((3, 3)) | [
"Construct",
"a",
"rotation",
"matrix",
"that",
"rotates",
"vectors",
"by",
"a",
"specified",
"angle",
"about",
"a",
"specified",
"axis",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L280-L298 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | badkpv | def badkpv(caller, name, comp, insize, divby, intype):
"""
Determine if a kernel pool variable is present and if so
that it has the correct size and type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/badkpv_c.html
:param caller: Name of the routine calling this routine.
:type caller: str
:param name: Name of a kernel pool variable.
:type name: str
:param comp: Comparison operator.
:type comp: str
:param insize: Expected size of the kernel pool variable.
:type insize: int
:param divby: A divisor of the size of the kernel pool variable.
:type divby: int
:param intype: Expected type of the kernel pool variable
:type intype: str
:return: returns false if the kernel pool variable is OK.
:rtype: bool
"""
caller = stypes.stringToCharP(caller)
name = stypes.stringToCharP(name)
comp = stypes.stringToCharP(comp)
insize = ctypes.c_int(insize)
divby = ctypes.c_int(divby)
intype = ctypes.c_char(intype.encode(encoding='UTF-8'))
return bool(libspice.badkpv_c(caller, name, comp, insize, divby, intype)) | python | def badkpv(caller, name, comp, insize, divby, intype):
"""
Determine if a kernel pool variable is present and if so
that it has the correct size and type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/badkpv_c.html
:param caller: Name of the routine calling this routine.
:type caller: str
:param name: Name of a kernel pool variable.
:type name: str
:param comp: Comparison operator.
:type comp: str
:param insize: Expected size of the kernel pool variable.
:type insize: int
:param divby: A divisor of the size of the kernel pool variable.
:type divby: int
:param intype: Expected type of the kernel pool variable
:type intype: str
:return: returns false if the kernel pool variable is OK.
:rtype: bool
"""
caller = stypes.stringToCharP(caller)
name = stypes.stringToCharP(name)
comp = stypes.stringToCharP(comp)
insize = ctypes.c_int(insize)
divby = ctypes.c_int(divby)
intype = ctypes.c_char(intype.encode(encoding='UTF-8'))
return bool(libspice.badkpv_c(caller, name, comp, insize, divby, intype)) | [
"def",
"badkpv",
"(",
"caller",
",",
"name",
",",
"comp",
",",
"insize",
",",
"divby",
",",
"intype",
")",
":",
"caller",
"=",
"stypes",
".",
"stringToCharP",
"(",
"caller",
")",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"name",
")",
"comp",
"=",
"stypes",
".",
"stringToCharP",
"(",
"comp",
")",
"insize",
"=",
"ctypes",
".",
"c_int",
"(",
"insize",
")",
"divby",
"=",
"ctypes",
".",
"c_int",
"(",
"divby",
")",
"intype",
"=",
"ctypes",
".",
"c_char",
"(",
"intype",
".",
"encode",
"(",
"encoding",
"=",
"'UTF-8'",
")",
")",
"return",
"bool",
"(",
"libspice",
".",
"badkpv_c",
"(",
"caller",
",",
"name",
",",
"comp",
",",
"insize",
",",
"divby",
",",
"intype",
")",
")"
] | Determine if a kernel pool variable is present and if so
that it has the correct size and type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/badkpv_c.html
:param caller: Name of the routine calling this routine.
:type caller: str
:param name: Name of a kernel pool variable.
:type name: str
:param comp: Comparison operator.
:type comp: str
:param insize: Expected size of the kernel pool variable.
:type insize: int
:param divby: A divisor of the size of the kernel pool variable.
:type divby: int
:param intype: Expected type of the kernel pool variable
:type intype: str
:return: returns false if the kernel pool variable is OK.
:rtype: bool | [
"Determine",
"if",
"a",
"kernel",
"pool",
"variable",
"is",
"present",
"and",
"if",
"so",
"that",
"it",
"has",
"the",
"correct",
"size",
"and",
"type",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L331-L359 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bltfrm | def bltfrm(frmcls, outCell=None):
"""
Return a SPICE set containing the frame IDs of all built-in frames
of a specified class.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html
:param frmcls: Frame class.
:type frmcls: int
:param outCell: Optional SpiceInt Cell that is returned
:type outCell: spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of frames of the specified class.
:rtype: spiceypy.utils.support_types.SpiceCell
"""
frmcls = ctypes.c_int(frmcls)
if not outCell:
outCell = stypes.SPICEINT_CELL(1000)
libspice.bltfrm_c(frmcls, outCell)
return outCell | python | def bltfrm(frmcls, outCell=None):
"""
Return a SPICE set containing the frame IDs of all built-in frames
of a specified class.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html
:param frmcls: Frame class.
:type frmcls: int
:param outCell: Optional SpiceInt Cell that is returned
:type outCell: spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of frames of the specified class.
:rtype: spiceypy.utils.support_types.SpiceCell
"""
frmcls = ctypes.c_int(frmcls)
if not outCell:
outCell = stypes.SPICEINT_CELL(1000)
libspice.bltfrm_c(frmcls, outCell)
return outCell | [
"def",
"bltfrm",
"(",
"frmcls",
",",
"outCell",
"=",
"None",
")",
":",
"frmcls",
"=",
"ctypes",
".",
"c_int",
"(",
"frmcls",
")",
"if",
"not",
"outCell",
":",
"outCell",
"=",
"stypes",
".",
"SPICEINT_CELL",
"(",
"1000",
")",
"libspice",
".",
"bltfrm_c",
"(",
"frmcls",
",",
"outCell",
")",
"return",
"outCell"
] | Return a SPICE set containing the frame IDs of all built-in frames
of a specified class.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html
:param frmcls: Frame class.
:type frmcls: int
:param outCell: Optional SpiceInt Cell that is returned
:type outCell: spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of frames of the specified class.
:rtype: spiceypy.utils.support_types.SpiceCell | [
"Return",
"a",
"SPICE",
"set",
"containing",
"the",
"frame",
"IDs",
"of",
"all",
"built",
"-",
"in",
"frames",
"of",
"a",
"specified",
"class",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L363-L381 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodc2n | def bodc2n(code, lenout=_default_len_out):
"""
Translate the SPICE integer code of a body into a common name
for that body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2n_c.html
:param code: Integer ID code to be translated into a name.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: A common name for the body identified by code.
:rtype: str
"""
code = ctypes.c_int(code)
name = stypes.stringToCharP(" " * lenout)
lenout = ctypes.c_int(lenout)
found = ctypes.c_int()
libspice.bodc2n_c(code, lenout, name, ctypes.byref(found))
return stypes.toPythonString(name), bool(found.value) | python | def bodc2n(code, lenout=_default_len_out):
"""
Translate the SPICE integer code of a body into a common name
for that body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2n_c.html
:param code: Integer ID code to be translated into a name.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: A common name for the body identified by code.
:rtype: str
"""
code = ctypes.c_int(code)
name = stypes.stringToCharP(" " * lenout)
lenout = ctypes.c_int(lenout)
found = ctypes.c_int()
libspice.bodc2n_c(code, lenout, name, ctypes.byref(found))
return stypes.toPythonString(name), bool(found.value) | [
"def",
"bodc2n",
"(",
"code",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"code",
"=",
"ctypes",
".",
"c_int",
"(",
"code",
")",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"\" \"",
"*",
"lenout",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"bodc2n_c",
"(",
"code",
",",
"lenout",
",",
"name",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"stypes",
".",
"toPythonString",
"(",
"name",
")",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Translate the SPICE integer code of a body into a common name
for that body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2n_c.html
:param code: Integer ID code to be translated into a name.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: A common name for the body identified by code.
:rtype: str | [
"Translate",
"the",
"SPICE",
"integer",
"code",
"of",
"a",
"body",
"into",
"a",
"common",
"name",
"for",
"that",
"body",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L386-L405 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodc2s | def bodc2s(code, lenout=_default_len_out):
"""
Translate a body ID code to either the corresponding name or if no
name to ID code mapping exists, the string representation of the
body ID value.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2s_c.html
:param code: Integer ID code to translate to a string.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: String corresponding to 'code'.
:rtype: str
"""
code = ctypes.c_int(code)
name = stypes.stringToCharP(" " * lenout)
lenout = ctypes.c_int(lenout)
libspice.bodc2s_c(code, lenout, name)
return stypes.toPythonString(name) | python | def bodc2s(code, lenout=_default_len_out):
"""
Translate a body ID code to either the corresponding name or if no
name to ID code mapping exists, the string representation of the
body ID value.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2s_c.html
:param code: Integer ID code to translate to a string.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: String corresponding to 'code'.
:rtype: str
"""
code = ctypes.c_int(code)
name = stypes.stringToCharP(" " * lenout)
lenout = ctypes.c_int(lenout)
libspice.bodc2s_c(code, lenout, name)
return stypes.toPythonString(name) | [
"def",
"bodc2s",
"(",
"code",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"code",
"=",
"ctypes",
".",
"c_int",
"(",
"code",
")",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"\" \"",
"*",
"lenout",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"libspice",
".",
"bodc2s_c",
"(",
"code",
",",
"lenout",
",",
"name",
")",
"return",
"stypes",
".",
"toPythonString",
"(",
"name",
")"
] | Translate a body ID code to either the corresponding name or if no
name to ID code mapping exists, the string representation of the
body ID value.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2s_c.html
:param code: Integer ID code to translate to a string.
:type code: int
:param lenout: Maximum length of output name.
:type lenout: int
:return: String corresponding to 'code'.
:rtype: str | [
"Translate",
"a",
"body",
"ID",
"code",
"to",
"either",
"the",
"corresponding",
"name",
"or",
"if",
"no",
"name",
"to",
"ID",
"code",
"mapping",
"exists",
"the",
"string",
"representation",
"of",
"the",
"body",
"ID",
"value",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L409-L428 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodfnd | def bodfnd(body, item):
"""
Determine whether values exist for some item for any body
in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html
:param body: ID code of body.
:type body: int
:param item: Item to find ("RADII", "NUT_AMP_RA", etc.).
:type item: str
:return: True if the item is in the kernel pool, and is False if it is not.
:rtype: bool
"""
body = ctypes.c_int(body)
item = stypes.stringToCharP(item)
return bool(libspice.bodfnd_c(body, item)) | python | def bodfnd(body, item):
"""
Determine whether values exist for some item for any body
in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html
:param body: ID code of body.
:type body: int
:param item: Item to find ("RADII", "NUT_AMP_RA", etc.).
:type item: str
:return: True if the item is in the kernel pool, and is False if it is not.
:rtype: bool
"""
body = ctypes.c_int(body)
item = stypes.stringToCharP(item)
return bool(libspice.bodfnd_c(body, item)) | [
"def",
"bodfnd",
"(",
"body",
",",
"item",
")",
":",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"return",
"bool",
"(",
"libspice",
".",
"bodfnd_c",
"(",
"body",
",",
"item",
")",
")"
] | Determine whether values exist for some item for any body
in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html
:param body: ID code of body.
:type body: int
:param item: Item to find ("RADII", "NUT_AMP_RA", etc.).
:type item: str
:return: True if the item is in the kernel pool, and is False if it is not.
:rtype: bool | [
"Determine",
"whether",
"values",
"exist",
"for",
"some",
"item",
"for",
"any",
"body",
"in",
"the",
"kernel",
"pool",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L450-L466 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodn2c | def bodn2c(name):
"""
Translate the name of a body or object to the corresponding SPICE
integer ID code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html
:param name: Body name to be translated into a SPICE ID code.
:type name: str
:return: SPICE integer ID code for the named body.
:rtype: int
"""
name = stypes.stringToCharP(name)
code = ctypes.c_int(0)
found = ctypes.c_int(0)
libspice.bodn2c_c(name, ctypes.byref(code), ctypes.byref(found))
return code.value, bool(found.value) | python | def bodn2c(name):
"""
Translate the name of a body or object to the corresponding SPICE
integer ID code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html
:param name: Body name to be translated into a SPICE ID code.
:type name: str
:return: SPICE integer ID code for the named body.
:rtype: int
"""
name = stypes.stringToCharP(name)
code = ctypes.c_int(0)
found = ctypes.c_int(0)
libspice.bodn2c_c(name, ctypes.byref(code), ctypes.byref(found))
return code.value, bool(found.value) | [
"def",
"bodn2c",
"(",
"name",
")",
":",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"name",
")",
"code",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"libspice",
".",
"bodn2c_c",
"(",
"name",
",",
"ctypes",
".",
"byref",
"(",
"code",
")",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"code",
".",
"value",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Translate the name of a body or object to the corresponding SPICE
integer ID code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html
:param name: Body name to be translated into a SPICE ID code.
:type name: str
:return: SPICE integer ID code for the named body.
:rtype: int | [
"Translate",
"the",
"name",
"of",
"a",
"body",
"or",
"object",
"to",
"the",
"corresponding",
"SPICE",
"integer",
"ID",
"code",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L471-L487 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bods2c | def bods2c(name):
"""
Translate a string containing a body name or ID code to an integer code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html
:param name: String to be translated to an ID code.
:type name: str
:return: Integer ID code corresponding to name.
:rtype: int
"""
name = stypes.stringToCharP(name)
code = ctypes.c_int(0)
found = ctypes.c_int(0)
libspice.bods2c_c(name, ctypes.byref(code), ctypes.byref(found))
return code.value, bool(found.value) | python | def bods2c(name):
"""
Translate a string containing a body name or ID code to an integer code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html
:param name: String to be translated to an ID code.
:type name: str
:return: Integer ID code corresponding to name.
:rtype: int
"""
name = stypes.stringToCharP(name)
code = ctypes.c_int(0)
found = ctypes.c_int(0)
libspice.bods2c_c(name, ctypes.byref(code), ctypes.byref(found))
return code.value, bool(found.value) | [
"def",
"bods2c",
"(",
"name",
")",
":",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"name",
")",
"code",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"libspice",
".",
"bods2c_c",
"(",
"name",
",",
"ctypes",
".",
"byref",
"(",
"code",
")",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"code",
".",
"value",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Translate a string containing a body name or ID code to an integer code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html
:param name: String to be translated to an ID code.
:type name: str
:return: Integer ID code corresponding to name.
:rtype: int | [
"Translate",
"a",
"string",
"containing",
"a",
"body",
"name",
"or",
"ID",
"code",
"to",
"an",
"integer",
"code",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L492-L507 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodvcd | def bodvcd(bodyid, item, maxn):
"""
Fetch from the kernel pool the double precision values of an item
associated with a body, where the body is specified by an integer ID
code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvcd_c.html
:param bodyid: Body ID code.
:type bodyid: int
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: dim, values
:rtype: tuple
"""
bodyid = ctypes.c_int(bodyid)
item = stypes.stringToCharP(item)
dim = ctypes.c_int()
values = stypes.emptyDoubleVector(maxn)
maxn = ctypes.c_int(maxn)
libspice.bodvcd_c(bodyid, item, maxn, ctypes.byref(dim), values)
return dim.value, stypes.cVectorToPython(values) | python | def bodvcd(bodyid, item, maxn):
"""
Fetch from the kernel pool the double precision values of an item
associated with a body, where the body is specified by an integer ID
code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvcd_c.html
:param bodyid: Body ID code.
:type bodyid: int
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: dim, values
:rtype: tuple
"""
bodyid = ctypes.c_int(bodyid)
item = stypes.stringToCharP(item)
dim = ctypes.c_int()
values = stypes.emptyDoubleVector(maxn)
maxn = ctypes.c_int(maxn)
libspice.bodvcd_c(bodyid, item, maxn, ctypes.byref(dim), values)
return dim.value, stypes.cVectorToPython(values) | [
"def",
"bodvcd",
"(",
"bodyid",
",",
"item",
",",
"maxn",
")",
":",
"bodyid",
"=",
"ctypes",
".",
"c_int",
"(",
"bodyid",
")",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"dim",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"values",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"maxn",
")",
"maxn",
"=",
"ctypes",
".",
"c_int",
"(",
"maxn",
")",
"libspice",
".",
"bodvcd_c",
"(",
"bodyid",
",",
"item",
",",
"maxn",
",",
"ctypes",
".",
"byref",
"(",
"dim",
")",
",",
"values",
")",
"return",
"dim",
".",
"value",
",",
"stypes",
".",
"cVectorToPython",
"(",
"values",
")"
] | Fetch from the kernel pool the double precision values of an item
associated with a body, where the body is specified by an integer ID
code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvcd_c.html
:param bodyid: Body ID code.
:type bodyid: int
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: dim, values
:rtype: tuple | [
"Fetch",
"from",
"the",
"kernel",
"pool",
"the",
"double",
"precision",
"values",
"of",
"an",
"item",
"associated",
"with",
"a",
"body",
"where",
"the",
"body",
"is",
"specified",
"by",
"an",
"integer",
"ID",
"code",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L541-L566 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bodvrd | def bodvrd(bodynm, item, maxn):
"""
Fetch from the kernel pool the double precision values
of an item associated with a body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvrd_c.html
:param bodynm: Body name.
:type bodynm: str
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: tuple of (dim, values)
:rtype: tuple
"""
bodynm = stypes.stringToCharP(bodynm)
item = stypes.stringToCharP(item)
dim = ctypes.c_int()
values = stypes.emptyDoubleVector(maxn)
maxn = ctypes.c_int(maxn)
libspice.bodvrd_c(bodynm, item, maxn, ctypes.byref(dim), values)
return dim.value, stypes.cVectorToPython(values) | python | def bodvrd(bodynm, item, maxn):
"""
Fetch from the kernel pool the double precision values
of an item associated with a body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvrd_c.html
:param bodynm: Body name.
:type bodynm: str
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: tuple of (dim, values)
:rtype: tuple
"""
bodynm = stypes.stringToCharP(bodynm)
item = stypes.stringToCharP(item)
dim = ctypes.c_int()
values = stypes.emptyDoubleVector(maxn)
maxn = ctypes.c_int(maxn)
libspice.bodvrd_c(bodynm, item, maxn, ctypes.byref(dim), values)
return dim.value, stypes.cVectorToPython(values) | [
"def",
"bodvrd",
"(",
"bodynm",
",",
"item",
",",
"maxn",
")",
":",
"bodynm",
"=",
"stypes",
".",
"stringToCharP",
"(",
"bodynm",
")",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"dim",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"values",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"maxn",
")",
"maxn",
"=",
"ctypes",
".",
"c_int",
"(",
"maxn",
")",
"libspice",
".",
"bodvrd_c",
"(",
"bodynm",
",",
"item",
",",
"maxn",
",",
"ctypes",
".",
"byref",
"(",
"dim",
")",
",",
"values",
")",
"return",
"dim",
".",
"value",
",",
"stypes",
".",
"cVectorToPython",
"(",
"values",
")"
] | Fetch from the kernel pool the double precision values
of an item associated with a body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvrd_c.html
:param bodynm: Body name.
:type bodynm: str
:param item:
Item for which values are desired,
("RADII", "NUT_PREC_ANGLES", etc.)
:type item: str
:param maxn: Maximum number of values that may be returned.
:type maxn: int
:return: tuple of (dim, values)
:rtype: tuple | [
"Fetch",
"from",
"the",
"kernel",
"pool",
"the",
"double",
"precision",
"values",
"of",
"an",
"item",
"associated",
"with",
"a",
"body",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L570-L594 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bschoc | def bschoc(value, ndim, lenvals, array, order):
"""
Do a binary search for a given value within a character string array,
accompanied by an order vector. Return the index of the matching array
entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int
"""
value = stypes.stringToCharP(value)
ndim = ctypes.c_int(ndim)
lenvals = ctypes.c_int(lenvals)
array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)
order = stypes.toIntVector(order)
return libspice.bschoc_c(value, ndim, lenvals, array, order) | python | def bschoc(value, ndim, lenvals, array, order):
"""
Do a binary search for a given value within a character string array,
accompanied by an order vector. Return the index of the matching array
entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int
"""
value = stypes.stringToCharP(value)
ndim = ctypes.c_int(ndim)
lenvals = ctypes.c_int(lenvals)
array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)
order = stypes.toIntVector(order)
return libspice.bschoc_c(value, ndim, lenvals, array, order) | [
"def",
"bschoc",
"(",
"value",
",",
"ndim",
",",
"lenvals",
",",
"array",
",",
"order",
")",
":",
"value",
"=",
"stypes",
".",
"stringToCharP",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"lenvals",
"=",
"ctypes",
".",
"c_int",
"(",
"lenvals",
")",
"array",
"=",
"stypes",
".",
"listToCharArrayPtr",
"(",
"array",
",",
"xLen",
"=",
"lenvals",
",",
"yLen",
"=",
"ndim",
")",
"order",
"=",
"stypes",
".",
"toIntVector",
"(",
"order",
")",
"return",
"libspice",
".",
"bschoc_c",
"(",
"value",
",",
"ndim",
",",
"lenvals",
",",
"array",
",",
"order",
")"
] | Do a binary search for a given value within a character string array,
accompanied by an order vector. Return the index of the matching array
entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int | [
"Do",
"a",
"binary",
"search",
"for",
"a",
"given",
"value",
"within",
"a",
"character",
"string",
"array",
"accompanied",
"by",
"an",
"order",
"vector",
".",
"Return",
"the",
"index",
"of",
"the",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"is",
"not",
"found",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L648-L674 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bschoi | def bschoi(value, ndim, array, order):
"""
Do a binary search for a given value within an integer array,
accompanied by an order vector. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html
:param value: Key value to be found in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Integer array to search.
:type array: Array of ints
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int
"""
value = ctypes.c_int(value)
ndim = ctypes.c_int(ndim)
array = stypes.toIntVector(array)
order = stypes.toIntVector(order)
return libspice.bschoi_c(value, ndim, array, order) | python | def bschoi(value, ndim, array, order):
"""
Do a binary search for a given value within an integer array,
accompanied by an order vector. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html
:param value: Key value to be found in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Integer array to search.
:type array: Array of ints
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int
"""
value = ctypes.c_int(value)
ndim = ctypes.c_int(ndim)
array = stypes.toIntVector(array)
order = stypes.toIntVector(order)
return libspice.bschoi_c(value, ndim, array, order) | [
"def",
"bschoi",
"(",
"value",
",",
"ndim",
",",
"array",
",",
"order",
")",
":",
"value",
"=",
"ctypes",
".",
"c_int",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"array",
")",
"order",
"=",
"stypes",
".",
"toIntVector",
"(",
"order",
")",
"return",
"libspice",
".",
"bschoi_c",
"(",
"value",
",",
"ndim",
",",
"array",
",",
"order",
")"
] | Do a binary search for a given value within an integer array,
accompanied by an order vector. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html
:param value: Key value to be found in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Integer array to search.
:type array: Array of ints
:param order: Order vector.
:type order: Array of ints
:return: index
:rtype: int | [
"Do",
"a",
"binary",
"search",
"for",
"a",
"given",
"value",
"within",
"an",
"integer",
"array",
"accompanied",
"by",
"an",
"order",
"vector",
".",
"Return",
"the",
"index",
"of",
"the",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"is",
"not",
"found",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L678-L701 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bsrchc | def bsrchc(value, ndim, lenvals, array):
"""
Do a binary earch for a given value within a character string array.
Return the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:return: index
:rtype: int
"""
value = stypes.stringToCharP(value)
ndim = ctypes.c_int(ndim)
lenvals = ctypes.c_int(lenvals)
array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)
return libspice.bsrchc_c(value, ndim, lenvals, array) | python | def bsrchc(value, ndim, lenvals, array):
"""
Do a binary earch for a given value within a character string array.
Return the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:return: index
:rtype: int
"""
value = stypes.stringToCharP(value)
ndim = ctypes.c_int(ndim)
lenvals = ctypes.c_int(lenvals)
array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim)
return libspice.bsrchc_c(value, ndim, lenvals, array) | [
"def",
"bsrchc",
"(",
"value",
",",
"ndim",
",",
"lenvals",
",",
"array",
")",
":",
"value",
"=",
"stypes",
".",
"stringToCharP",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"lenvals",
"=",
"ctypes",
".",
"c_int",
"(",
"lenvals",
")",
"array",
"=",
"stypes",
".",
"listToCharArrayPtr",
"(",
"array",
",",
"xLen",
"=",
"lenvals",
",",
"yLen",
"=",
"ndim",
")",
"return",
"libspice",
".",
"bsrchc_c",
"(",
"value",
",",
"ndim",
",",
"lenvals",
",",
"array",
")"
] | Do a binary earch for a given value within a character string array.
Return the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html
:param value: Key value to be found in array.
:type value: str
:param ndim: Dimension of array.
:type ndim: int
:param lenvals: String length.
:type lenvals: int
:param array: Character string array to search.
:type array: list of strings
:return: index
:rtype: int | [
"Do",
"a",
"binary",
"earch",
"for",
"a",
"given",
"value",
"within",
"a",
"character",
"string",
"array",
".",
"Return",
"the",
"index",
"of",
"the",
"first",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"was",
"not",
"found",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L705-L728 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bsrchd | def bsrchd(value, ndim, array):
"""
Do a binary search for a key value within a double precision array,
assumed to be in increasing order. Return the index of the matching
array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html
:param value: Value to find in array.
:type value: float
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of floats
:return: index
:rtype: int
"""
value = ctypes.c_double(value)
ndim = ctypes.c_int(ndim)
array = stypes.toDoubleVector(array)
return libspice.bsrchd_c(value, ndim, array) | python | def bsrchd(value, ndim, array):
"""
Do a binary search for a key value within a double precision array,
assumed to be in increasing order. Return the index of the matching
array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html
:param value: Value to find in array.
:type value: float
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of floats
:return: index
:rtype: int
"""
value = ctypes.c_double(value)
ndim = ctypes.c_int(ndim)
array = stypes.toDoubleVector(array)
return libspice.bsrchd_c(value, ndim, array) | [
"def",
"bsrchd",
"(",
"value",
",",
"ndim",
",",
"array",
")",
":",
"value",
"=",
"ctypes",
".",
"c_double",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"array",
")",
"return",
"libspice",
".",
"bsrchd_c",
"(",
"value",
",",
"ndim",
",",
"array",
")"
] | Do a binary search for a key value within a double precision array,
assumed to be in increasing order. Return the index of the matching
array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html
:param value: Value to find in array.
:type value: float
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of floats
:return: index
:rtype: int | [
"Do",
"a",
"binary",
"search",
"for",
"a",
"key",
"value",
"within",
"a",
"double",
"precision",
"array",
"assumed",
"to",
"be",
"in",
"increasing",
"order",
".",
"Return",
"the",
"index",
"of",
"the",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"is",
"not",
"found",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L732-L752 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | bsrchi | def bsrchi(value, ndim, array):
"""
Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param value: Value to find in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of ints
:return: index
:rtype: int
"""
value = ctypes.c_int(value)
ndim = ctypes.c_int(ndim)
array = stypes.toIntVector(array)
return libspice.bsrchi_c(value, ndim, array) | python | def bsrchi(value, ndim, array):
"""
Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param value: Value to find in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of ints
:return: index
:rtype: int
"""
value = ctypes.c_int(value)
ndim = ctypes.c_int(ndim)
array = stypes.toIntVector(array)
return libspice.bsrchi_c(value, ndim, array) | [
"def",
"bsrchi",
"(",
"value",
",",
"ndim",
",",
"array",
")",
":",
"value",
"=",
"ctypes",
".",
"c_int",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"array",
")",
"return",
"libspice",
".",
"bsrchi_c",
"(",
"value",
",",
"ndim",
",",
"array",
")"
] | Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param value: Value to find in array.
:type value: int
:param ndim: Dimension of array.
:type ndim: int
:param array: Array to be searched.
:type array: Array of ints
:return: index
:rtype: int | [
"Do",
"a",
"binary",
"search",
"for",
"a",
"key",
"value",
"within",
"an",
"integer",
"array",
"assumed",
"to",
"be",
"in",
"increasing",
"order",
".",
"Return",
"the",
"index",
"of",
"the",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"is",
"not",
"found",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L756-L776 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ccifrm | def ccifrm(frclss, clssid, lenout=_default_len_out):
"""
Return the frame name, frame ID, and center associated with
a given frame class and class ID.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ccifrm_c.html
:param frclss: Class of frame.
:type frclss: int
:param clssid: Class ID of frame.
:type clssid: int
:param lenout: Maximum length of output string.
:type lenout: int
:return:
the frame name,
frame ID,
center.
:rtype: tuple
"""
frclss = ctypes.c_int(frclss)
clssid = ctypes.c_int(clssid)
lenout = ctypes.c_int(lenout)
frcode = ctypes.c_int()
frname = stypes.stringToCharP(lenout)
center = ctypes.c_int()
found = ctypes.c_int()
libspice.ccifrm_c(frclss, clssid, lenout, ctypes.byref(frcode), frname,
ctypes.byref(center), ctypes.byref(found))
return frcode.value, stypes.toPythonString(
frname), center.value, bool(found.value) | python | def ccifrm(frclss, clssid, lenout=_default_len_out):
"""
Return the frame name, frame ID, and center associated with
a given frame class and class ID.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ccifrm_c.html
:param frclss: Class of frame.
:type frclss: int
:param clssid: Class ID of frame.
:type clssid: int
:param lenout: Maximum length of output string.
:type lenout: int
:return:
the frame name,
frame ID,
center.
:rtype: tuple
"""
frclss = ctypes.c_int(frclss)
clssid = ctypes.c_int(clssid)
lenout = ctypes.c_int(lenout)
frcode = ctypes.c_int()
frname = stypes.stringToCharP(lenout)
center = ctypes.c_int()
found = ctypes.c_int()
libspice.ccifrm_c(frclss, clssid, lenout, ctypes.byref(frcode), frname,
ctypes.byref(center), ctypes.byref(found))
return frcode.value, stypes.toPythonString(
frname), center.value, bool(found.value) | [
"def",
"ccifrm",
"(",
"frclss",
",",
"clssid",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"frclss",
"=",
"ctypes",
".",
"c_int",
"(",
"frclss",
")",
"clssid",
"=",
"ctypes",
".",
"c_int",
"(",
"clssid",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"frcode",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"frname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",
"center",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"ccifrm_c",
"(",
"frclss",
",",
"clssid",
",",
"lenout",
",",
"ctypes",
".",
"byref",
"(",
"frcode",
")",
",",
"frname",
",",
"ctypes",
".",
"byref",
"(",
"center",
")",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"frcode",
".",
"value",
",",
"stypes",
".",
"toPythonString",
"(",
"frname",
")",
",",
"center",
".",
"value",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Return the frame name, frame ID, and center associated with
a given frame class and class ID.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ccifrm_c.html
:param frclss: Class of frame.
:type frclss: int
:param clssid: Class ID of frame.
:type clssid: int
:param lenout: Maximum length of output string.
:type lenout: int
:return:
the frame name,
frame ID,
center.
:rtype: tuple | [
"Return",
"the",
"frame",
"name",
"frame",
"ID",
"and",
"center",
"associated",
"with",
"a",
"given",
"frame",
"class",
"and",
"class",
"ID",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L800-L829 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cgv2el | def cgv2el(center, vec1, vec2):
"""
Form a SPICE ellipse from a center vector and two generating vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cgv2el_c.html
:param center: Center Vector
:type center: 3-Element Array of floats
:param vec1: Vector 1
:type vec1: 3-Element Array of floats
:param vec2: Vector 2
:type vec2: 3-Element Array of floats
:return: Ellipse
:rtype: spiceypy.utils.support_types.Ellipse
"""
center = stypes.toDoubleVector(center)
vec1 = stypes.toDoubleVector(vec1)
vec2 = stypes.toDoubleVector(vec2)
ellipse = stypes.Ellipse()
libspice.cgv2el_c(center, vec1, vec2, ctypes.byref(ellipse))
return ellipse | python | def cgv2el(center, vec1, vec2):
"""
Form a SPICE ellipse from a center vector and two generating vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cgv2el_c.html
:param center: Center Vector
:type center: 3-Element Array of floats
:param vec1: Vector 1
:type vec1: 3-Element Array of floats
:param vec2: Vector 2
:type vec2: 3-Element Array of floats
:return: Ellipse
:rtype: spiceypy.utils.support_types.Ellipse
"""
center = stypes.toDoubleVector(center)
vec1 = stypes.toDoubleVector(vec1)
vec2 = stypes.toDoubleVector(vec2)
ellipse = stypes.Ellipse()
libspice.cgv2el_c(center, vec1, vec2, ctypes.byref(ellipse))
return ellipse | [
"def",
"cgv2el",
"(",
"center",
",",
"vec1",
",",
"vec2",
")",
":",
"center",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"center",
")",
"vec1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vec1",
")",
"vec2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"vec2",
")",
"ellipse",
"=",
"stypes",
".",
"Ellipse",
"(",
")",
"libspice",
".",
"cgv2el_c",
"(",
"center",
",",
"vec1",
",",
"vec2",
",",
"ctypes",
".",
"byref",
"(",
"ellipse",
")",
")",
"return",
"ellipse"
] | Form a SPICE ellipse from a center vector and two generating vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cgv2el_c.html
:param center: Center Vector
:type center: 3-Element Array of floats
:param vec1: Vector 1
:type vec1: 3-Element Array of floats
:param vec2: Vector 2
:type vec2: 3-Element Array of floats
:return: Ellipse
:rtype: spiceypy.utils.support_types.Ellipse | [
"Form",
"a",
"SPICE",
"ellipse",
"from",
"a",
"center",
"vector",
"and",
"two",
"generating",
"vectors",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L833-L853 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cidfrm | def cidfrm(cent, lenout=_default_len_out):
"""
Retrieve frame ID code and name to associate with a frame center.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cidfrm_c.html
:param cent: An object to associate a frame with.
:type cent: int
:param lenout: Available space in output string frname.
:type lenout: int
:return:
frame ID code,
name to associate with a frame center.
:rtype: tuple
"""
cent = ctypes.c_int(cent)
lenout = ctypes.c_int(lenout)
frcode = ctypes.c_int()
frname = stypes.stringToCharP(lenout)
found = ctypes.c_int()
libspice.cidfrm_c(cent, lenout, ctypes.byref(frcode), frname,
ctypes.byref(found))
return frcode.value, stypes.toPythonString(frname), bool(found.value) | python | def cidfrm(cent, lenout=_default_len_out):
"""
Retrieve frame ID code and name to associate with a frame center.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cidfrm_c.html
:param cent: An object to associate a frame with.
:type cent: int
:param lenout: Available space in output string frname.
:type lenout: int
:return:
frame ID code,
name to associate with a frame center.
:rtype: tuple
"""
cent = ctypes.c_int(cent)
lenout = ctypes.c_int(lenout)
frcode = ctypes.c_int()
frname = stypes.stringToCharP(lenout)
found = ctypes.c_int()
libspice.cidfrm_c(cent, lenout, ctypes.byref(frcode), frname,
ctypes.byref(found))
return frcode.value, stypes.toPythonString(frname), bool(found.value) | [
"def",
"cidfrm",
"(",
"cent",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"cent",
"=",
"ctypes",
".",
"c_int",
"(",
"cent",
")",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"frcode",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"frname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"cidfrm_c",
"(",
"cent",
",",
"lenout",
",",
"ctypes",
".",
"byref",
"(",
"frcode",
")",
",",
"frname",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"frcode",
".",
"value",
",",
"stypes",
".",
"toPythonString",
"(",
"frname",
")",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Retrieve frame ID code and name to associate with a frame center.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cidfrm_c.html
:param cent: An object to associate a frame with.
:type cent: int
:param lenout: Available space in output string frname.
:type lenout: int
:return:
frame ID code,
name to associate with a frame center.
:rtype: tuple | [
"Retrieve",
"frame",
"ID",
"code",
"and",
"name",
"to",
"associate",
"with",
"a",
"frame",
"center",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L918-L940 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckcov | def ckcov(ck, idcode, needav, level, tol, timsys, cover=None):
"""
Find the coverage window for a specified object in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcov_c.html
:param ck: Name of CK file.
:type ck: str
:param idcode: ID code of object.
:type idcode: int
:param needav: Flag indicating whether angular velocity is needed.
:type needav: bool
:param level: Coverage level: (SEGMENT OR INTERVAL)
:type level: str
:param tol: Tolerance in ticks.
:type tol: float
:param timsys: Time system used to represent coverage.
:type timsys: str
:param cover: Window giving coverage for idcode.
:type cover: Optional SpiceCell
:return: coverage window for a specified object in a specified CK file
:rtype: spiceypy.utils.support_types.SpiceCell
"""
ck = stypes.stringToCharP(ck)
idcode = ctypes.c_int(idcode)
needav = ctypes.c_int(needav)
level = stypes.stringToCharP(level)
tol = ctypes.c_double(tol)
timsys = stypes.stringToCharP(timsys)
if not cover:
cover = stypes.SPICEDOUBLE_CELL(20000)
assert isinstance(cover, stypes.SpiceCell)
assert cover.dtype == 1
libspice.ckcov_c(ck, idcode, needav, level, tol, timsys,
ctypes.byref(cover))
return cover | python | def ckcov(ck, idcode, needav, level, tol, timsys, cover=None):
"""
Find the coverage window for a specified object in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcov_c.html
:param ck: Name of CK file.
:type ck: str
:param idcode: ID code of object.
:type idcode: int
:param needav: Flag indicating whether angular velocity is needed.
:type needav: bool
:param level: Coverage level: (SEGMENT OR INTERVAL)
:type level: str
:param tol: Tolerance in ticks.
:type tol: float
:param timsys: Time system used to represent coverage.
:type timsys: str
:param cover: Window giving coverage for idcode.
:type cover: Optional SpiceCell
:return: coverage window for a specified object in a specified CK file
:rtype: spiceypy.utils.support_types.SpiceCell
"""
ck = stypes.stringToCharP(ck)
idcode = ctypes.c_int(idcode)
needav = ctypes.c_int(needav)
level = stypes.stringToCharP(level)
tol = ctypes.c_double(tol)
timsys = stypes.stringToCharP(timsys)
if not cover:
cover = stypes.SPICEDOUBLE_CELL(20000)
assert isinstance(cover, stypes.SpiceCell)
assert cover.dtype == 1
libspice.ckcov_c(ck, idcode, needav, level, tol, timsys,
ctypes.byref(cover))
return cover | [
"def",
"ckcov",
"(",
"ck",
",",
"idcode",
",",
"needav",
",",
"level",
",",
"tol",
",",
"timsys",
",",
"cover",
"=",
"None",
")",
":",
"ck",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ck",
")",
"idcode",
"=",
"ctypes",
".",
"c_int",
"(",
"idcode",
")",
"needav",
"=",
"ctypes",
".",
"c_int",
"(",
"needav",
")",
"level",
"=",
"stypes",
".",
"stringToCharP",
"(",
"level",
")",
"tol",
"=",
"ctypes",
".",
"c_double",
"(",
"tol",
")",
"timsys",
"=",
"stypes",
".",
"stringToCharP",
"(",
"timsys",
")",
"if",
"not",
"cover",
":",
"cover",
"=",
"stypes",
".",
"SPICEDOUBLE_CELL",
"(",
"20000",
")",
"assert",
"isinstance",
"(",
"cover",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"cover",
".",
"dtype",
"==",
"1",
"libspice",
".",
"ckcov_c",
"(",
"ck",
",",
"idcode",
",",
"needav",
",",
"level",
",",
"tol",
",",
"timsys",
",",
"ctypes",
".",
"byref",
"(",
"cover",
")",
")",
"return",
"cover"
] | Find the coverage window for a specified object in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcov_c.html
:param ck: Name of CK file.
:type ck: str
:param idcode: ID code of object.
:type idcode: int
:param needav: Flag indicating whether angular velocity is needed.
:type needav: bool
:param level: Coverage level: (SEGMENT OR INTERVAL)
:type level: str
:param tol: Tolerance in ticks.
:type tol: float
:param timsys: Time system used to represent coverage.
:type timsys: str
:param cover: Window giving coverage for idcode.
:type cover: Optional SpiceCell
:return: coverage window for a specified object in a specified CK file
:rtype: spiceypy.utils.support_types.SpiceCell | [
"Find",
"the",
"coverage",
"window",
"for",
"a",
"specified",
"object",
"in",
"a",
"specified",
"CK",
"file",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L958-L993 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cklpf | def cklpf(filename):
"""
Load a CK pointing file for use by the CK readers. Return that
file's handle, to be used by other CK routines to refer to the
file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cklpf_c.html
:param filename: Name of the CK file to be loaded.
:type filename: str
:return: Loaded file's handle.
:rtype: int
"""
filename = stypes.stringToCharP(filename)
handle = ctypes.c_int()
libspice.cklpf_c(filename, ctypes.byref(handle))
return handle.value | python | def cklpf(filename):
"""
Load a CK pointing file for use by the CK readers. Return that
file's handle, to be used by other CK routines to refer to the
file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cklpf_c.html
:param filename: Name of the CK file to be loaded.
:type filename: str
:return: Loaded file's handle.
:rtype: int
"""
filename = stypes.stringToCharP(filename)
handle = ctypes.c_int()
libspice.cklpf_c(filename, ctypes.byref(handle))
return handle.value | [
"def",
"cklpf",
"(",
"filename",
")",
":",
"filename",
"=",
"stypes",
".",
"stringToCharP",
"(",
"filename",
")",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"cklpf_c",
"(",
"filename",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
"return",
"handle",
".",
"value"
] | Load a CK pointing file for use by the CK readers. Return that
file's handle, to be used by other CK routines to refer to the
file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cklpf_c.html
:param filename: Name of the CK file to be loaded.
:type filename: str
:return: Loaded file's handle.
:rtype: int | [
"Load",
"a",
"CK",
"pointing",
"file",
"for",
"use",
"by",
"the",
"CK",
"readers",
".",
"Return",
"that",
"file",
"s",
"handle",
"to",
"be",
"used",
"by",
"other",
"CK",
"routines",
"to",
"refer",
"to",
"the",
"file",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1067-L1083 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckobj | def ckobj(ck, outCell=None):
"""
Find the set of ID codes of all objects in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html
:param ck: Name of CK file.
:type ck: str
:param outCell: Optional user provided Spice Int cell.
:type outCell: Optional spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of objects in CK file.
:rtype: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(ck, str)
ck = stypes.stringToCharP(ck)
if not outCell:
outCell = stypes.SPICEINT_CELL(1000)
assert isinstance(outCell, stypes.SpiceCell)
assert outCell.dtype == 2
libspice.ckobj_c(ck, ctypes.byref(outCell))
return outCell | python | def ckobj(ck, outCell=None):
"""
Find the set of ID codes of all objects in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html
:param ck: Name of CK file.
:type ck: str
:param outCell: Optional user provided Spice Int cell.
:type outCell: Optional spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of objects in CK file.
:rtype: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(ck, str)
ck = stypes.stringToCharP(ck)
if not outCell:
outCell = stypes.SPICEINT_CELL(1000)
assert isinstance(outCell, stypes.SpiceCell)
assert outCell.dtype == 2
libspice.ckobj_c(ck, ctypes.byref(outCell))
return outCell | [
"def",
"ckobj",
"(",
"ck",
",",
"outCell",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"ck",
",",
"str",
")",
"ck",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ck",
")",
"if",
"not",
"outCell",
":",
"outCell",
"=",
"stypes",
".",
"SPICEINT_CELL",
"(",
"1000",
")",
"assert",
"isinstance",
"(",
"outCell",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"outCell",
".",
"dtype",
"==",
"2",
"libspice",
".",
"ckobj_c",
"(",
"ck",
",",
"ctypes",
".",
"byref",
"(",
"outCell",
")",
")",
"return",
"outCell"
] | Find the set of ID codes of all objects in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html
:param ck: Name of CK file.
:type ck: str
:param outCell: Optional user provided Spice Int cell.
:type outCell: Optional spiceypy.utils.support_types.SpiceCell
:return: Set of ID codes of objects in CK file.
:rtype: spiceypy.utils.support_types.SpiceCell | [
"Find",
"the",
"set",
"of",
"ID",
"codes",
"of",
"all",
"objects",
"in",
"a",
"specified",
"CK",
"file",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1087-L1107 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckopn | def ckopn(filename, ifname, ncomch):
"""
Open a new CK file, returning the handle of the opened file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckopn_c.html
:param filename: The name of the CK file to be opened.
:type filename: str
:param ifname: The internal filename for the CK.
:type ifname: str
:param ncomch: The number of characters to reserve for comments.
:type ncomch: int
:return: The handle of the opened CK file.
:rtype: int
"""
filename = stypes.stringToCharP(filename)
ifname = stypes.stringToCharP(ifname)
ncomch = ctypes.c_int(ncomch)
handle = ctypes.c_int()
libspice.ckopn_c(filename, ifname, ncomch, ctypes.byref(handle))
return handle.value | python | def ckopn(filename, ifname, ncomch):
"""
Open a new CK file, returning the handle of the opened file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckopn_c.html
:param filename: The name of the CK file to be opened.
:type filename: str
:param ifname: The internal filename for the CK.
:type ifname: str
:param ncomch: The number of characters to reserve for comments.
:type ncomch: int
:return: The handle of the opened CK file.
:rtype: int
"""
filename = stypes.stringToCharP(filename)
ifname = stypes.stringToCharP(ifname)
ncomch = ctypes.c_int(ncomch)
handle = ctypes.c_int()
libspice.ckopn_c(filename, ifname, ncomch, ctypes.byref(handle))
return handle.value | [
"def",
"ckopn",
"(",
"filename",
",",
"ifname",
",",
"ncomch",
")",
":",
"filename",
"=",
"stypes",
".",
"stringToCharP",
"(",
"filename",
")",
"ifname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ifname",
")",
"ncomch",
"=",
"ctypes",
".",
"c_int",
"(",
"ncomch",
")",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"ckopn_c",
"(",
"filename",
",",
"ifname",
",",
"ncomch",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
"return",
"handle",
".",
"value"
] | Open a new CK file, returning the handle of the opened file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckopn_c.html
:param filename: The name of the CK file to be opened.
:type filename: str
:param ifname: The internal filename for the CK.
:type ifname: str
:param ncomch: The number of characters to reserve for comments.
:type ncomch: int
:return: The handle of the opened CK file.
:rtype: int | [
"Open",
"a",
"new",
"CK",
"file",
"returning",
"the",
"handle",
"of",
"the",
"opened",
"file",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1111-L1131 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckw01 | def ckw01(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats,
avvs):
"""
Add a type 1 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw01_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
sclkdp = stypes.toDoubleVector(sclkdp)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
libspice.ckw01_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec,
sclkdp, quats, avvs) | python | def ckw01(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats,
avvs):
"""
Add a type 1 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw01_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
sclkdp = stypes.toDoubleVector(sclkdp)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
libspice.ckw01_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec,
sclkdp, quats, avvs) | [
"def",
"ckw01",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"nrec",
",",
"sclkdp",
",",
"quats",
",",
"avvs",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"begtim",
"=",
"ctypes",
".",
"c_double",
"(",
"begtim",
")",
"endtim",
"=",
"ctypes",
".",
"c_double",
"(",
"endtim",
")",
"inst",
"=",
"ctypes",
".",
"c_int",
"(",
"inst",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"avflag",
"=",
"ctypes",
".",
"c_int",
"(",
"avflag",
")",
"segid",
"=",
"stypes",
".",
"stringToCharP",
"(",
"segid",
")",
"sclkdp",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"sclkdp",
")",
"quats",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"quats",
")",
"avvs",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"avvs",
")",
"nrec",
"=",
"ctypes",
".",
"c_int",
"(",
"nrec",
")",
"libspice",
".",
"ckw01_c",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"nrec",
",",
"sclkdp",
",",
"quats",
",",
"avvs",
")"
] | Add a type 1 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw01_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats | [
"Add",
"a",
"type",
"1",
"segment",
"to",
"a",
"C",
"-",
"kernel",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1150-L1192 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckw02 | def ckw02(handle, begtim, endtim, inst, ref, segid, nrec, start, stop, quats,
avvs, rates):
"""
Write a type 2 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param start: Encoded SCLK interval start times.
:type start: Array of floats
:param stop: Encoded SCLK interval stop times.
:type stop: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param rates: Number of seconds per tick for each interval.
:type rates: Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
segid = stypes.stringToCharP(segid)
start = stypes.toDoubleVector(start)
stop = stypes.toDoubleVector(stop)
rates = stypes.toDoubleVector(rates)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
libspice.ckw02_c(handle, begtim, endtim, inst, ref, segid, nrec, start,
stop, quats, avvs, rates) | python | def ckw02(handle, begtim, endtim, inst, ref, segid, nrec, start, stop, quats,
avvs, rates):
"""
Write a type 2 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param start: Encoded SCLK interval start times.
:type start: Array of floats
:param stop: Encoded SCLK interval stop times.
:type stop: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param rates: Number of seconds per tick for each interval.
:type rates: Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
segid = stypes.stringToCharP(segid)
start = stypes.toDoubleVector(start)
stop = stypes.toDoubleVector(stop)
rates = stypes.toDoubleVector(rates)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
libspice.ckw02_c(handle, begtim, endtim, inst, ref, segid, nrec, start,
stop, quats, avvs, rates) | [
"def",
"ckw02",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"segid",
",",
"nrec",
",",
"start",
",",
"stop",
",",
"quats",
",",
"avvs",
",",
"rates",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"begtim",
"=",
"ctypes",
".",
"c_double",
"(",
"begtim",
")",
"endtim",
"=",
"ctypes",
".",
"c_double",
"(",
"endtim",
")",
"inst",
"=",
"ctypes",
".",
"c_int",
"(",
"inst",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"segid",
"=",
"stypes",
".",
"stringToCharP",
"(",
"segid",
")",
"start",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"start",
")",
"stop",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"stop",
")",
"rates",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"rates",
")",
"quats",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"quats",
")",
"avvs",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"avvs",
")",
"nrec",
"=",
"ctypes",
".",
"c_int",
"(",
"nrec",
")",
"libspice",
".",
"ckw02_c",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"segid",
",",
"nrec",
",",
"start",
",",
"stop",
",",
"quats",
",",
"avvs",
",",
"rates",
")"
] | Write a type 2 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param start: Encoded SCLK interval start times.
:type start: Array of floats
:param stop: Encoded SCLK interval stop times.
:type stop: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param rates: Number of seconds per tick for each interval.
:type rates: Array of floats | [
"Write",
"a",
"type",
"2",
"segment",
"to",
"a",
"C",
"-",
"kernel",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1196-L1241 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckw03 | def ckw03(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats,
avvs, nints, starts):
"""
Add a type 3 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw03_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
sclkdp = stypes.toDoubleVector(sclkdp)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
starts = stypes.toDoubleVector(starts)
nints = ctypes.c_int(nints)
libspice.ckw03_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec,
sclkdp, quats, avvs, nints, starts) | python | def ckw03(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats,
avvs, nints, starts):
"""
Add a type 3 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw03_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats
"""
handle = ctypes.c_int(handle)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
sclkdp = stypes.toDoubleVector(sclkdp)
quats = stypes.toDoubleMatrix(quats)
avvs = stypes.toDoubleMatrix(avvs)
nrec = ctypes.c_int(nrec)
starts = stypes.toDoubleVector(starts)
nints = ctypes.c_int(nints)
libspice.ckw03_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec,
sclkdp, quats, avvs, nints, starts) | [
"def",
"ckw03",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"nrec",
",",
"sclkdp",
",",
"quats",
",",
"avvs",
",",
"nints",
",",
"starts",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"begtim",
"=",
"ctypes",
".",
"c_double",
"(",
"begtim",
")",
"endtim",
"=",
"ctypes",
".",
"c_double",
"(",
"endtim",
")",
"inst",
"=",
"ctypes",
".",
"c_int",
"(",
"inst",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"avflag",
"=",
"ctypes",
".",
"c_int",
"(",
"avflag",
")",
"segid",
"=",
"stypes",
".",
"stringToCharP",
"(",
"segid",
")",
"sclkdp",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"sclkdp",
")",
"quats",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"quats",
")",
"avvs",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"avvs",
")",
"nrec",
"=",
"ctypes",
".",
"c_int",
"(",
"nrec",
")",
"starts",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"starts",
")",
"nints",
"=",
"ctypes",
".",
"c_int",
"(",
"nints",
")",
"libspice",
".",
"ckw03_c",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"nrec",
",",
"sclkdp",
",",
"quats",
",",
"avvs",
",",
"nints",
",",
"starts",
")"
] | Add a type 3 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw03_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param nrec: Number of pointing records.
:type nrec: int
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param quats: Quaternions representing instrument pointing.
:type quats: Nx4-Element Array of floats
:param avvs: Angular velocity vectors.
:type avvs: Nx3-Element Array of floats
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats | [
"Add",
"a",
"type",
"3",
"segment",
"to",
"a",
"C",
"-",
"kernel",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1245-L1293 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | ckw05 | def ckw05(handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid,
sclkdp, packts, rate, nints, starts):
"""
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param subtype: CK type 5 subtype code. Can be: 0, 1, 2, 3 see naif docs via link above.
:type subtype: int
:param degree: Degree of interpolating polynomials.
:type degree: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param packts: Array of packets.
:type packts: Some NxM vector of floats
:param rate: Nominal SCLK rate in seconds per tick.
:type rate: float
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats
"""
handle = ctypes.c_int(handle)
subtype = ctypes.c_int(subtype)
degree = ctypes.c_int(degree)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
n = ctypes.c_int(len(packts))
sclkdp = stypes.toDoubleVector(sclkdp)
packts = stypes.toDoubleMatrix(packts)
rate = ctypes.c_double(rate)
nints = ctypes.c_int(nints)
starts = stypes.toDoubleVector(starts)
libspice.ckw05_c(handle, subtype, degree, begtim, endtim, inst, ref, avflag,
segid, n, sclkdp, packts, rate, nints, starts) | python | def ckw05(handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid,
sclkdp, packts, rate, nints, starts):
"""
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param subtype: CK type 5 subtype code. Can be: 0, 1, 2, 3 see naif docs via link above.
:type subtype: int
:param degree: Degree of interpolating polynomials.
:type degree: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param packts: Array of packets.
:type packts: Some NxM vector of floats
:param rate: Nominal SCLK rate in seconds per tick.
:type rate: float
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats
"""
handle = ctypes.c_int(handle)
subtype = ctypes.c_int(subtype)
degree = ctypes.c_int(degree)
begtim = ctypes.c_double(begtim)
endtim = ctypes.c_double(endtim)
inst = ctypes.c_int(inst)
ref = stypes.stringToCharP(ref)
avflag = ctypes.c_int(avflag)
segid = stypes.stringToCharP(segid)
n = ctypes.c_int(len(packts))
sclkdp = stypes.toDoubleVector(sclkdp)
packts = stypes.toDoubleMatrix(packts)
rate = ctypes.c_double(rate)
nints = ctypes.c_int(nints)
starts = stypes.toDoubleVector(starts)
libspice.ckw05_c(handle, subtype, degree, begtim, endtim, inst, ref, avflag,
segid, n, sclkdp, packts, rate, nints, starts) | [
"def",
"ckw05",
"(",
"handle",
",",
"subtype",
",",
"degree",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"sclkdp",
",",
"packts",
",",
"rate",
",",
"nints",
",",
"starts",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"subtype",
"=",
"ctypes",
".",
"c_int",
"(",
"subtype",
")",
"degree",
"=",
"ctypes",
".",
"c_int",
"(",
"degree",
")",
"begtim",
"=",
"ctypes",
".",
"c_double",
"(",
"begtim",
")",
"endtim",
"=",
"ctypes",
".",
"c_double",
"(",
"endtim",
")",
"inst",
"=",
"ctypes",
".",
"c_int",
"(",
"inst",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ref",
")",
"avflag",
"=",
"ctypes",
".",
"c_int",
"(",
"avflag",
")",
"segid",
"=",
"stypes",
".",
"stringToCharP",
"(",
"segid",
")",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"packts",
")",
")",
"sclkdp",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"sclkdp",
")",
"packts",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"packts",
")",
"rate",
"=",
"ctypes",
".",
"c_double",
"(",
"rate",
")",
"nints",
"=",
"ctypes",
".",
"c_int",
"(",
"nints",
")",
"starts",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"starts",
")",
"libspice",
".",
"ckw05_c",
"(",
"handle",
",",
"subtype",
",",
"degree",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"n",
",",
"sclkdp",
",",
"packts",
",",
"rate",
",",
"nints",
",",
"starts",
")"
] | Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param subtype: CK type 5 subtype code. Can be: 0, 1, 2, 3 see naif docs via link above.
:type subtype: int
:param degree: Degree of interpolating polynomials.
:type degree: int
:param begtim: The beginning encoded SCLK of the segment.
:type begtim: float
:param endtim: The ending encoded SCLK of the segment.
:type endtim: float
:param inst: The NAIF instrument ID code.
:type inst: int
:param ref: The reference frame of the segment.
:type ref: str
:param avflag: True if the segment will contain angular velocity.
:type avflag: bool
:param segid: Segment identifier.
:type segid: str
:param sclkdp: Encoded SCLK times.
:type sclkdp: Array of floats
:param packts: Array of packets.
:type packts: Some NxM vector of floats
:param rate: Nominal SCLK rate in seconds per tick.
:type rate: float
:param nints: Number of intervals.
:type nints: int
:param starts: Encoded SCLK interval start times.
:type starts: Array of floats | [
"Write",
"a",
"type",
"5",
"segment",
"to",
"a",
"CK",
"file",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1297-L1349 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cltext | def cltext(fname):
"""
Internal undocumented command for closing a text file opened by RDTEXT.
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, rdtext.f::
C$Procedure CLTEXT ( Close a text file opened by RDTEXT)
ENTRY CLTEXT ( FILE )
CHARACTER*(*) FILE
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C FILE I Text file to be closed.
CSPICE, rdtext.c::
/* $Procedure CLTEXT ( Close a text file opened by RDTEXT) */
/* Subroutine */ int cltext_(char *file, ftnlen file_len)
:param fname: Text file to be closed.
:type fname: str
"""
fnameP = stypes.stringToCharP(fname)
fname_len = ctypes.c_int(len(fname))
libspice.cltext_(fnameP, fname_len) | python | def cltext(fname):
"""
Internal undocumented command for closing a text file opened by RDTEXT.
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, rdtext.f::
C$Procedure CLTEXT ( Close a text file opened by RDTEXT)
ENTRY CLTEXT ( FILE )
CHARACTER*(*) FILE
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C FILE I Text file to be closed.
CSPICE, rdtext.c::
/* $Procedure CLTEXT ( Close a text file opened by RDTEXT) */
/* Subroutine */ int cltext_(char *file, ftnlen file_len)
:param fname: Text file to be closed.
:type fname: str
"""
fnameP = stypes.stringToCharP(fname)
fname_len = ctypes.c_int(len(fname))
libspice.cltext_(fnameP, fname_len) | [
"def",
"cltext",
"(",
"fname",
")",
":",
"fnameP",
"=",
"stypes",
".",
"stringToCharP",
"(",
"fname",
")",
"fname_len",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"fname",
")",
")",
"libspice",
".",
"cltext_",
"(",
"fnameP",
",",
"fname_len",
")"
] | Internal undocumented command for closing a text file opened by RDTEXT.
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, rdtext.f::
C$Procedure CLTEXT ( Close a text file opened by RDTEXT)
ENTRY CLTEXT ( FILE )
CHARACTER*(*) FILE
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C FILE I Text file to be closed.
CSPICE, rdtext.c::
/* $Procedure CLTEXT ( Close a text file opened by RDTEXT) */
/* Subroutine */ int cltext_(char *file, ftnlen file_len)
:param fname: Text file to be closed.
:type fname: str | [
"Internal",
"undocumented",
"command",
"for",
"closing",
"a",
"text",
"file",
"opened",
"by",
"RDTEXT",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1381-L1407 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cmprss | def cmprss(delim, n, instr, lenout=_default_len_out):
"""
Compress a character string by removing occurrences of
more than N consecutive occurrences of a specified
character.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html
:param delim: Delimiter to be compressed.
:type delim: str
:param n: Maximum consecutive occurrences of delim.
:type n: int
:param instr: Input string.
:type instr: str
:param lenout: Optional available space in output string.
:type lenout: Optional int
:return: Compressed string.
:rtype: str
"""
delim = ctypes.c_char(delim.encode(encoding='UTF-8'))
n = ctypes.c_int(n)
instr = stypes.stringToCharP(instr)
output = stypes.stringToCharP(lenout)
libspice.cmprss_c(delim, n, instr, lenout, output)
return stypes.toPythonString(output) | python | def cmprss(delim, n, instr, lenout=_default_len_out):
"""
Compress a character string by removing occurrences of
more than N consecutive occurrences of a specified
character.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html
:param delim: Delimiter to be compressed.
:type delim: str
:param n: Maximum consecutive occurrences of delim.
:type n: int
:param instr: Input string.
:type instr: str
:param lenout: Optional available space in output string.
:type lenout: Optional int
:return: Compressed string.
:rtype: str
"""
delim = ctypes.c_char(delim.encode(encoding='UTF-8'))
n = ctypes.c_int(n)
instr = stypes.stringToCharP(instr)
output = stypes.stringToCharP(lenout)
libspice.cmprss_c(delim, n, instr, lenout, output)
return stypes.toPythonString(output) | [
"def",
"cmprss",
"(",
"delim",
",",
"n",
",",
"instr",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"delim",
"=",
"ctypes",
".",
"c_char",
"(",
"delim",
".",
"encode",
"(",
"encoding",
"=",
"'UTF-8'",
")",
")",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"n",
")",
"instr",
"=",
"stypes",
".",
"stringToCharP",
"(",
"instr",
")",
"output",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",
"libspice",
".",
"cmprss_c",
"(",
"delim",
",",
"n",
",",
"instr",
",",
"lenout",
",",
"output",
")",
"return",
"stypes",
".",
"toPythonString",
"(",
"output",
")"
] | Compress a character string by removing occurrences of
more than N consecutive occurrences of a specified
character.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html
:param delim: Delimiter to be compressed.
:type delim: str
:param n: Maximum consecutive occurrences of delim.
:type n: int
:param instr: Input string.
:type instr: str
:param lenout: Optional available space in output string.
:type lenout: Optional int
:return: Compressed string.
:rtype: str | [
"Compress",
"a",
"character",
"string",
"by",
"removing",
"occurrences",
"of",
"more",
"than",
"N",
"consecutive",
"occurrences",
"of",
"a",
"specified",
"character",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1411-L1435 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cnmfrm | def cnmfrm(cname, lenout=_default_len_out):
"""
Retrieve frame ID code and name to associate with an object.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html
:param cname: Name of the object to find a frame for.
:type cname: int
:param lenout: Maximum length available for frame name.
:type lenout: int
:return:
The ID code of the frame associated with cname,
The name of the frame with ID frcode.
:rtype: tuple
"""
lenout = ctypes.c_int(lenout)
frname = stypes.stringToCharP(lenout)
cname = stypes.stringToCharP(cname)
found = ctypes.c_int()
frcode = ctypes.c_int()
libspice.cnmfrm_c(cname, lenout, ctypes.byref(frcode), frname,
ctypes.byref(found))
return frcode.value, stypes.toPythonString(frname), bool(found.value) | python | def cnmfrm(cname, lenout=_default_len_out):
"""
Retrieve frame ID code and name to associate with an object.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html
:param cname: Name of the object to find a frame for.
:type cname: int
:param lenout: Maximum length available for frame name.
:type lenout: int
:return:
The ID code of the frame associated with cname,
The name of the frame with ID frcode.
:rtype: tuple
"""
lenout = ctypes.c_int(lenout)
frname = stypes.stringToCharP(lenout)
cname = stypes.stringToCharP(cname)
found = ctypes.c_int()
frcode = ctypes.c_int()
libspice.cnmfrm_c(cname, lenout, ctypes.byref(frcode), frname,
ctypes.byref(found))
return frcode.value, stypes.toPythonString(frname), bool(found.value) | [
"def",
"cnmfrm",
"(",
"cname",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"frname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"lenout",
")",
"cname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"cname",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"frcode",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"cnmfrm_c",
"(",
"cname",
",",
"lenout",
",",
"ctypes",
".",
"byref",
"(",
"frcode",
")",
",",
"frname",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"frcode",
".",
"value",
",",
"stypes",
".",
"toPythonString",
"(",
"frname",
")",
",",
"bool",
"(",
"found",
".",
"value",
")"
] | Retrieve frame ID code and name to associate with an object.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html
:param cname: Name of the object to find a frame for.
:type cname: int
:param lenout: Maximum length available for frame name.
:type lenout: int
:return:
The ID code of the frame associated with cname,
The name of the frame with ID frcode.
:rtype: tuple | [
"Retrieve",
"frame",
"ID",
"code",
"and",
"name",
"to",
"associate",
"with",
"an",
"object",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1440-L1462 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | convrt | def convrt(x, inunit, outunit):
"""
Take a measurement X, the units associated with
X, and units to which X should be converted; return Y
the value of the measurement in the output units.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/convrt_c.html
:param x: Number representing a measurement in some units.
:type x: float
:param inunit: The units in which x is measured.
:type inunit: str
:param outunit: Desired units for the measurement.
:type outunit: str
:return: The measurment in the desired units.
:rtype: float
"""
inunit = stypes.stringToCharP(inunit)
outunit = stypes.stringToCharP(outunit)
y = ctypes.c_double()
if hasattr(x, "__iter__"):
outArray=[]
for n in x:
libspice.convrt_c(n,inunit,outunit,ctypes.byref(y))
outArray.append(y.value)
return outArray
x = ctypes.c_double(x)
libspice.convrt_c(x, inunit, outunit, ctypes.byref(y))
return y.value | python | def convrt(x, inunit, outunit):
"""
Take a measurement X, the units associated with
X, and units to which X should be converted; return Y
the value of the measurement in the output units.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/convrt_c.html
:param x: Number representing a measurement in some units.
:type x: float
:param inunit: The units in which x is measured.
:type inunit: str
:param outunit: Desired units for the measurement.
:type outunit: str
:return: The measurment in the desired units.
:rtype: float
"""
inunit = stypes.stringToCharP(inunit)
outunit = stypes.stringToCharP(outunit)
y = ctypes.c_double()
if hasattr(x, "__iter__"):
outArray=[]
for n in x:
libspice.convrt_c(n,inunit,outunit,ctypes.byref(y))
outArray.append(y.value)
return outArray
x = ctypes.c_double(x)
libspice.convrt_c(x, inunit, outunit, ctypes.byref(y))
return y.value | [
"def",
"convrt",
"(",
"x",
",",
"inunit",
",",
"outunit",
")",
":",
"inunit",
"=",
"stypes",
".",
"stringToCharP",
"(",
"inunit",
")",
"outunit",
"=",
"stypes",
".",
"stringToCharP",
"(",
"outunit",
")",
"y",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"if",
"hasattr",
"(",
"x",
",",
"\"__iter__\"",
")",
":",
"outArray",
"=",
"[",
"]",
"for",
"n",
"in",
"x",
":",
"libspice",
".",
"convrt_c",
"(",
"n",
",",
"inunit",
",",
"outunit",
",",
"ctypes",
".",
"byref",
"(",
"y",
")",
")",
"outArray",
".",
"append",
"(",
"y",
".",
"value",
")",
"return",
"outArray",
"x",
"=",
"ctypes",
".",
"c_double",
"(",
"x",
")",
"libspice",
".",
"convrt_c",
"(",
"x",
",",
"inunit",
",",
"outunit",
",",
"ctypes",
".",
"byref",
"(",
"y",
")",
")",
"return",
"y",
".",
"value"
] | Take a measurement X, the units associated with
X, and units to which X should be converted; return Y
the value of the measurement in the output units.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/convrt_c.html
:param x: Number representing a measurement in some units.
:type x: float
:param inunit: The units in which x is measured.
:type inunit: str
:param outunit: Desired units for the measurement.
:type outunit: str
:return: The measurment in the desired units.
:rtype: float | [
"Take",
"a",
"measurement",
"X",
"the",
"units",
"associated",
"with",
"X",
"and",
"units",
"to",
"which",
"X",
"should",
"be",
"converted",
";",
"return",
"Y",
"the",
"value",
"of",
"the",
"measurement",
"in",
"the",
"output",
"units",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1489-L1519 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | copy | def copy(cell):
"""
Copy the contents of a SpiceCell of any data type to another
cell of the same type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html
:param cell: Cell to be copied.
:type cell: spiceypy.utils.support_types.SpiceCell
:return: New cell
:rtype: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
# Next line was redundant with [raise NotImpImplementedError] below
# assert cell.dtype == 0 or cell.dtype == 1 or cell.dtype == 2
if cell.dtype is 0:
newcopy = stypes.SPICECHAR_CELL(cell.size, cell.length)
elif cell.dtype is 1:
newcopy = stypes.SPICEDOUBLE_CELL(cell.size)
elif cell.dtype is 2:
newcopy = stypes.SPICEINT_CELL(cell.size)
else:
raise NotImplementedError
libspice.copy_c(ctypes.byref(cell), ctypes.byref(newcopy))
return newcopy | python | def copy(cell):
"""
Copy the contents of a SpiceCell of any data type to another
cell of the same type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html
:param cell: Cell to be copied.
:type cell: spiceypy.utils.support_types.SpiceCell
:return: New cell
:rtype: spiceypy.utils.support_types.SpiceCell
"""
assert isinstance(cell, stypes.SpiceCell)
# Next line was redundant with [raise NotImpImplementedError] below
# assert cell.dtype == 0 or cell.dtype == 1 or cell.dtype == 2
if cell.dtype is 0:
newcopy = stypes.SPICECHAR_CELL(cell.size, cell.length)
elif cell.dtype is 1:
newcopy = stypes.SPICEDOUBLE_CELL(cell.size)
elif cell.dtype is 2:
newcopy = stypes.SPICEINT_CELL(cell.size)
else:
raise NotImplementedError
libspice.copy_c(ctypes.byref(cell), ctypes.byref(newcopy))
return newcopy | [
"def",
"copy",
"(",
"cell",
")",
":",
"assert",
"isinstance",
"(",
"cell",
",",
"stypes",
".",
"SpiceCell",
")",
"# Next line was redundant with [raise NotImpImplementedError] below",
"# assert cell.dtype == 0 or cell.dtype == 1 or cell.dtype == 2",
"if",
"cell",
".",
"dtype",
"is",
"0",
":",
"newcopy",
"=",
"stypes",
".",
"SPICECHAR_CELL",
"(",
"cell",
".",
"size",
",",
"cell",
".",
"length",
")",
"elif",
"cell",
".",
"dtype",
"is",
"1",
":",
"newcopy",
"=",
"stypes",
".",
"SPICEDOUBLE_CELL",
"(",
"cell",
".",
"size",
")",
"elif",
"cell",
".",
"dtype",
"is",
"2",
":",
"newcopy",
"=",
"stypes",
".",
"SPICEINT_CELL",
"(",
"cell",
".",
"size",
")",
"else",
":",
"raise",
"NotImplementedError",
"libspice",
".",
"copy_c",
"(",
"ctypes",
".",
"byref",
"(",
"cell",
")",
",",
"ctypes",
".",
"byref",
"(",
"newcopy",
")",
")",
"return",
"newcopy"
] | Copy the contents of a SpiceCell of any data type to another
cell of the same type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html
:param cell: Cell to be copied.
:type cell: spiceypy.utils.support_types.SpiceCell
:return: New cell
:rtype: spiceypy.utils.support_types.SpiceCell | [
"Copy",
"the",
"contents",
"of",
"a",
"SpiceCell",
"of",
"any",
"data",
"type",
"to",
"another",
"cell",
"of",
"the",
"same",
"type",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1523-L1547 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cpos | def cpos(string, chars, start):
"""
Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching forward.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the first character of str at or
following index start that is in the collection chars.
:rtype: int
"""
string = stypes.stringToCharP(string)
chars = stypes.stringToCharP(chars)
start = ctypes.c_int(start)
return libspice.cpos_c(string, chars, start) | python | def cpos(string, chars, start):
"""
Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching forward.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the first character of str at or
following index start that is in the collection chars.
:rtype: int
"""
string = stypes.stringToCharP(string)
chars = stypes.stringToCharP(chars)
start = ctypes.c_int(start)
return libspice.cpos_c(string, chars, start) | [
"def",
"cpos",
"(",
"string",
",",
"chars",
",",
"start",
")",
":",
"string",
"=",
"stypes",
".",
"stringToCharP",
"(",
"string",
")",
"chars",
"=",
"stypes",
".",
"stringToCharP",
"(",
"chars",
")",
"start",
"=",
"ctypes",
".",
"c_int",
"(",
"start",
")",
"return",
"libspice",
".",
"cpos_c",
"(",
"string",
",",
"chars",
",",
"start",
")"
] | Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching forward.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the first character of str at or
following index start that is in the collection chars.
:rtype: int | [
"Find",
"the",
"first",
"occurrence",
"in",
"a",
"string",
"of",
"a",
"character",
"belonging",
"to",
"a",
"collection",
"of",
"characters",
"starting",
"at",
"a",
"specified",
"location",
"searching",
"forward",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1551-L1573 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cposr | def cposr(string, chars, start):
"""
Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching in reverse.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the last character of str at or
before index start that is in the collection chars.
:rtype: int
"""
string = stypes.stringToCharP(string)
chars = stypes.stringToCharP(chars)
start = ctypes.c_int(start)
return libspice.cposr_c(string, chars, start) | python | def cposr(string, chars, start):
"""
Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching in reverse.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the last character of str at or
before index start that is in the collection chars.
:rtype: int
"""
string = stypes.stringToCharP(string)
chars = stypes.stringToCharP(chars)
start = ctypes.c_int(start)
return libspice.cposr_c(string, chars, start) | [
"def",
"cposr",
"(",
"string",
",",
"chars",
",",
"start",
")",
":",
"string",
"=",
"stypes",
".",
"stringToCharP",
"(",
"string",
")",
"chars",
"=",
"stypes",
".",
"stringToCharP",
"(",
"chars",
")",
"start",
"=",
"ctypes",
".",
"c_int",
"(",
"start",
")",
"return",
"libspice",
".",
"cposr_c",
"(",
"string",
",",
"chars",
",",
"start",
")"
] | Find the first occurrence in a string of a character belonging
to a collection of characters, starting at a specified location,
searching in reverse.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html
:param string: Any character string.
:type string: str
:param chars: A collection of characters.
:type chars: str
:param start: Position to begin looking for one of chars.
:type start: int
:return:
The index of the last character of str at or
before index start that is in the collection chars.
:rtype: int | [
"Find",
"the",
"first",
"occurrence",
"in",
"a",
"string",
"of",
"a",
"character",
"belonging",
"to",
"a",
"collection",
"of",
"characters",
"starting",
"at",
"a",
"specified",
"location",
"searching",
"in",
"reverse",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1577-L1599 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cvpool | def cvpool(agent):
"""
Indicate whether or not any watched kernel variables that have a
specified agent on their notification list have been updated.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cvpool_c.html
:param agent: Name of the agent to check for notices.
:type agent: str
:return: True if variables for "agent" have been updated.
:rtype: bool
"""
agent = stypes.stringToCharP(agent)
update = ctypes.c_int()
libspice.cvpool_c(agent, ctypes.byref(update))
return bool(update.value) | python | def cvpool(agent):
"""
Indicate whether or not any watched kernel variables that have a
specified agent on their notification list have been updated.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cvpool_c.html
:param agent: Name of the agent to check for notices.
:type agent: str
:return: True if variables for "agent" have been updated.
:rtype: bool
"""
agent = stypes.stringToCharP(agent)
update = ctypes.c_int()
libspice.cvpool_c(agent, ctypes.byref(update))
return bool(update.value) | [
"def",
"cvpool",
"(",
"agent",
")",
":",
"agent",
"=",
"stypes",
".",
"stringToCharP",
"(",
"agent",
")",
"update",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"cvpool_c",
"(",
"agent",
",",
"ctypes",
".",
"byref",
"(",
"update",
")",
")",
"return",
"bool",
"(",
"update",
".",
"value",
")"
] | Indicate whether or not any watched kernel variables that have a
specified agent on their notification list have been updated.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cvpool_c.html
:param agent: Name of the agent to check for notices.
:type agent: str
:return: True if variables for "agent" have been updated.
:rtype: bool | [
"Indicate",
"whether",
"or",
"not",
"any",
"watched",
"kernel",
"variables",
"that",
"have",
"a",
"specified",
"agent",
"on",
"their",
"notification",
"list",
"have",
"been",
"updated",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1603-L1618 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cyllat | def cyllat(r, lonc, z):
"""
Convert from cylindrical to latitudinal coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cyllat_c.html
:param r: Distance of point from z axis.
:type r: float
:param lonc: Cylindrical angle of point from XZ plane(radians).
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return: Distance, Longitude (radians), and Latitude of point (radians).
:rtype: tuple
"""
r = ctypes.c_double(r)
lonc = ctypes.c_double(lonc)
z = ctypes.c_double(z)
radius = ctypes.c_double()
lon = ctypes.c_double()
lat = ctypes.c_double()
libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(lon),
ctypes.byref(lat))
return radius.value, lon.value, lat.value | python | def cyllat(r, lonc, z):
"""
Convert from cylindrical to latitudinal coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cyllat_c.html
:param r: Distance of point from z axis.
:type r: float
:param lonc: Cylindrical angle of point from XZ plane(radians).
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return: Distance, Longitude (radians), and Latitude of point (radians).
:rtype: tuple
"""
r = ctypes.c_double(r)
lonc = ctypes.c_double(lonc)
z = ctypes.c_double(z)
radius = ctypes.c_double()
lon = ctypes.c_double()
lat = ctypes.c_double()
libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(lon),
ctypes.byref(lat))
return radius.value, lon.value, lat.value | [
"def",
"cyllat",
"(",
"r",
",",
"lonc",
",",
"z",
")",
":",
"r",
"=",
"ctypes",
".",
"c_double",
"(",
"r",
")",
"lonc",
"=",
"ctypes",
".",
"c_double",
"(",
"lonc",
")",
"z",
"=",
"ctypes",
".",
"c_double",
"(",
"z",
")",
"radius",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"lon",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"lat",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"cyllat_c",
"(",
"r",
",",
"lonc",
",",
"z",
",",
"ctypes",
".",
"byref",
"(",
"radius",
")",
",",
"ctypes",
".",
"byref",
"(",
"lon",
")",
",",
"ctypes",
".",
"byref",
"(",
"lat",
")",
")",
"return",
"radius",
".",
"value",
",",
"lon",
".",
"value",
",",
"lat",
".",
"value"
] | Convert from cylindrical to latitudinal coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cyllat_c.html
:param r: Distance of point from z axis.
:type r: float
:param lonc: Cylindrical angle of point from XZ plane(radians).
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return: Distance, Longitude (radians), and Latitude of point (radians).
:rtype: tuple | [
"Convert",
"from",
"cylindrical",
"to",
"latitudinal",
"coordinates",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1622-L1645 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cylrec | def cylrec(r, lon, z):
"""
Convert from cylindrical to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html
:param r: Distance of a point from z axis.
:type r: float
:param lon: Angle (radians) of a point from xZ plane.
:type lon: float
:param z: Height of a point above xY plane.
:type z: float
:return: Rectangular coordinates of the point.
:rtype: 3-Element Array of floats
"""
r = ctypes.c_double(r)
lon = ctypes.c_double(lon)
z = ctypes.c_double(z)
rectan = stypes.emptyDoubleVector(3)
libspice.cylrec_c(r, lon, z, rectan)
return stypes.cVectorToPython(rectan) | python | def cylrec(r, lon, z):
"""
Convert from cylindrical to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html
:param r: Distance of a point from z axis.
:type r: float
:param lon: Angle (radians) of a point from xZ plane.
:type lon: float
:param z: Height of a point above xY plane.
:type z: float
:return: Rectangular coordinates of the point.
:rtype: 3-Element Array of floats
"""
r = ctypes.c_double(r)
lon = ctypes.c_double(lon)
z = ctypes.c_double(z)
rectan = stypes.emptyDoubleVector(3)
libspice.cylrec_c(r, lon, z, rectan)
return stypes.cVectorToPython(rectan) | [
"def",
"cylrec",
"(",
"r",
",",
"lon",
",",
"z",
")",
":",
"r",
"=",
"ctypes",
".",
"c_double",
"(",
"r",
")",
"lon",
"=",
"ctypes",
".",
"c_double",
"(",
"lon",
")",
"z",
"=",
"ctypes",
".",
"c_double",
"(",
"z",
")",
"rectan",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"3",
")",
"libspice",
".",
"cylrec_c",
"(",
"r",
",",
"lon",
",",
"z",
",",
"rectan",
")",
"return",
"stypes",
".",
"cVectorToPython",
"(",
"rectan",
")"
] | Convert from cylindrical to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html
:param r: Distance of a point from z axis.
:type r: float
:param lon: Angle (radians) of a point from xZ plane.
:type lon: float
:param z: Height of a point above xY plane.
:type z: float
:return: Rectangular coordinates of the point.
:rtype: 3-Element Array of floats | [
"Convert",
"from",
"cylindrical",
"to",
"rectangular",
"coordinates",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1649-L1669 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | cylsph | def cylsph(r, lonc, z):
"""
Convert from cylindrical to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylsph_c.html
:param r: Rectangular coordinates of the point.
:type r: float
:param lonc: Angle (radians) of point from XZ plane.
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return:
Distance of point from origin,
Polar angle (co-latitude in radians) of point,
Azimuthal angle (longitude) of point (radians).
:rtype: tuple
"""
r = ctypes.c_double(r)
lonc = ctypes.c_double(lonc)
z = ctypes.c_double(z)
radius = ctypes.c_double()
colat = ctypes.c_double()
lon = ctypes.c_double()
libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(colat),
ctypes.byref(lon))
return radius.value, colat.value, lon.value | python | def cylsph(r, lonc, z):
"""
Convert from cylindrical to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylsph_c.html
:param r: Rectangular coordinates of the point.
:type r: float
:param lonc: Angle (radians) of point from XZ plane.
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return:
Distance of point from origin,
Polar angle (co-latitude in radians) of point,
Azimuthal angle (longitude) of point (radians).
:rtype: tuple
"""
r = ctypes.c_double(r)
lonc = ctypes.c_double(lonc)
z = ctypes.c_double(z)
radius = ctypes.c_double()
colat = ctypes.c_double()
lon = ctypes.c_double()
libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(colat),
ctypes.byref(lon))
return radius.value, colat.value, lon.value | [
"def",
"cylsph",
"(",
"r",
",",
"lonc",
",",
"z",
")",
":",
"r",
"=",
"ctypes",
".",
"c_double",
"(",
"r",
")",
"lonc",
"=",
"ctypes",
".",
"c_double",
"(",
"lonc",
")",
"z",
"=",
"ctypes",
".",
"c_double",
"(",
"z",
")",
"radius",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"colat",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"lon",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"cyllat_c",
"(",
"r",
",",
"lonc",
",",
"z",
",",
"ctypes",
".",
"byref",
"(",
"radius",
")",
",",
"ctypes",
".",
"byref",
"(",
"colat",
")",
",",
"ctypes",
".",
"byref",
"(",
"lon",
")",
")",
"return",
"radius",
".",
"value",
",",
"colat",
".",
"value",
",",
"lon",
".",
"value"
] | Convert from cylindrical to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylsph_c.html
:param r: Rectangular coordinates of the point.
:type r: float
:param lonc: Angle (radians) of point from XZ plane.
:type lonc: float
:param z: Height of point above XY plane.
:type z: float
:return:
Distance of point from origin,
Polar angle (co-latitude in radians) of point,
Azimuthal angle (longitude) of point (radians).
:rtype: tuple | [
"Convert",
"from",
"cylindrical",
"to",
"spherical",
"coordinates",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1673-L1699 | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | dafac | def dafac(handle, buffer):
"""
Add comments from a buffer of character strings to the comment
area of a binary DAF file, appending them to any comments which
are already present in the file's comment area.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafac_c.html
:param handle: handle of a DAF opened with write access.
:type handle: int
:param buffer: Buffer of comments to put into the comment area.
:type buffer: list[str]
"""
handle = ctypes.c_int(handle)
lenvals = ctypes.c_int(len(max(buffer, key=len)) + 1)
n = ctypes.c_int(len(buffer))
buffer = stypes.listToCharArrayPtr(buffer)
libspice.dafac_c(handle, n, lenvals, buffer) | python | def dafac(handle, buffer):
"""
Add comments from a buffer of character strings to the comment
area of a binary DAF file, appending them to any comments which
are already present in the file's comment area.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafac_c.html
:param handle: handle of a DAF opened with write access.
:type handle: int
:param buffer: Buffer of comments to put into the comment area.
:type buffer: list[str]
"""
handle = ctypes.c_int(handle)
lenvals = ctypes.c_int(len(max(buffer, key=len)) + 1)
n = ctypes.c_int(len(buffer))
buffer = stypes.listToCharArrayPtr(buffer)
libspice.dafac_c(handle, n, lenvals, buffer) | [
"def",
"dafac",
"(",
"handle",
",",
"buffer",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"lenvals",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"max",
"(",
"buffer",
",",
"key",
"=",
"len",
")",
")",
"+",
"1",
")",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"buffer",
")",
")",
"buffer",
"=",
"stypes",
".",
"listToCharArrayPtr",
"(",
"buffer",
")",
"libspice",
".",
"dafac_c",
"(",
"handle",
",",
"n",
",",
"lenvals",
",",
"buffer",
")"
] | Add comments from a buffer of character strings to the comment
area of a binary DAF file, appending them to any comments which
are already present in the file's comment area.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafac_c.html
:param handle: handle of a DAF opened with write access.
:type handle: int
:param buffer: Buffer of comments to put into the comment area.
:type buffer: list[str] | [
"Add",
"comments",
"from",
"a",
"buffer",
"of",
"character",
"strings",
"to",
"the",
"comment",
"area",
"of",
"a",
"binary",
"DAF",
"file",
"appending",
"them",
"to",
"any",
"comments",
"which",
"are",
"already",
"present",
"in",
"the",
"file",
"s",
"comment",
"area",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1706-L1723 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.