_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q26900 | FCIFDHSIFileHandler.calc_area_extent | train | def calc_area_extent(self, key):
"""Calculate area extent for a dataset."""
# Calculate the area extent of the swath based on start line and column
# information, total number of segments and channel resolution
xyres = {500: 22272, 1000: 11136, 2000: 5568}
chkres = xyres[key.reso... | python | {
"resource": ""
} |
q26901 | FCIFDHSIFileHandler.calibrate | train | def calibrate(self, data, key):
"""Data calibration."""
# logger.debug('Calibration: %s' % key.calibration)
logger.warning('Calibration disabled!')
if key.calibration == 'brightness_temperature':
# self._ir_calibrate(data, key)
pass
| python | {
"resource": ""
} |
q26902 | FCIFDHSIFileHandler._ir_calibrate | train | def _ir_calibrate(self, data, key):
"""IR channel calibration."""
# Not sure if Lv is correct, FCI User Guide is a bit unclear
Lv = data.data * \
self.nc[
'/data/{}/measured/radiance_unit_conversion_coefficient'
.format(key.name)][...]
vc = s... | python | {
"resource": ""
} |
q26903 | FCIFDHSIFileHandler._vis_calibrate | train | def _vis_calibrate(self, data, key):
"""VIS channel calibration."""
# radiance to reflectance taken as in mipp/xrit/MSG.py
# again FCI User Guide is not clear on how to do this
sirr = self.nc[
'/data/{}/measured/channel_effective_solar_irradiance'
| python | {
"resource": ""
} |
q26904 | get_xritdecompress_cmd | train | def get_xritdecompress_cmd():
"""Find a valid binary for the xRITDecompress command."""
cmd = os.environ.get('XRIT_DECOMPRESS_PATH', None)
if not cmd:
raise IOError("XRIT_DECOMPRESS_PATH is not defined (complete path to | python | {
"resource": ""
} |
q26905 | get_xritdecompress_outfile | train | def get_xritdecompress_outfile(stdout):
"""Analyse the output of the xRITDecompress command call and return the file."""
outfile = b''
for line in stdout:
try:
k, v = [x.strip() for x in line.split(b':', 1)]
| python | {
"resource": ""
} |
q26906 | decompress | train | def decompress(infile, outdir='.'):
"""Decompress an XRIT data file and return the path to the decompressed file.
It expect to find Eumetsat's xRITDecompress through the environment variable
XRIT_DECOMPRESS_PATH.
"""
cmd = get_xritdecompress_cmd()
infile = os.path.abspath(infile)
cwd = os.g... | python | {
"resource": ""
} |
q26907 | HRITFileHandler._get_hd | train | def _get_hd(self, hdr_info):
"""Open the file, read and get the basic file header info and set the mda
dictionary
"""
hdr_map, variable_length_headers, text_headers = hdr_info
with open(self.filename) as fp:
total_header_length = 16
while fp.tell() < ... | python | {
"resource": ""
} |
q26908 | HRITFileHandler.get_xy_from_linecol | train | def get_xy_from_linecol(self, line, col, offsets, factors):
"""Get the intermediate coordinates from line & col.
Intermediate coordinates are actually the instruments scanning angles.
"""
loff, coff = offsets
lfac, | python | {
"resource": ""
} |
q26909 | _wl_dist | train | def _wl_dist(wl_a, wl_b):
"""Return the distance between two requested wavelengths."""
if isinstance(wl_a, tuple):
| python | {
"resource": ""
} |
q26910 | get_best_dataset_key | train | def get_best_dataset_key(key, choices):
"""Choose the "best" `DatasetID` from `choices` based on `key`.
The best key is chosen based on the follow criteria:
1. Central wavelength is nearest to the `key` wavelength if
specified.
2. Least modified dataset if `modifiers` is `None` in `... | python | {
"resource": ""
} |
q26911 | filter_keys_by_dataset_id | train | def filter_keys_by_dataset_id(did, key_container):
"""Filer provided key iterable by the provided `DatasetID`.
Note: The `modifiers` attribute of `did` should be `None` to allow for
**any** modifier in the results.
Args:
did (DatasetID): Query parameters to match in the `key_container`.
... | python | {
"resource": ""
} |
q26912 | get_key | train | def get_key(key, key_container, num_results=1, best=True,
resolution=None, calibration=None, polarization=None,
level=None, modifiers=None):
"""Get the fully-specified key best matching the provided key.
Only the best match is returned if `best` is `True` (default). See
`get_best_da... | python | {
"resource": ""
} |
q26913 | group_files | train | def group_files(files_to_sort, reader=None, time_threshold=10,
group_keys=None, ppp_config_dir=None, reader_kwargs=None):
"""Group series of files by file pattern information.
By default this will group files by their filename ``start_time``
assuming it exists in the pattern. By passing the... | python | {
"resource": ""
} |
q26914 | configs_for_reader | train | def configs_for_reader(reader=None, ppp_config_dir=None):
"""Generator of reader configuration files for one or more readers
Args:
reader (Optional[str]): Yield configs only for this reader
ppp_config_dir (Optional[str]): Additional configuration directory
to search for reader confi... | python | {
"resource": ""
} |
q26915 | available_readers | train | def available_readers(as_dict=False):
"""Available readers based on current configuration.
Args:
as_dict (bool): Optionally return reader information as a dictionary.
Default: False
Returns: List of available reader names. If `as_dict` is `True` then
a list of ... | python | {
"resource": ""
} |
q26916 | find_files_and_readers | train | def find_files_and_readers(start_time=None, end_time=None, base_dir=None,
reader=None, sensor=None, ppp_config_dir=None,
filter_parameters=None, reader_kwargs=None):
"""Find on-disk files matching the provided parameters.
Use `start_time` and/or `end_time` ... | python | {
"resource": ""
} |
q26917 | load_readers | train | def load_readers(filenames=None, reader=None, reader_kwargs=None,
ppp_config_dir=None):
"""Create specified readers and assign files to them.
Args:
filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object
... | python | {
"resource": ""
} |
q26918 | DatasetDict.get_key | train | def get_key(self, match_key, num_results=1, best=True, **dfilter):
"""Get multiple fully-specified keys that match the provided query.
Args:
key (DatasetID): DatasetID of query parameters to use for
searching. Any parameter that is `None`
... | python | {
"resource": ""
} |
q26919 | DatasetDict.get | train | def get(self, key, default=None):
"""Get value with optional default."""
try:
| python | {
"resource": ""
} |
q26920 | sub_arrays | train | def sub_arrays(proj1, proj2):
"""Substract two DataArrays and combine their attrs."""
attrs = combine_metadata(proj1.attrs, proj2.attrs)
if (attrs.get('area') is | python | {
"resource": ""
} |
q26921 | zero_missing_data | train | def zero_missing_data(data1, data2):
"""Replace NaN values with zeros in data1 if the data is valid in data2."""
nans | python | {
"resource": ""
} |
q26922 | CompositorLoader.load_sensor_composites | train | def load_sensor_composites(self, sensor_name):
"""Load all compositor configs for the provided sensor."""
config_filename = sensor_name + ".yaml"
LOG.debug("Looking for composites config file %s", config_filename)
composite_configs = config_search_paths(
os.path.join("composi... | python | {
"resource": ""
} |
q26923 | CompositorLoader.load_compositors | train | def load_compositors(self, sensor_names):
"""Load all compositor configs for the provided sensors.
Args:
sensor_names (list of strings): Sensor names that have matching
``sensor_name.yaml`` config files.
Returns:
(comps, mods)... | python | {
"resource": ""
} |
q26924 | NIRReflectance._init_refl3x | train | def _init_refl3x(self, projectables):
"""Initiate the 3.x reflectance derivations."""
if not Calculator:
LOG.info("Couldn't load pyspectral")
raise ImportError("No module named pyspectral.near_infrared_reflectance")
| python | {
"resource": ""
} |
q26925 | NIRReflectance._get_reflectance | train | def _get_reflectance(self, projectables, optional_datasets):
"""Calculate 3.x reflectance with pyspectral."""
_nir, _tb11 = projectables
LOG.info('Getting reflective part of %s', _nir.attrs['name'])
sun_zenith = None
tb13_4 = None
for dataset in optional_datasets:
... | python | {
"resource": ""
} |
q26926 | RatioSharpenedRGB._get_band | train | def _get_band(self, high_res, low_res, color, ratio):
"""Figure out what data should represent this color."""
if self.high_resolution_band == color:
ret = high_res
else:
| python | {
"resource": ""
} |
q26927 | prepare_resampler | train | def prepare_resampler(source_area, destination_area, resampler=None, **resample_kwargs):
"""Instantiate and return a resampler."""
if resampler is None:
LOG.info("Using default KDTree resampler")
resampler = 'kd_tree'
if isinstance(resampler, BaseResampler):
raise ValueError("Trying... | python | {
"resource": ""
} |
q26928 | resample | train | def resample(source_area, data, destination_area,
resampler=None, **kwargs):
"""Do the resampling."""
if 'resampler_class' in kwargs:
import warnings
warnings.warn("'resampler_class' is deprecated, use 'resampler'",
DeprecationWarning)
resampler = kwarg... | python | {
"resource": ""
} |
q26929 | BaseResampler.resample | train | def resample(self, data, cache_dir=None, mask_area=None, **kwargs):
"""Resample `data` by calling `precompute` and `compute` methods.
Only certain resampling classes may use `cache_dir` and the `mask`
provided when `mask_area` is True. The return value of calling the
`precompute` method... | python | {
"resource": ""
} |
q26930 | BaseResampler._create_cache_filename | train | def _create_cache_filename(self, cache_dir=None, **kwargs):
"""Create filename for the cached resampling parameters"""
cache_dir = cache_dir or '.'
| python | {
"resource": ""
} |
q26931 | KDTreeResampler.precompute | train | def precompute(self, mask=None, radius_of_influence=None, epsilon=0,
cache_dir=None, **kwargs):
"""Create a KDTree structure and store it for later use.
Note: The `mask` keyword should be provided if geolocation may be valid
where data points are invalid.
"""
... | python | {
"resource": ""
} |
q26932 | KDTreeResampler._apply_cached_indexes | train | def _apply_cached_indexes(self, cached_indexes, persist=False):
"""Reassign various resampler index attributes."""
# cacheable_dict = {}
for elt in ['valid_input_index', 'valid_output_index',
'index_array', 'distance_array']:
val = cached_indexes[elt]
... | python | {
"resource": ""
} |
q26933 | KDTreeResampler.load_neighbour_info | train | def load_neighbour_info(self, cache_dir, mask=None, **kwargs):
"""Read index arrays from either the in-memory or disk cache."""
mask_name = getattr(mask, 'name', None)
filename = self._create_cache_filename(cache_dir,
mask=mask_name, **kwargs)
... | python | {
"resource": ""
} |
q26934 | KDTreeResampler.save_neighbour_info | train | def save_neighbour_info(self, cache_dir, mask=None, **kwargs):
"""Cache resampler's index arrays if there is a cache dir."""
if cache_dir:
mask_name = getattr(mask, 'name', None)
filename = self._create_cache_filename(
| python | {
"resource": ""
} |
q26935 | EWAResampler.resample | train | def resample(self, *args, **kwargs):
"""Run precompute and compute methods.
.. note::
This sets the default of 'mask_area' to False since it is
not needed in EWA resampling currently.
"""
| python | {
"resource": ""
} |
q26936 | EWAResampler._call_ll2cr | train | def _call_ll2cr(self, lons, lats, target_geo_def, swath_usage=0):
"""Wrapper around ll2cr for handling dask delayed calls better."""
new_src = SwathDefinition(lons, lats)
swath_points_in_grid, cols, rows = ll2cr(new_src, target_geo_def)
# FIXME: How do we check swath usage/coverage if w... | python | {
"resource": ""
} |
q26937 | EWAResampler.precompute | train | def precompute(self, cache_dir=None, swath_usage=0, **kwargs):
"""Generate row and column arrays and store it for later use."""
if kwargs.get('mask') is not None:
LOG.warning("'mask' parameter has no affect during EWA "
"resampling")
del kwargs
source... | python | {
"resource": ""
} |
q26938 | EWAResampler._call_fornav | train | def _call_fornav(self, cols, rows, target_geo_def, data,
grid_coverage=0, **kwargs):
"""Wrapper to run fornav as a dask delayed."""
num_valid_points, res = fornav(cols, rows, target_geo_def,
data, **kwargs)
if isinstance(data, tuple):
... | python | {
"resource": ""
} |
q26939 | BilinearResampler.precompute | train | def precompute(self, mask=None, radius_of_influence=50000, epsilon=0,
reduce_data=True, nprocs=1,
cache_dir=False, **kwargs):
"""Create bilinear coefficients and store them for later use.
Note: The `mask` keyword should be provided if geolocation may be valid
... | python | {
"resource": ""
} |
q26940 | BilinearResampler.compute | train | def compute(self, data, fill_value=None, **kwargs):
"""Resample the given data using bilinear interpolation"""
del kwargs
if fill_value is None:
fill_value = data.attrs.get('_FillValue')
target_shape = self.target_geo_def.shape
res = self.resampler.get_sample_from_b... | python | {
"resource": ""
} |
q26941 | AttributeHelper.apply_attributes | train | def apply_attributes(self, nc, table, prefix=''):
"""
apply fixed attributes, or look up attributes needed and apply them
"""
for name, value in sorted(table.items()):
if name in nc.ncattrs():
LOG.debug('already have a value for %s' % name)
con... | python | {
"resource": ""
} |
q26942 | NetCDFWriter.set_projection_attrs | train | def set_projection_attrs(self, area_id, proj4_info):
"""Assign projection attributes per GRB standard"""
proj4_info['a'], proj4_info['b'] = proj4_radius_parameters(proj4_info)
if proj4_info["proj"] == "geos":
p = self.projection = self.nc.createVariable("fixedgrid_projection", 'i4')
... | python | {
"resource": ""
} |
q26943 | SCMIWriter.enhancer | train | def enhancer(self):
"""Lazy loading of enhancements only if needed."""
if self._enhancer is None:
self._enhancer = | python | {
"resource": ""
} |
q26944 | SCMIWriter._group_by_area | train | def _group_by_area(self, datasets):
"""Group datasets by their area."""
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for | python | {
"resource": ""
} |
q26945 | _config_data_files | train | def _config_data_files(base_dirs, extensions=(".cfg", )):
"""Find all subdirectory configuration files.
Searches each base directory relative to this setup.py file and finds
all files ending in the extensions provided.
:param base_dirs: iterable of relative base directories to search
:param extens... | python | {
"resource": ""
} |
q26946 | from_sds | train | def from_sds(var, *args, **kwargs):
"""Create a dask array from a SD dataset."""
var.__dict__['dtype'] = HTYPE_TO_DTYPE[var.info()[3]]
| python | {
"resource": ""
} |
q26947 | HDF4FileHandler._open_xarray_dataset | train | def _open_xarray_dataset(self, val, chunks=CHUNK_SIZE):
"""Read the band in blocks."""
dask_arr = from_sds(val, chunks=chunks)
attrs = val.attributes()
| python | {
"resource": ""
} |
q26948 | overlay | train | def overlay(top, bottom, maxval=None):
"""Blending two layers.
from: https://docs.gimp.org/en/gimp-concepts-layer-modes.html
"""
if maxval is None:
| python | {
"resource": ""
} |
q26949 | read_writer_config | train | def read_writer_config(config_files, loader=UnsafeLoader):
"""Read the writer `config_files` and return the info extracted."""
conf = {}
LOG.debug('Reading %s', str(config_files))
for config_file in config_files:
with open(config_file) as fd:
conf.update(yaml.load(fd.read(), Loader=... | python | {
"resource": ""
} |
q26950 | load_writer_configs | train | def load_writer_configs(writer_configs, ppp_config_dir,
**writer_kwargs):
"""Load the writer from the provided `writer_configs`."""
try:
writer_info = read_writer_config(writer_configs)
writer_class = writer_info['writer']
except (ValueError, KeyError, yaml.YAMLError)... | python | {
"resource": ""
} |
q26951 | load_writer | train | def load_writer(writer, ppp_config_dir=None, **writer_kwargs):
"""Find and load writer `writer` in the available configuration files."""
if ppp_config_dir is None:
ppp_config_dir = get_environ_config_dir()
config_fn = writer + ".yaml" if "." not in writer else writer
config_files = config_searc... | python | {
"resource": ""
} |
q26952 | configs_for_writer | train | def configs_for_writer(writer=None, ppp_config_dir=None):
"""Generator of writer configuration files for one or more writers
Args:
writer (Optional[str]): Yield configs only for this writer
ppp_config_dir (Optional[str]): Additional configuration directory
to search for writer confi... | python | {
"resource": ""
} |
q26953 | available_writers | train | def available_writers(as_dict=False):
"""Available writers based on current configuration.
Args:
as_dict (bool): Optionally return writer information as a dictionary.
Default: False
Returns: List of available writer names. If `as_dict` is `True` then
a list of ... | python | {
"resource": ""
} |
q26954 | add_text | train | def add_text(orig, dc, img, text=None):
"""Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info.
"""
LOG.info("Add text to image.")
dc.add_text(**text)
arr = da.from_arra... | python | {
"resource": ""
} |
q26955 | show | train | def show(dataset, **kwargs):
"""Display the dataset as an image.
"""
| python | {
"resource": ""
} |
q26956 | compute_writer_results | train | def compute_writer_results(results):
"""Compute all the given dask graphs `results` so that the files are
saved.
Args:
results (iterable): Iterable of dask graphs resulting from calls to
`scn.save_datasets(..., compute=False)`
"""
if not results:
return
... | python | {
"resource": ""
} |
q26957 | Writer.separate_init_kwargs | train | def separate_init_kwargs(cls, kwargs):
"""Helper class method to separate arguments between init and save methods.
Currently the :class:`~satpy.scene.Scene` is passed one set of
arguments to represent the Writer creation and saving steps. This is
not preferred for Writer structure, but ... | python | {
"resource": ""
} |
q26958 | Writer.get_filename | train | def get_filename(self, **kwargs):
"""Create a filename where output data will be saved.
Args:
kwargs (dict): Attributes and other metadata to use for formatting
the previously provided `filename`.
"""
if self.filename_parser is None:
raise Runtim... | python | {
"resource": ""
} |
q26959 | LIFileHandler.get_area_def | train | def get_area_def(self, key, info=None):
"""Create AreaDefinition for specified product.
Projection information are hard coded for 0 degree geos projection
Test dataset doesn't provide the values in the file container.
Only fill values are inserted.
"""
# TODO Get projec... | python | {
"resource": ""
} |
q26960 | AbstractYAMLReader.get_dataset_key | train | def get_dataset_key(self, key, **kwargs):
"""Get the fully qualified `DatasetID` matching `key`. | python | {
"resource": ""
} |
q26961 | AbstractYAMLReader.load_ds_ids_from_config | train | def load_ds_ids_from_config(self):
"""Get the dataset ids from the config."""
ids = []
for dataset in self.datasets.values():
# xarray doesn't like concatenating attributes that are lists
# https://github.com/pydata/xarray/issues/2060
if 'coordinates' in datas... | python | {
"resource": ""
} |
q26962 | FileYAMLReader.check_file_covers_area | train | def check_file_covers_area(file_handler, check_area):
"""Checks if the file covers the current area.
If the file doesn't provide any bounding box information or 'area'
was not provided in `filter_parameters`, the check returns True.
"""
try:
gbb = Boundary(*file_hand... | python | {
"resource": ""
} |
q26963 | FileYAMLReader.find_required_filehandlers | train | def find_required_filehandlers(self, requirements, filename_info):
"""Find the necessary file handlers for the given requirements.
We assume here requirements are available.
Raises:
KeyError, if no handler for the given requirements is available.
RuntimeError, if there ... | python | {
"resource": ""
} |
q26964 | FileYAMLReader.sorted_filetype_items | train | def sorted_filetype_items(self):
"""Sort the instance's filetypes in using order."""
processed_types = []
file_type_items = deque(self.config['file_types'].items())
while len(file_type_items):
filetype, filetype_info = file_type_items.popleft()
requirements = fil... | python | {
"resource": ""
} |
q26965 | FileYAMLReader.new_filehandler_instances | train | def new_filehandler_instances(self, filetype_info, filename_items, fh_kwargs=None):
"""Generate new filehandler instances."""
requirements = filetype_info.get('requires')
filetype_cls = filetype_info['file_reader']
if fh_kwargs is None:
fh_kwargs = {}
for filename, ... | python | {
"resource": ""
} |
q26966 | FileYAMLReader.filter_fh_by_metadata | train | def filter_fh_by_metadata(self, filehandlers):
"""Filter out filehandlers using provide filter parameters."""
for filehandler in filehandlers:
filehandler.metadata['start_time'] = filehandler.start_time
| python | {
"resource": ""
} |
q26967 | FileYAMLReader.new_filehandlers_for_filetype | train | def new_filehandlers_for_filetype(self, filetype_info, filenames, fh_kwargs=None):
"""Create filehandlers for a given filetype."""
filename_iter = self.filename_items_for_filetype(filenames,
filetype_info)
if self.filter_filenames:
... | python | {
"resource": ""
} |
q26968 | FileYAMLReader.create_filehandlers | train | def create_filehandlers(self, filenames, fh_kwargs=None):
"""Organize the filenames into file types and create file handlers."""
filenames = list(OrderedDict.fromkeys(filenames))
logger.debug("Assigning to %s: %s", self.info['name'], filenames)
self.info.setdefault('filenames', []).exte... | python | {
"resource": ""
} |
q26969 | FileYAMLReader.update_ds_ids_from_file_handlers | train | def update_ds_ids_from_file_handlers(self):
"""Update DatasetIDs with information from loaded files.
This is useful, for example, if dataset resolution may change
depending on what files were loaded.
"""
for file_handlers in self.file_handlers.values():
fh = file_ha... | python | {
"resource": ""
} |
q26970 | FileYAMLReader.add_ds_ids_from_files | train | def add_ds_ids_from_files(self):
"""Check files for more dynamically discovered datasets."""
for file_handlers in self.file_handlers.values():
try:
fh = file_handlers[0]
avail_ids = fh.available_datasets()
except NotImplementedError:
... | python | {
"resource": ""
} |
q26971 | FileYAMLReader._load_dataset | train | def _load_dataset(dsid, ds_info, file_handlers, dim='y'):
"""Load only a piece of the dataset."""
slice_list = []
failure = True
for fh in file_handlers:
try:
projectable = fh.get_dataset(dsid, ds_info)
if projectable is not None:
... | python | {
"resource": ""
} |
q26972 | FileYAMLReader._get_coordinates_for_dataset_keys | train | def _get_coordinates_for_dataset_keys(self, dsids):
"""Get all coordinates."""
coordinates = {}
for dsid in dsids:
| python | {
"resource": ""
} |
q26973 | FileYAMLReader._load_ancillary_variables | train | def _load_ancillary_variables(self, datasets):
"""Load the ancillary variables of `datasets`."""
all_av_ids = set()
for dataset in datasets.values():
ancillary_variables = dataset.attrs.get('ancillary_variables', [])
if not isinstance(ancillary_variables, (list, tuple, se... | python | {
"resource": ""
} |
q26974 | FileYAMLReader.load | train | def load(self, dataset_keys, previous_datasets=None):
"""Load `dataset_keys`.
If `previous_datasets` is provided, do not reload those."""
all_datasets = previous_datasets or DatasetDict()
datasets = DatasetDict()
# Include coordinates in the list of datasets to load
dsi... | python | {
"resource": ""
} |
q26975 | calibrate_counts | train | def calibrate_counts(array, attributes, index):
"""Calibration for counts channels."""
offset = np.float32(attributes["corrected_counts_offsets"][index])
| python | {
"resource": ""
} |
q26976 | calibrate_radiance | train | def calibrate_radiance(array, attributes, index):
"""Calibration for radiance channels."""
offset = np.float32(attributes["radiance_offsets"][index])
| python | {
"resource": ""
} |
q26977 | calibrate_refl | train | def calibrate_refl(array, attributes, index):
"""Calibration for reflective channels."""
offset = np.float32(attributes["reflectance_offsets"][index])
scale = np.float32(attributes["reflectance_scales"][index])
| python | {
"resource": ""
} |
q26978 | calibrate_bt | train | def calibrate_bt(array, attributes, index, band_name):
"""Calibration for the emissive channels."""
offset = np.float32(attributes["radiance_offsets"][index])
scale = np.float32(attributes["radiance_scales"][index])
array = (array - offset) * scale
# Planck constant (Joule second)
h__ = np.flo... | python | {
"resource": ""
} |
q26979 | HDFEOSGeoReader.load | train | def load(self, file_key):
"""Load the data."""
var = self.sd.select(file_key)
data = xr.DataArray(from_sds(var, chunks=CHUNK_SIZE),
dims=['y', 'x']).astype(np.float32)
data = data.where(data != var._FillValue) | python | {
"resource": ""
} |
q26980 | read_geo | train | def read_geo(fid, key):
"""Read geolocation and related datasets."""
dsid = GEO_NAMES[key.name]
add_epoch = False
if "time" in key.name:
days = fid["/L1C/" + dsid["day"]].value
msecs = fid["/L1C/" + dsid["msec"]].value
data = _form_datetimes(days, msecs)
add_epoch = True
... | python | {
"resource": ""
} |
q26981 | _form_datetimes | train | def _form_datetimes(days, msecs):
"""Calculate seconds since EPOCH from days and milliseconds for each of IASI scan."""
all_datetimes = []
for i in range(days.size):
day = int(days[i])
msec = msecs[i]
scanline_datetimes = []
for j in range(int(VALUES_PER_SCAN_LINE / 4)):
... | python | {
"resource": ""
} |
q26982 | runtime_import | train | def runtime_import(object_path):
"""Import at runtime."""
obj_module, obj_element = object_path.rsplit(".", | python | {
"resource": ""
} |
q26983 | get_config | train | def get_config(filename, *search_dirs, **kwargs):
"""Blends the different configs, from package defaults to ."""
config = kwargs.get("config_reader_class", configparser.ConfigParser)()
paths = config_search_paths(filename, *search_dirs)
successes = config.read(reversed(paths))
if successes:
| python | {
"resource": ""
} |
q26984 | glob_config | train | def glob_config(pattern, *search_dirs):
"""Return glob results for all possible configuration locations.
Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory.
This is done for performance since this is usually used to find *all* configs for a cert... | python | {
"resource": ""
} |
q26985 | _check_import | train | def _check_import(module_names):
"""Import the specified modules and provide status."""
diagnostics = {}
for module_name in module_names:
try:
__import__(module_name)
res = | python | {
"resource": ""
} |
q26986 | check_satpy | train | def check_satpy(readers=None, writers=None, extras=None):
"""Check the satpy readers and writers for correct installation.
Args:
readers (list or None): Limit readers checked to those specified
writers (list or None): Limit writers checked to those specified
extras (list or None): Limit... | python | {
"resource": ""
} |
q26987 | ensure_dir | train | def ensure_dir(filename):
"""Checks if the dir of f exists, otherwise create it."""
directory = os.path.dirname(filename)
| python | {
"resource": ""
} |
q26988 | logging_on | train | def logging_on(level=logging.WARNING):
"""Turn logging on.
"""
global _is_logging_on
if not _is_logging_on:
console = logging.StreamHandler()
console.setFormatter(logging.Formatter("[%(levelname)s: %(asctime)s :"
" %(name)s] %(message)s",
... | python | {
"resource": ""
} |
q26989 | get_logger | train | def get_logger(name):
"""Return logger with null handler added if needed."""
if not hasattr(logging.Logger, 'trace'):
logging.addLevelName(TRACE_LEVEL, 'TRACE')
def trace(self, message, *args, **kwargs):
if self.isEnabledFor(TRACE_LEVEL):
# Yes, logger takes its '*ar... | python | {
"resource": ""
} |
q26990 | lonlat2xyz | train | def lonlat2xyz(lon, lat):
"""Convert lon lat to cartesian."""
lat = xu.deg2rad(lat)
lon = xu.deg2rad(lon)
x = xu.cos(lat) * xu.cos(lon)
| python | {
"resource": ""
} |
q26991 | xyz2lonlat | train | def xyz2lonlat(x, y, z):
"""Convert cartesian to lon lat."""
lon = xu.rad2deg(xu.arctan2(y, x))
lat = | python | {
"resource": ""
} |
q26992 | angle2xyz | train | def angle2xyz(azi, zen):
"""Convert azimuth and zenith to cartesian."""
azi = xu.deg2rad(azi)
zen = xu.deg2rad(zen)
x = xu.sin(zen) * xu.sin(azi)
| python | {
"resource": ""
} |
q26993 | xyz2angle | train | def xyz2angle(x, y, z):
"""Convert cartesian to azimuth and zenith."""
azi = xu.rad2deg(xu.arctan2(x, y))
zen | python | {
"resource": ""
} |
q26994 | proj_units_to_meters | train | def proj_units_to_meters(proj_str):
"""Convert projection units from kilometers to meters."""
proj_parts = proj_str.split()
new_parts = []
for itm in proj_parts:
key, val = itm.split('=')
key = key.strip('+')
if key in ['a', 'b', 'h']:
val = float(val)
if ... | python | {
"resource": ""
} |
q26995 | sunzen_corr_cos | train | def sunzen_corr_cos(data, cos_zen, limit=88., max_sza=95.):
"""Perform Sun zenith angle correction.
The correction is based on the provided cosine of the zenith
angle (``cos_zen``). The correction is limited
to ``limit`` degrees (default: 88.0 degrees). For larger zenith
angles, the correction is... | python | {
"resource": ""
} |
q26996 | OrderedConfigParser.read | train | def read(self, filename):
"""Reads config file
"""
try:
conf_file = open(filename, 'r')
config = conf_file.read()
config_keys = re.findall(r'\[.*\]', config)
self.section_keys = [key[1:-1] for key in config_keys]
except IOError as e:
| python | {
"resource": ""
} |
q26997 | SCMIFileHandler._get_sensor | train | def _get_sensor(self):
"""Determine the sensor for this file."""
# sometimes Himawari-8 (or 9) data is stored in SCMI format
is_h8 = 'H8' in self.platform_name
| python | {
"resource": ""
} |
q26998 | SCMIFileHandler._get_cf_grid_mapping_var | train | def _get_cf_grid_mapping_var(self):
"""Figure out which grid mapping should be used"""
gmaps = ['fixedgrid_projection', 'goes_imager_projection',
'lambert_projection', 'polar_projection',
'mercator_projection']
if 'grid_mapping' in self.filename_info:
... | python | {
"resource": ""
} |
q26999 | SCMIFileHandler._get_proj4_name | train | def _get_proj4_name(self, projection):
"""Map CF projection name to PROJ.4 name."""
gmap_name = projection.attrs['grid_mapping_name']
proj = {
'geostationary': 'geos',
'lambert_conformal_conic': 'lcc', | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.