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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | RadTbConverter._getsatname | def _getsatname(self):
"""
Get the satellite name used in the rsr-reader, from the platform
and number
"""
if self.platform_name.startswith("Meteosat"):
return self.platform_name
else:
raise NotImplementedError(
'Platform {0} not yet supported...'.format(self.platform_name)) | python | def _getsatname(self):
"""
Get the satellite name used in the rsr-reader, from the platform
and number
"""
if self.platform_name.startswith("Meteosat"):
return self.platform_name
else:
raise NotImplementedError(
'Platform {0} not yet supported...'.format(self.platform_name)) | [
"def",
"_getsatname",
"(",
"self",
")",
":",
"if",
"self",
".",
"platform_name",
".",
"startswith",
"(",
"\"Meteosat\"",
")",
":",
"return",
"self",
".",
"platform_name",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Platform {0} not yet supported...'",
".",... | Get the satellite name used in the rsr-reader, from the platform
and number | [
"Get",
"the",
"satellite",
"name",
"used",
"in",
"the",
"rsr",
"-",
"reader",
"from",
"the",
"platform",
"and",
"number"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L160-L170 | train | 29,200 |
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | RadTbConverter.make_tb2rad_lut | def make_tb2rad_lut(self, filepath, normalized=True):
"""Generate a Tb to radiance look-up table"""
tb_ = np.arange(TB_MIN, TB_MAX, self.tb_resolution)
retv = self.tb2radiance(tb_, normalized=normalized)
rad = retv['radiance']
np.savez(filepath, tb=tb_, radiance=rad) | python | def make_tb2rad_lut(self, filepath, normalized=True):
"""Generate a Tb to radiance look-up table"""
tb_ = np.arange(TB_MIN, TB_MAX, self.tb_resolution)
retv = self.tb2radiance(tb_, normalized=normalized)
rad = retv['radiance']
np.savez(filepath, tb=tb_, radiance=rad) | [
"def",
"make_tb2rad_lut",
"(",
"self",
",",
"filepath",
",",
"normalized",
"=",
"True",
")",
":",
"tb_",
"=",
"np",
".",
"arange",
"(",
"TB_MIN",
",",
"TB_MAX",
",",
"self",
".",
"tb_resolution",
")",
"retv",
"=",
"self",
".",
"tb2radiance",
"(",
"tb_"... | Generate a Tb to radiance look-up table | [
"Generate",
"a",
"Tb",
"to",
"radiance",
"look",
"-",
"up",
"table"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L226-L231 | train | 29,201 |
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | RadTbConverter.radiance2tb | def radiance2tb(self, rad):
"""
Get the Tb from the radiance using the Planck function and the central wavelength of the band
rad:
Radiance in SI units
"""
return radiance2tb(rad, self.rsr[self.bandname][self.detector]['central_wavelength'] * 1e-6) | python | def radiance2tb(self, rad):
"""
Get the Tb from the radiance using the Planck function and the central wavelength of the band
rad:
Radiance in SI units
"""
return radiance2tb(rad, self.rsr[self.bandname][self.detector]['central_wavelength'] * 1e-6) | [
"def",
"radiance2tb",
"(",
"self",
",",
"rad",
")",
":",
"return",
"radiance2tb",
"(",
"rad",
",",
"self",
".",
"rsr",
"[",
"self",
".",
"bandname",
"]",
"[",
"self",
".",
"detector",
"]",
"[",
"'central_wavelength'",
"]",
"*",
"1e-6",
")"
] | Get the Tb from the radiance using the Planck function and the central wavelength of the band
rad:
Radiance in SI units | [
"Get",
"the",
"Tb",
"from",
"the",
"radiance",
"using",
"the",
"Planck",
"function",
"and",
"the",
"central",
"wavelength",
"of",
"the",
"band"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L239-L246 | train | 29,202 |
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | SeviriRadTbConverter.radiance2tb | def radiance2tb(self, rad):
"""Get the Tb from the radiance using the simple non-linear regression
method.
rad: Radiance in units = 'mW/m^2 sr^-1 (cm^-1)^-1'
"""
#
# Tb = C2 * νc/{α * log[C1*νc**3 / L + 1]} - β/α
#
# C1 = 2 * h * c**2 and C2 = hc/k
#
c_1 = 2 * H_PLANCK * C_SPEED ** 2
c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN
vc_ = SEVIRI[self.bandname][self.platform_name][0]
# Multiply by 100 to get SI units!
vc_ *= 100.0
alpha = SEVIRI[self.bandname][self.platform_name][1]
beta = SEVIRI[self.bandname][self.platform_name][2]
tb_ = c_2 * vc_ / \
(alpha * np.log(c_1 * vc_ ** 3 / rad + 1)) - beta / alpha
return tb_ | python | def radiance2tb(self, rad):
"""Get the Tb from the radiance using the simple non-linear regression
method.
rad: Radiance in units = 'mW/m^2 sr^-1 (cm^-1)^-1'
"""
#
# Tb = C2 * νc/{α * log[C1*νc**3 / L + 1]} - β/α
#
# C1 = 2 * h * c**2 and C2 = hc/k
#
c_1 = 2 * H_PLANCK * C_SPEED ** 2
c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN
vc_ = SEVIRI[self.bandname][self.platform_name][0]
# Multiply by 100 to get SI units!
vc_ *= 100.0
alpha = SEVIRI[self.bandname][self.platform_name][1]
beta = SEVIRI[self.bandname][self.platform_name][2]
tb_ = c_2 * vc_ / \
(alpha * np.log(c_1 * vc_ ** 3 / rad + 1)) - beta / alpha
return tb_ | [
"def",
"radiance2tb",
"(",
"self",
",",
"rad",
")",
":",
"#",
"# Tb = C2 * νc/{α * log[C1*νc**3 / L + 1]} - β/α",
"#",
"# C1 = 2 * h * c**2 and C2 = hc/k",
"#",
"c_1",
"=",
"2",
"*",
"H_PLANCK",
"*",
"C_SPEED",
"**",
"2",
"c_2",
"=",
"H_PLANCK",
"*",
"C_SPEED",
... | Get the Tb from the radiance using the simple non-linear regression
method.
rad: Radiance in units = 'mW/m^2 sr^-1 (cm^-1)^-1' | [
"Get",
"the",
"Tb",
"from",
"the",
"radiance",
"using",
"the",
"simple",
"non",
"-",
"linear",
"regression",
"method",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L289-L313 | train | 29,203 |
pytroll/pyspectral | pyspectral/radiance_tb_conversion.py | SeviriRadTbConverter.tb2radiance | def tb2radiance(self, tb_, **kwargs):
"""Get the radiance from the Tb using the simple non-linear regression
method. SI units of course!
"""
# L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1)
#
# C1 = 2 * h * c**2 and C2 = hc/k
#
lut = kwargs.get('lut', None)
normalized = kwargs.get('normalized', True)
if lut is not None:
raise NotImplementedError('Using a tb-radiance LUT is not yet supported')
if not normalized:
raise NotImplementedError('Deriving the band integrated radiance is not supported')
c_1 = 2 * H_PLANCK * C_SPEED ** 2
c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN
vc_ = SEVIRI[self.bandname][self.platform_name][0]
# Multiply by 100 to get SI units!
vc_ *= 100.0
alpha = SEVIRI[self.bandname][self.platform_name][1]
beta = SEVIRI[self.bandname][self.platform_name][2]
radiance = c_1 * vc_ ** 3 / \
(np.exp(c_2 * vc_ / (alpha * tb_ + beta)) - 1)
unit = 'W/m^2 sr^-1 (m^-1)^-1'
scale = 1.0
return {'radiance': radiance,
'unit': unit,
'scale': scale} | python | def tb2radiance(self, tb_, **kwargs):
"""Get the radiance from the Tb using the simple non-linear regression
method. SI units of course!
"""
# L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1)
#
# C1 = 2 * h * c**2 and C2 = hc/k
#
lut = kwargs.get('lut', None)
normalized = kwargs.get('normalized', True)
if lut is not None:
raise NotImplementedError('Using a tb-radiance LUT is not yet supported')
if not normalized:
raise NotImplementedError('Deriving the band integrated radiance is not supported')
c_1 = 2 * H_PLANCK * C_SPEED ** 2
c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN
vc_ = SEVIRI[self.bandname][self.platform_name][0]
# Multiply by 100 to get SI units!
vc_ *= 100.0
alpha = SEVIRI[self.bandname][self.platform_name][1]
beta = SEVIRI[self.bandname][self.platform_name][2]
radiance = c_1 * vc_ ** 3 / \
(np.exp(c_2 * vc_ / (alpha * tb_ + beta)) - 1)
unit = 'W/m^2 sr^-1 (m^-1)^-1'
scale = 1.0
return {'radiance': radiance,
'unit': unit,
'scale': scale} | [
"def",
"tb2radiance",
"(",
"self",
",",
"tb_",
",",
"*",
"*",
"kwargs",
")",
":",
"# L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1)",
"#",
"# C1 = 2 * h * c**2 and C2 = hc/k",
"#",
"lut",
"=",
"kwargs",
".",
"get",
"(",
"'lut'",
",",
"None",
")",
"normalized",
"... | Get the radiance from the Tb using the simple non-linear regression
method. SI units of course! | [
"Get",
"the",
"radiance",
"from",
"the",
"Tb",
"using",
"the",
"simple",
"non",
"-",
"linear",
"regression",
"method",
".",
"SI",
"units",
"of",
"course!"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/radiance_tb_conversion.py#L315-L347 | train | 29,204 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse._get_rsr_data_version | def _get_rsr_data_version(self):
"""Check the version of the RSR data from the version file in the RSR
directory
"""
rsr_data_version_path = os.path.join(self.rsr_dir, RSR_DATA_VERSION_FILENAME)
if not os.path.exists(rsr_data_version_path):
return "v0.0.0"
with open(rsr_data_version_path, 'r') as fpt:
# Get the version from the file
return fpt.readline().strip() | python | def _get_rsr_data_version(self):
"""Check the version of the RSR data from the version file in the RSR
directory
"""
rsr_data_version_path = os.path.join(self.rsr_dir, RSR_DATA_VERSION_FILENAME)
if not os.path.exists(rsr_data_version_path):
return "v0.0.0"
with open(rsr_data_version_path, 'r') as fpt:
# Get the version from the file
return fpt.readline().strip() | [
"def",
"_get_rsr_data_version",
"(",
"self",
")",
":",
"rsr_data_version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"rsr_dir",
",",
"RSR_DATA_VERSION_FILENAME",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rsr_data_version_path"... | Check the version of the RSR data from the version file in the RSR
directory | [
"Check",
"the",
"version",
"of",
"the",
"RSR",
"data",
"from",
"the",
"version",
"file",
"in",
"the",
"RSR",
"directory"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L98-L110 | train | 29,205 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse._check_instrument | def _check_instrument(self):
"""Check and try fix instrument name if needed"""
instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower())
if instr != self.instrument.lower():
self.instrument = instr
LOG.warning("Inconsistent instrument/satellite input - " +
"instrument set to %s", self.instrument)
self.instrument = self.instrument.lower().replace('/', '') | python | def _check_instrument(self):
"""Check and try fix instrument name if needed"""
instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower())
if instr != self.instrument.lower():
self.instrument = instr
LOG.warning("Inconsistent instrument/satellite input - " +
"instrument set to %s", self.instrument)
self.instrument = self.instrument.lower().replace('/', '') | [
"def",
"_check_instrument",
"(",
"self",
")",
":",
"instr",
"=",
"INSTRUMENTS",
".",
"get",
"(",
"self",
".",
"platform_name",
",",
"self",
".",
"instrument",
".",
"lower",
"(",
")",
")",
"if",
"instr",
"!=",
"self",
".",
"instrument",
".",
"lower",
"(... | Check and try fix instrument name if needed | [
"Check",
"and",
"try",
"fix",
"instrument",
"name",
"if",
"needed"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L112-L120 | train | 29,206 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse._get_filename | def _get_filename(self):
"""Get the rsr filname from platform and instrument names, and download if not
available.
"""
self.filename = expanduser(
os.path.join(self.rsr_dir, 'rsr_{0}_{1}.h5'.format(self.instrument,
self.platform_name)))
LOG.debug('Filename: %s', str(self.filename))
if not os.path.exists(self.filename) or not os.path.isfile(self.filename):
LOG.warning("No rsr file %s on disk", self.filename)
if self._rsr_data_version_uptodate:
LOG.info("RSR data up to date, so seems there is no support for this platform and sensor")
else:
# Try download from the internet!
if self.do_download:
LOG.info("Will download from internet...")
download_rsr()
if self._get_rsr_data_version() == RSR_DATA_VERSION:
self._rsr_data_version_uptodate = True
if not self._rsr_data_version_uptodate:
LOG.warning("rsr data may not be up to date: %s", self.filename)
if self.do_download:
LOG.info("Will download from internet...")
download_rsr() | python | def _get_filename(self):
"""Get the rsr filname from platform and instrument names, and download if not
available.
"""
self.filename = expanduser(
os.path.join(self.rsr_dir, 'rsr_{0}_{1}.h5'.format(self.instrument,
self.platform_name)))
LOG.debug('Filename: %s', str(self.filename))
if not os.path.exists(self.filename) or not os.path.isfile(self.filename):
LOG.warning("No rsr file %s on disk", self.filename)
if self._rsr_data_version_uptodate:
LOG.info("RSR data up to date, so seems there is no support for this platform and sensor")
else:
# Try download from the internet!
if self.do_download:
LOG.info("Will download from internet...")
download_rsr()
if self._get_rsr_data_version() == RSR_DATA_VERSION:
self._rsr_data_version_uptodate = True
if not self._rsr_data_version_uptodate:
LOG.warning("rsr data may not be up to date: %s", self.filename)
if self.do_download:
LOG.info("Will download from internet...")
download_rsr() | [
"def",
"_get_filename",
"(",
"self",
")",
":",
"self",
".",
"filename",
"=",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"rsr_dir",
",",
"'rsr_{0}_{1}.h5'",
".",
"format",
"(",
"self",
".",
"instrument",
",",
"self",
".",
"plat... | Get the rsr filname from platform and instrument names, and download if not
available. | [
"Get",
"the",
"rsr",
"filname",
"from",
"platform",
"and",
"instrument",
"names",
"and",
"download",
"if",
"not",
"available",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L122-L149 | train | 29,207 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse.load | def load(self):
"""Read the internally formatet hdf5 relative spectral response data"""
import h5py
no_detectors_message = False
with h5py.File(self.filename, 'r') as h5f:
self.band_names = [b.decode('utf-8') for b in h5f.attrs['band_names'].tolist()]
self.description = h5f.attrs['description'].decode('utf-8')
if not self.platform_name:
try:
self.platform_name = h5f.attrs['platform_name'].decode('utf-8')
except KeyError:
LOG.warning("No platform_name in HDF5 file")
try:
self.platform_name = h5f.attrs[
'platform'] + '-' + h5f.attrs['satnum']
except KeyError:
LOG.warning(
"Unable to determine platform name from HDF5 file content")
self.platform_name = None
if not self.instrument:
try:
self.instrument = h5f.attrs['sensor'].decode('utf-8')
except KeyError:
LOG.warning("No sensor name specified in HDF5 file")
self.instrument = INSTRUMENTS.get(self.platform_name)
for bandname in self.band_names:
self.rsr[bandname] = {}
try:
num_of_det = h5f[bandname].attrs['number_of_detectors']
except KeyError:
if not no_detectors_message:
LOG.debug("No detectors found - assume only one...")
num_of_det = 1
no_detectors_message = True
for i in range(1, num_of_det + 1):
dname = 'det-{0:d}'.format(i)
self.rsr[bandname][dname] = {}
try:
resp = h5f[bandname][dname]['response'][:]
except KeyError:
resp = h5f[bandname]['response'][:]
self.rsr[bandname][dname]['response'] = resp
try:
wvl = (h5f[bandname][dname]['wavelength'][:] *
h5f[bandname][dname][
'wavelength'].attrs['scale'])
except KeyError:
wvl = (h5f[bandname]['wavelength'][:] *
h5f[bandname]['wavelength'].attrs['scale'])
# The wavelength is given in micro meters!
self.rsr[bandname][dname]['wavelength'] = wvl * 1e6
try:
central_wvl = h5f[bandname][
dname].attrs['central_wavelength']
except KeyError:
central_wvl = h5f[bandname].attrs['central_wavelength']
self.rsr[bandname][dname][
'central_wavelength'] = central_wvl | python | def load(self):
"""Read the internally formatet hdf5 relative spectral response data"""
import h5py
no_detectors_message = False
with h5py.File(self.filename, 'r') as h5f:
self.band_names = [b.decode('utf-8') for b in h5f.attrs['band_names'].tolist()]
self.description = h5f.attrs['description'].decode('utf-8')
if not self.platform_name:
try:
self.platform_name = h5f.attrs['platform_name'].decode('utf-8')
except KeyError:
LOG.warning("No platform_name in HDF5 file")
try:
self.platform_name = h5f.attrs[
'platform'] + '-' + h5f.attrs['satnum']
except KeyError:
LOG.warning(
"Unable to determine platform name from HDF5 file content")
self.platform_name = None
if not self.instrument:
try:
self.instrument = h5f.attrs['sensor'].decode('utf-8')
except KeyError:
LOG.warning("No sensor name specified in HDF5 file")
self.instrument = INSTRUMENTS.get(self.platform_name)
for bandname in self.band_names:
self.rsr[bandname] = {}
try:
num_of_det = h5f[bandname].attrs['number_of_detectors']
except KeyError:
if not no_detectors_message:
LOG.debug("No detectors found - assume only one...")
num_of_det = 1
no_detectors_message = True
for i in range(1, num_of_det + 1):
dname = 'det-{0:d}'.format(i)
self.rsr[bandname][dname] = {}
try:
resp = h5f[bandname][dname]['response'][:]
except KeyError:
resp = h5f[bandname]['response'][:]
self.rsr[bandname][dname]['response'] = resp
try:
wvl = (h5f[bandname][dname]['wavelength'][:] *
h5f[bandname][dname][
'wavelength'].attrs['scale'])
except KeyError:
wvl = (h5f[bandname]['wavelength'][:] *
h5f[bandname]['wavelength'].attrs['scale'])
# The wavelength is given in micro meters!
self.rsr[bandname][dname]['wavelength'] = wvl * 1e6
try:
central_wvl = h5f[bandname][
dname].attrs['central_wavelength']
except KeyError:
central_wvl = h5f[bandname].attrs['central_wavelength']
self.rsr[bandname][dname][
'central_wavelength'] = central_wvl | [
"def",
"load",
"(",
"self",
")",
":",
"import",
"h5py",
"no_detectors_message",
"=",
"False",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"h5f",
":",
"self",
".",
"band_names",
"=",
"[",
"b",
".",
"decode",
"(",
... | Read the internally formatet hdf5 relative spectral response data | [
"Read",
"the",
"internally",
"formatet",
"hdf5",
"relative",
"spectral",
"response",
"data"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L151-L217 | train | 29,208 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse.integral | def integral(self, bandname):
"""Calculate the integral of the spectral response function for each
detector.
"""
intg = {}
for det in self.rsr[bandname].keys():
wvl = self.rsr[bandname][det]['wavelength']
resp = self.rsr[bandname][det]['response']
intg[det] = np.trapz(resp, wvl)
return intg | python | def integral(self, bandname):
"""Calculate the integral of the spectral response function for each
detector.
"""
intg = {}
for det in self.rsr[bandname].keys():
wvl = self.rsr[bandname][det]['wavelength']
resp = self.rsr[bandname][det]['response']
intg[det] = np.trapz(resp, wvl)
return intg | [
"def",
"integral",
"(",
"self",
",",
"bandname",
")",
":",
"intg",
"=",
"{",
"}",
"for",
"det",
"in",
"self",
".",
"rsr",
"[",
"bandname",
"]",
".",
"keys",
"(",
")",
":",
"wvl",
"=",
"self",
".",
"rsr",
"[",
"bandname",
"]",
"[",
"det",
"]",
... | Calculate the integral of the spectral response function for each
detector. | [
"Calculate",
"the",
"integral",
"of",
"the",
"spectral",
"response",
"function",
"for",
"each",
"detector",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L219-L228 | train | 29,209 |
pytroll/pyspectral | pyspectral/rsr_reader.py | RelativeSpectralResponse.convert | def convert(self):
"""Convert spectral response functions from wavelength to wavenumber"""
from pyspectral.utils import (convert2wavenumber, get_central_wave)
if self._wavespace == WAVE_LENGTH:
rsr, info = convert2wavenumber(self.rsr)
for band in rsr.keys():
for det in rsr[band].keys():
self.rsr[band][det][WAVE_NUMBER] = rsr[
band][det][WAVE_NUMBER]
self.rsr[band][det]['response'] = rsr[
band][det]['response']
self.unit = info['unit']
self.si_scale = info['si_scale']
self._wavespace = WAVE_NUMBER
for band in rsr.keys():
for det in rsr[band].keys():
self.rsr[band][det]['central_wavenumber'] = \
get_central_wave(self.rsr[band][det][WAVE_NUMBER], self.rsr[band][det]['response'])
del self.rsr[band][det][WAVE_LENGTH]
else:
errmsg = "Conversion from {wn} to {wl} not supported yet".format(wn=WAVE_NUMBER, wl=WAVE_LENGTH)
raise NotImplementedError(errmsg) | python | def convert(self):
"""Convert spectral response functions from wavelength to wavenumber"""
from pyspectral.utils import (convert2wavenumber, get_central_wave)
if self._wavespace == WAVE_LENGTH:
rsr, info = convert2wavenumber(self.rsr)
for band in rsr.keys():
for det in rsr[band].keys():
self.rsr[band][det][WAVE_NUMBER] = rsr[
band][det][WAVE_NUMBER]
self.rsr[band][det]['response'] = rsr[
band][det]['response']
self.unit = info['unit']
self.si_scale = info['si_scale']
self._wavespace = WAVE_NUMBER
for band in rsr.keys():
for det in rsr[band].keys():
self.rsr[band][det]['central_wavenumber'] = \
get_central_wave(self.rsr[band][det][WAVE_NUMBER], self.rsr[band][det]['response'])
del self.rsr[band][det][WAVE_LENGTH]
else:
errmsg = "Conversion from {wn} to {wl} not supported yet".format(wn=WAVE_NUMBER, wl=WAVE_LENGTH)
raise NotImplementedError(errmsg) | [
"def",
"convert",
"(",
"self",
")",
":",
"from",
"pyspectral",
".",
"utils",
"import",
"(",
"convert2wavenumber",
",",
"get_central_wave",
")",
"if",
"self",
".",
"_wavespace",
"==",
"WAVE_LENGTH",
":",
"rsr",
",",
"info",
"=",
"convert2wavenumber",
"(",
"se... | Convert spectral response functions from wavelength to wavenumber | [
"Convert",
"spectral",
"response",
"functions",
"from",
"wavelength",
"to",
"wavenumber"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rsr_reader.py#L230-L252 | train | 29,210 |
pytroll/pyspectral | pyspectral/raw_reader.py | InstrumentRSR._get_options_from_config | def _get_options_from_config(self):
"""Get configuration settings from configuration file"""
options = get_config()
self.output_dir = options.get('rsr_dir', './')
self.path = options[self.platform_name + '-' + self.instrument]['path']
self.options = options | python | def _get_options_from_config(self):
"""Get configuration settings from configuration file"""
options = get_config()
self.output_dir = options.get('rsr_dir', './')
self.path = options[self.platform_name + '-' + self.instrument]['path']
self.options = options | [
"def",
"_get_options_from_config",
"(",
"self",
")",
":",
"options",
"=",
"get_config",
"(",
")",
"self",
".",
"output_dir",
"=",
"options",
".",
"get",
"(",
"'rsr_dir'",
",",
"'./'",
")",
"self",
".",
"path",
"=",
"options",
"[",
"self",
".",
"platform_... | Get configuration settings from configuration file | [
"Get",
"configuration",
"settings",
"from",
"configuration",
"file"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/raw_reader.py#L55-L61 | train | 29,211 |
pytroll/pyspectral | pyspectral/raw_reader.py | InstrumentRSR._get_bandfilenames | def _get_bandfilenames(self):
"""Get the instrument rsr filenames"""
for band in self.bandnames:
LOG.debug("Band = %s", str(band))
self.filenames[band] = os.path.join(self.path,
self.options[self.platform_name + '-' +
self.instrument][band])
LOG.debug(self.filenames[band])
if not os.path.exists(self.filenames[band]):
LOG.warning("Couldn't find an existing file for this band: %s",
str(self.filenames[band])) | python | def _get_bandfilenames(self):
"""Get the instrument rsr filenames"""
for band in self.bandnames:
LOG.debug("Band = %s", str(band))
self.filenames[band] = os.path.join(self.path,
self.options[self.platform_name + '-' +
self.instrument][band])
LOG.debug(self.filenames[band])
if not os.path.exists(self.filenames[band]):
LOG.warning("Couldn't find an existing file for this band: %s",
str(self.filenames[band])) | [
"def",
"_get_bandfilenames",
"(",
"self",
")",
":",
"for",
"band",
"in",
"self",
".",
"bandnames",
":",
"LOG",
".",
"debug",
"(",
"\"Band = %s\"",
",",
"str",
"(",
"band",
")",
")",
"self",
".",
"filenames",
"[",
"band",
"]",
"=",
"os",
".",
"path",
... | Get the instrument rsr filenames | [
"Get",
"the",
"instrument",
"rsr",
"filenames"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/raw_reader.py#L63-L73 | train | 29,212 |
pytroll/pyspectral | pyspectral/blackbody.py | blackbody_rad2temp | def blackbody_rad2temp(wavelength, radiance):
"""Derive brightness temperatures from radiance using the Planck
function. Wavelength space. Assumes SI units as input and returns
temperature in Kelvin
"""
mask = False
if np.isscalar(radiance):
rad = np.array([radiance, ], dtype='float64')
else:
rad = np.array(radiance, dtype='float64')
if np.ma.is_masked(radiance):
mask = radiance.mask
rad = np.ma.masked_array(rad, mask=mask)
rad = np.ma.masked_less_equal(rad, 0)
if np.isscalar(wavelength):
wvl = np.array([wavelength, ], dtype='float64')
else:
wvl = np.array(wavelength, dtype='float64')
const1 = H_PLANCK * C_SPEED / K_BOLTZMANN
const2 = 2 * H_PLANCK * C_SPEED**2
res = const1 / (wvl * np.log(np.divide(const2, rad * wvl**5) + 1.0))
shape = rad.shape
resshape = res.shape
if wvl.shape[0] == 1:
if rad.shape[0] == 1:
return res[0]
else:
return res[::].reshape(shape)
else:
if rad.shape[0] == 1:
return res[0, :]
else:
if len(shape) == 1:
return np.reshape(res, (shape[0], resshape[1]))
else:
return np.reshape(res, (shape[0], shape[1], resshape[1])) | python | def blackbody_rad2temp(wavelength, radiance):
"""Derive brightness temperatures from radiance using the Planck
function. Wavelength space. Assumes SI units as input and returns
temperature in Kelvin
"""
mask = False
if np.isscalar(radiance):
rad = np.array([radiance, ], dtype='float64')
else:
rad = np.array(radiance, dtype='float64')
if np.ma.is_masked(radiance):
mask = radiance.mask
rad = np.ma.masked_array(rad, mask=mask)
rad = np.ma.masked_less_equal(rad, 0)
if np.isscalar(wavelength):
wvl = np.array([wavelength, ], dtype='float64')
else:
wvl = np.array(wavelength, dtype='float64')
const1 = H_PLANCK * C_SPEED / K_BOLTZMANN
const2 = 2 * H_PLANCK * C_SPEED**2
res = const1 / (wvl * np.log(np.divide(const2, rad * wvl**5) + 1.0))
shape = rad.shape
resshape = res.shape
if wvl.shape[0] == 1:
if rad.shape[0] == 1:
return res[0]
else:
return res[::].reshape(shape)
else:
if rad.shape[0] == 1:
return res[0, :]
else:
if len(shape) == 1:
return np.reshape(res, (shape[0], resshape[1]))
else:
return np.reshape(res, (shape[0], shape[1], resshape[1])) | [
"def",
"blackbody_rad2temp",
"(",
"wavelength",
",",
"radiance",
")",
":",
"mask",
"=",
"False",
"if",
"np",
".",
"isscalar",
"(",
"radiance",
")",
":",
"rad",
"=",
"np",
".",
"array",
"(",
"[",
"radiance",
",",
"]",
",",
"dtype",
"=",
"'float64'",
"... | Derive brightness temperatures from radiance using the Planck
function. Wavelength space. Assumes SI units as input and returns
temperature in Kelvin | [
"Derive",
"brightness",
"temperatures",
"from",
"radiance",
"using",
"the",
"Planck",
"function",
".",
"Wavelength",
"space",
".",
"Assumes",
"SI",
"units",
"as",
"input",
"and",
"returns",
"temperature",
"in",
"Kelvin"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/blackbody.py#L37-L79 | train | 29,213 |
pytroll/pyspectral | pyspectral/blackbody.py | blackbody_wn_rad2temp | def blackbody_wn_rad2temp(wavenumber, radiance):
"""Derive brightness temperatures from radiance using the Planck
function. Wavenumber space"""
if np.isscalar(radiance):
rad = np.array([radiance, ], dtype='float64')
else:
rad = np.array(radiance, dtype='float64')
if np.isscalar(wavenumber):
wavnum = np.array([wavenumber, ], dtype='float64')
else:
wavnum = np.array(wavenumber, dtype='float64')
const1 = H_PLANCK * C_SPEED / K_BOLTZMANN
const2 = 2 * H_PLANCK * C_SPEED**2
res = const1 * wavnum / np.log(np.divide(const2 * wavnum**3, rad) + 1.0)
shape = rad.shape
resshape = res.shape
if wavnum.shape[0] == 1:
if rad.shape[0] == 1:
return res[0]
else:
return res[::].reshape(shape)
else:
if rad.shape[0] == 1:
return res[0, :]
else:
if len(shape) == 1:
return np.reshape(res, (shape[0], resshape[1]))
else:
return np.reshape(res, (shape[0], shape[1], resshape[1])) | python | def blackbody_wn_rad2temp(wavenumber, radiance):
"""Derive brightness temperatures from radiance using the Planck
function. Wavenumber space"""
if np.isscalar(radiance):
rad = np.array([radiance, ], dtype='float64')
else:
rad = np.array(radiance, dtype='float64')
if np.isscalar(wavenumber):
wavnum = np.array([wavenumber, ], dtype='float64')
else:
wavnum = np.array(wavenumber, dtype='float64')
const1 = H_PLANCK * C_SPEED / K_BOLTZMANN
const2 = 2 * H_PLANCK * C_SPEED**2
res = const1 * wavnum / np.log(np.divide(const2 * wavnum**3, rad) + 1.0)
shape = rad.shape
resshape = res.shape
if wavnum.shape[0] == 1:
if rad.shape[0] == 1:
return res[0]
else:
return res[::].reshape(shape)
else:
if rad.shape[0] == 1:
return res[0, :]
else:
if len(shape) == 1:
return np.reshape(res, (shape[0], resshape[1]))
else:
return np.reshape(res, (shape[0], shape[1], resshape[1])) | [
"def",
"blackbody_wn_rad2temp",
"(",
"wavenumber",
",",
"radiance",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"radiance",
")",
":",
"rad",
"=",
"np",
".",
"array",
"(",
"[",
"radiance",
",",
"]",
",",
"dtype",
"=",
"'float64'",
")",
"else",
":",
"r... | Derive brightness temperatures from radiance using the Planck
function. Wavenumber space | [
"Derive",
"brightness",
"temperatures",
"from",
"radiance",
"using",
"the",
"Planck",
"function",
".",
"Wavenumber",
"space"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/blackbody.py#L82-L114 | train | 29,214 |
pytroll/pyspectral | rsr_convert_scripts/seviri_rsr.py | get_central_wave | def get_central_wave(wavl, resp):
"""Calculate the central wavelength or the central wavenumber,
depending on what is input
"""
return np.trapz(resp * wavl, wavl) / np.trapz(resp, wavl) | python | def get_central_wave(wavl, resp):
"""Calculate the central wavelength or the central wavenumber,
depending on what is input
"""
return np.trapz(resp * wavl, wavl) / np.trapz(resp, wavl) | [
"def",
"get_central_wave",
"(",
"wavl",
",",
"resp",
")",
":",
"return",
"np",
".",
"trapz",
"(",
"resp",
"*",
"wavl",
",",
"wavl",
")",
"/",
"np",
".",
"trapz",
"(",
"resp",
",",
"wavl",
")"
] | Calculate the central wavelength or the central wavenumber,
depending on what is input | [
"Calculate",
"the",
"central",
"wavelength",
"or",
"the",
"central",
"wavenumber",
"depending",
"on",
"what",
"is",
"input"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/seviri_rsr.py#L215-L219 | train | 29,215 |
pytroll/pyspectral | rsr_convert_scripts/seviri_rsr.py | generate_seviri_file | def generate_seviri_file(seviri, platform_name):
"""Generate the pyspectral internal common format relative response
function file for one SEVIRI
"""
import h5py
filename = os.path.join(seviri.output_dir,
"rsr_seviri_{0}.h5".format(platform_name))
sat_name = platform_name
with h5py.File(filename, "w") as h5f:
h5f.attrs['description'] = 'Relative Spectral Responses for SEVIRI'
h5f.attrs['platform_name'] = platform_name
bandlist = [str(key) for key in seviri.rsr.keys()]
h5f.attrs['band_names'] = bandlist
for key in seviri.rsr.keys():
grp = h5f.create_group(key)
if isinstance(seviri.central_wavelength[key][sat_name], dict):
grp.attrs['central_wavelength'] = \
seviri.central_wavelength[key][sat_name]['95']
else:
grp.attrs['central_wavelength'] = \
seviri.central_wavelength[key][sat_name]
arr = seviri.rsr[key]['wavelength']
dset = grp.create_dataset('wavelength', arr.shape, dtype='f')
dset.attrs['unit'] = 'm'
dset.attrs['scale'] = 1e-06
dset[...] = arr
try:
arr = seviri.rsr[key][sat_name]['95']
except ValueError:
arr = seviri.rsr[key][sat_name]
dset = grp.create_dataset('response', arr.shape, dtype='f')
dset[...] = arr
return | python | def generate_seviri_file(seviri, platform_name):
"""Generate the pyspectral internal common format relative response
function file for one SEVIRI
"""
import h5py
filename = os.path.join(seviri.output_dir,
"rsr_seviri_{0}.h5".format(platform_name))
sat_name = platform_name
with h5py.File(filename, "w") as h5f:
h5f.attrs['description'] = 'Relative Spectral Responses for SEVIRI'
h5f.attrs['platform_name'] = platform_name
bandlist = [str(key) for key in seviri.rsr.keys()]
h5f.attrs['band_names'] = bandlist
for key in seviri.rsr.keys():
grp = h5f.create_group(key)
if isinstance(seviri.central_wavelength[key][sat_name], dict):
grp.attrs['central_wavelength'] = \
seviri.central_wavelength[key][sat_name]['95']
else:
grp.attrs['central_wavelength'] = \
seviri.central_wavelength[key][sat_name]
arr = seviri.rsr[key]['wavelength']
dset = grp.create_dataset('wavelength', arr.shape, dtype='f')
dset.attrs['unit'] = 'm'
dset.attrs['scale'] = 1e-06
dset[...] = arr
try:
arr = seviri.rsr[key][sat_name]['95']
except ValueError:
arr = seviri.rsr[key][sat_name]
dset = grp.create_dataset('response', arr.shape, dtype='f')
dset[...] = arr
return | [
"def",
"generate_seviri_file",
"(",
"seviri",
",",
"platform_name",
")",
":",
"import",
"h5py",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"seviri",
".",
"output_dir",
",",
"\"rsr_seviri_{0}.h5\"",
".",
"format",
"(",
"platform_name",
")",
")",
"s... | Generate the pyspectral internal common format relative response
function file for one SEVIRI | [
"Generate",
"the",
"pyspectral",
"internal",
"common",
"format",
"relative",
"response",
"function",
"file",
"for",
"one",
"SEVIRI"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/seviri_rsr.py#L222-L259 | train | 29,216 |
pytroll/pyspectral | rsr_convert_scripts/seviri_rsr.py | Seviri.convert2wavenumber | def convert2wavenumber(self):
"""Convert from wavelengths to wavenumber"""
for chname in self.rsr.keys():
elems = [k for k in self.rsr[chname].keys()]
for sat in elems:
if sat == "wavelength":
LOG.debug("Get the wavenumber from the wavelength: sat=%s chname=%s", sat, chname)
wnum = 1. / (1e-4 * self.rsr[chname][sat][:]) # microns to cm
self.rsr[chname]['wavenumber'] = wnum[::-1]
else:
if type(self.rsr[chname][sat]) is dict:
for name in self.rsr[chname][sat].keys():
resp = self.rsr[chname][sat][name][:]
self.rsr[chname][sat][name] = resp[::-1]
else:
resp = self.rsr[chname][sat][:]
self.rsr[chname][sat] = resp[::-1]
for chname in self.rsr.keys():
del self.rsr[chname]['wavelength']
self.unit = 'cm-1' | python | def convert2wavenumber(self):
"""Convert from wavelengths to wavenumber"""
for chname in self.rsr.keys():
elems = [k for k in self.rsr[chname].keys()]
for sat in elems:
if sat == "wavelength":
LOG.debug("Get the wavenumber from the wavelength: sat=%s chname=%s", sat, chname)
wnum = 1. / (1e-4 * self.rsr[chname][sat][:]) # microns to cm
self.rsr[chname]['wavenumber'] = wnum[::-1]
else:
if type(self.rsr[chname][sat]) is dict:
for name in self.rsr[chname][sat].keys():
resp = self.rsr[chname][sat][name][:]
self.rsr[chname][sat][name] = resp[::-1]
else:
resp = self.rsr[chname][sat][:]
self.rsr[chname][sat] = resp[::-1]
for chname in self.rsr.keys():
del self.rsr[chname]['wavelength']
self.unit = 'cm-1' | [
"def",
"convert2wavenumber",
"(",
"self",
")",
":",
"for",
"chname",
"in",
"self",
".",
"rsr",
".",
"keys",
"(",
")",
":",
"elems",
"=",
"[",
"k",
"for",
"k",
"in",
"self",
".",
"rsr",
"[",
"chname",
"]",
".",
"keys",
"(",
")",
"]",
"for",
"sat... | Convert from wavelengths to wavenumber | [
"Convert",
"from",
"wavelengths",
"to",
"wavenumber"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/seviri_rsr.py#L163-L184 | train | 29,217 |
pytroll/pyspectral | rsr_convert_scripts/seviri_rsr.py | Seviri.get_centrals | def get_centrals(self):
"""Get the central wavenumbers or central wavelengths of all channels,
depending on the given 'wavespace'
"""
result = {}
for chname in self.rsr.keys():
result[chname] = {}
if self.wavespace == "wavelength":
x__ = self.rsr[chname]["wavelength"]
else:
x__ = self.rsr[chname]["wavenumber"]
for sat in self.rsr[chname].keys():
if sat in ["wavelength", "wavenumber"]:
continue
if type(self.rsr[chname][sat]) is dict:
result[chname][sat] = {}
for name in self.rsr[chname][sat].keys():
resp = self.rsr[chname][sat][name]
result[chname][sat][name] = get_central_wave(x__, resp)
else:
resp = self.rsr[chname][sat]
result[chname][sat] = get_central_wave(x__, resp)
if self.wavespace == "wavelength":
self.central_wavelength = result
else:
self.central_wavenumber = result | python | def get_centrals(self):
"""Get the central wavenumbers or central wavelengths of all channels,
depending on the given 'wavespace'
"""
result = {}
for chname in self.rsr.keys():
result[chname] = {}
if self.wavespace == "wavelength":
x__ = self.rsr[chname]["wavelength"]
else:
x__ = self.rsr[chname]["wavenumber"]
for sat in self.rsr[chname].keys():
if sat in ["wavelength", "wavenumber"]:
continue
if type(self.rsr[chname][sat]) is dict:
result[chname][sat] = {}
for name in self.rsr[chname][sat].keys():
resp = self.rsr[chname][sat][name]
result[chname][sat][name] = get_central_wave(x__, resp)
else:
resp = self.rsr[chname][sat]
result[chname][sat] = get_central_wave(x__, resp)
if self.wavespace == "wavelength":
self.central_wavelength = result
else:
self.central_wavenumber = result | [
"def",
"get_centrals",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"chname",
"in",
"self",
".",
"rsr",
".",
"keys",
"(",
")",
":",
"result",
"[",
"chname",
"]",
"=",
"{",
"}",
"if",
"self",
".",
"wavespace",
"==",
"\"wavelength\"",
":",
... | Get the central wavenumbers or central wavelengths of all channels,
depending on the given 'wavespace' | [
"Get",
"the",
"central",
"wavenumbers",
"or",
"central",
"wavelengths",
"of",
"all",
"channels",
"depending",
"on",
"the",
"given",
"wavespace"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/seviri_rsr.py#L186-L212 | train | 29,218 |
pytroll/pyspectral | rsr_convert_scripts/abi_rsr.py | AbiRSR._load | def _load(self, scale=1.0):
"""Load the ABI relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
data = np.genfromtxt(self.requested_band_filename,
unpack=True,
names=['wavelength',
'wavenumber',
'response'],
skip_header=2)
wvl = data['wavelength'] * scale
resp = data['response']
self.rsr = {'wavelength': wvl, 'response': resp} | python | def _load(self, scale=1.0):
"""Load the ABI relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
data = np.genfromtxt(self.requested_band_filename,
unpack=True,
names=['wavelength',
'wavenumber',
'response'],
skip_header=2)
wvl = data['wavelength'] * scale
resp = data['response']
self.rsr = {'wavelength': wvl, 'response': resp} | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"LOG",
".",
"debug",
"(",
"\"File: %s\"",
",",
"str",
"(",
"self",
".",
"requested_band_filename",
")",
")",
"data",
"=",
"np",
".",
"genfromtxt",
"(",
"self",
".",
"requested_band_filename... | Load the ABI relative spectral responses | [
"Load",
"the",
"ABI",
"relative",
"spectral",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/abi_rsr.py#L71-L87 | train | 29,219 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum.convert2wavenumber | def convert2wavenumber(self):
"""
Convert from wavelengths to wavenumber.
Units:
Wavelength: micro meters (1e-6 m)
Wavenumber: cm-1
"""
self.wavenumber = 1. / (1e-4 * self.wavelength[::-1])
self.irradiance = (self.irradiance[::-1] *
self.wavelength[::-1] * self.wavelength[::-1] * 0.1)
self.wavelength = None | python | def convert2wavenumber(self):
"""
Convert from wavelengths to wavenumber.
Units:
Wavelength: micro meters (1e-6 m)
Wavenumber: cm-1
"""
self.wavenumber = 1. / (1e-4 * self.wavelength[::-1])
self.irradiance = (self.irradiance[::-1] *
self.wavelength[::-1] * self.wavelength[::-1] * 0.1)
self.wavelength = None | [
"def",
"convert2wavenumber",
"(",
"self",
")",
":",
"self",
".",
"wavenumber",
"=",
"1.",
"/",
"(",
"1e-4",
"*",
"self",
".",
"wavelength",
"[",
":",
":",
"-",
"1",
"]",
")",
"self",
".",
"irradiance",
"=",
"(",
"self",
".",
"irradiance",
"[",
":",... | Convert from wavelengths to wavenumber.
Units:
Wavelength: micro meters (1e-6 m)
Wavenumber: cm-1 | [
"Convert",
"from",
"wavelengths",
"to",
"wavenumber",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L90-L101 | train | 29,220 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum._load | def _load(self):
"""Read the tabulated spectral irradiance data from file"""
self.wavelength, self.irradiance = \
np.genfromtxt(self.filename, unpack=True) | python | def _load(self):
"""Read the tabulated spectral irradiance data from file"""
self.wavelength, self.irradiance = \
np.genfromtxt(self.filename, unpack=True) | [
"def",
"_load",
"(",
"self",
")",
":",
"self",
".",
"wavelength",
",",
"self",
".",
"irradiance",
"=",
"np",
".",
"genfromtxt",
"(",
"self",
".",
"filename",
",",
"unpack",
"=",
"True",
")"
] | Read the tabulated spectral irradiance data from file | [
"Read",
"the",
"tabulated",
"spectral",
"irradiance",
"data",
"from",
"file"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L103-L106 | train | 29,221 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum.solar_constant | def solar_constant(self):
"""Calculate the solar constant"""
if self.wavenumber is not None:
return np.trapz(self.irradiance, self.wavenumber)
elif self.wavelength is not None:
return np.trapz(self.irradiance, self.wavelength)
else:
raise TypeError('Neither wavelengths nor wavenumbers available!') | python | def solar_constant(self):
"""Calculate the solar constant"""
if self.wavenumber is not None:
return np.trapz(self.irradiance, self.wavenumber)
elif self.wavelength is not None:
return np.trapz(self.irradiance, self.wavelength)
else:
raise TypeError('Neither wavelengths nor wavenumbers available!') | [
"def",
"solar_constant",
"(",
"self",
")",
":",
"if",
"self",
".",
"wavenumber",
"is",
"not",
"None",
":",
"return",
"np",
".",
"trapz",
"(",
"self",
".",
"irradiance",
",",
"self",
".",
"wavenumber",
")",
"elif",
"self",
".",
"wavelength",
"is",
"not"... | Calculate the solar constant | [
"Calculate",
"the",
"solar",
"constant"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L108-L115 | train | 29,222 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum.inband_solarflux | def inband_solarflux(self, rsr, scale=1.0, **options):
"""Derive the inband solar flux for a given instrument relative
spectral response valid for an earth-sun distance of one AU.
"""
return self._band_calculations(rsr, True, scale, **options) | python | def inband_solarflux(self, rsr, scale=1.0, **options):
"""Derive the inband solar flux for a given instrument relative
spectral response valid for an earth-sun distance of one AU.
"""
return self._band_calculations(rsr, True, scale, **options) | [
"def",
"inband_solarflux",
"(",
"self",
",",
"rsr",
",",
"scale",
"=",
"1.0",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"_band_calculations",
"(",
"rsr",
",",
"True",
",",
"scale",
",",
"*",
"*",
"options",
")"
] | Derive the inband solar flux for a given instrument relative
spectral response valid for an earth-sun distance of one AU. | [
"Derive",
"the",
"inband",
"solar",
"flux",
"for",
"a",
"given",
"instrument",
"relative",
"spectral",
"response",
"valid",
"for",
"an",
"earth",
"-",
"sun",
"distance",
"of",
"one",
"AU",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L117-L121 | train | 29,223 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum.inband_solarirradiance | def inband_solarirradiance(self, rsr, scale=1.0, **options):
"""Derive the inband solar irradiance for a given instrument relative
spectral response valid for an earth-sun distance of one AU."""
return self._band_calculations(rsr, False, scale, **options) | python | def inband_solarirradiance(self, rsr, scale=1.0, **options):
"""Derive the inband solar irradiance for a given instrument relative
spectral response valid for an earth-sun distance of one AU."""
return self._band_calculations(rsr, False, scale, **options) | [
"def",
"inband_solarirradiance",
"(",
"self",
",",
"rsr",
",",
"scale",
"=",
"1.0",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"_band_calculations",
"(",
"rsr",
",",
"False",
",",
"scale",
",",
"*",
"*",
"options",
")"
] | Derive the inband solar irradiance for a given instrument relative
spectral response valid for an earth-sun distance of one AU. | [
"Derive",
"the",
"inband",
"solar",
"irradiance",
"for",
"a",
"given",
"instrument",
"relative",
"spectral",
"response",
"valid",
"for",
"an",
"earth",
"-",
"sun",
"distance",
"of",
"one",
"AU",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L123-L127 | train | 29,224 |
pytroll/pyspectral | pyspectral/solar.py | SolarIrradianceSpectrum._band_calculations | def _band_calculations(self, rsr, flux, scale, **options):
"""Derive the inband solar flux or inband solar irradiance for a given
instrument relative spectral response valid for an earth-sun distance
of one AU.
rsr: Relative Spectral Response (one detector only)
Dictionary with two members 'wavelength' and 'response'
options:
detector: Detector number (between 1 and N - N=number of detectors
for channel)
"""
from scipy.interpolate import InterpolatedUnivariateSpline
if 'detector' in options:
detector = options['detector']
else:
detector = 1
# Resample/Interpolate the response curve:
if self.wavespace == 'wavelength':
if 'response' in rsr:
wvl = rsr['wavelength'] * scale
resp = rsr['response']
else:
wvl = rsr['det-{0:d}'.format(detector)]['wavelength'] * scale
resp = rsr['det-{0:d}'.format(detector)]['response']
else:
if 'response' in rsr:
wvl = rsr['wavenumber'] * scale
resp = rsr['response']
else:
wvl = rsr['det-{0:d}'.format(detector)]['wavenumber'] * scale
resp = rsr['det-{0:d}'.format(detector)]['response']
start = wvl[0]
end = wvl[-1]
# print "Start and end: ", start, end
LOG.debug("Begin and end wavelength/wavenumber: %f %f ", start, end)
dlambda = self._dlambda
xspl = np.linspace(start, end, round((end - start) / self._dlambda) + 1)
ius = InterpolatedUnivariateSpline(wvl, resp)
resp_ipol = ius(xspl)
# Interpolate solar spectrum to specified resolution and over specified
# Spectral interval:
self.interpolate(dlambda=dlambda, ival_wavelength=(start, end))
# Mask out outside the response curve:
maskidx = np.logical_and(np.greater_equal(self.ipol_wavelength, start),
np.less_equal(self.ipol_wavelength, end))
wvl = np.repeat(self.ipol_wavelength, maskidx)
irr = np.repeat(self.ipol_irradiance, maskidx)
# Calculate the solar-flux: (w/m2)
if flux:
return np.trapz(irr * resp_ipol, wvl)
else:
# Divide by the equivalent band width:
return np.trapz(irr * resp_ipol, wvl) / np.trapz(resp_ipol, wvl) | python | def _band_calculations(self, rsr, flux, scale, **options):
"""Derive the inband solar flux or inband solar irradiance for a given
instrument relative spectral response valid for an earth-sun distance
of one AU.
rsr: Relative Spectral Response (one detector only)
Dictionary with two members 'wavelength' and 'response'
options:
detector: Detector number (between 1 and N - N=number of detectors
for channel)
"""
from scipy.interpolate import InterpolatedUnivariateSpline
if 'detector' in options:
detector = options['detector']
else:
detector = 1
# Resample/Interpolate the response curve:
if self.wavespace == 'wavelength':
if 'response' in rsr:
wvl = rsr['wavelength'] * scale
resp = rsr['response']
else:
wvl = rsr['det-{0:d}'.format(detector)]['wavelength'] * scale
resp = rsr['det-{0:d}'.format(detector)]['response']
else:
if 'response' in rsr:
wvl = rsr['wavenumber'] * scale
resp = rsr['response']
else:
wvl = rsr['det-{0:d}'.format(detector)]['wavenumber'] * scale
resp = rsr['det-{0:d}'.format(detector)]['response']
start = wvl[0]
end = wvl[-1]
# print "Start and end: ", start, end
LOG.debug("Begin and end wavelength/wavenumber: %f %f ", start, end)
dlambda = self._dlambda
xspl = np.linspace(start, end, round((end - start) / self._dlambda) + 1)
ius = InterpolatedUnivariateSpline(wvl, resp)
resp_ipol = ius(xspl)
# Interpolate solar spectrum to specified resolution and over specified
# Spectral interval:
self.interpolate(dlambda=dlambda, ival_wavelength=(start, end))
# Mask out outside the response curve:
maskidx = np.logical_and(np.greater_equal(self.ipol_wavelength, start),
np.less_equal(self.ipol_wavelength, end))
wvl = np.repeat(self.ipol_wavelength, maskidx)
irr = np.repeat(self.ipol_irradiance, maskidx)
# Calculate the solar-flux: (w/m2)
if flux:
return np.trapz(irr * resp_ipol, wvl)
else:
# Divide by the equivalent band width:
return np.trapz(irr * resp_ipol, wvl) / np.trapz(resp_ipol, wvl) | [
"def",
"_band_calculations",
"(",
"self",
",",
"rsr",
",",
"flux",
",",
"scale",
",",
"*",
"*",
"options",
")",
":",
"from",
"scipy",
".",
"interpolate",
"import",
"InterpolatedUnivariateSpline",
"if",
"'detector'",
"in",
"options",
":",
"detector",
"=",
"op... | Derive the inband solar flux or inband solar irradiance for a given
instrument relative spectral response valid for an earth-sun distance
of one AU.
rsr: Relative Spectral Response (one detector only)
Dictionary with two members 'wavelength' and 'response'
options:
detector: Detector number (between 1 and N - N=number of detectors
for channel) | [
"Derive",
"the",
"inband",
"solar",
"flux",
"or",
"inband",
"solar",
"irradiance",
"for",
"a",
"given",
"instrument",
"relative",
"spectral",
"response",
"valid",
"for",
"an",
"earth",
"-",
"sun",
"distance",
"of",
"one",
"AU",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/solar.py#L129-L188 | train | 29,225 |
pytroll/pyspectral | rsr_convert_scripts/ahi_reader.py | AhiRSR._load | def _load(self, filename=None):
"""Load the Himawari AHI RSR data for the band requested
"""
if not filename:
filename = self.filename
wb_ = open_workbook(filename)
self.rsr = {}
sheet_names = []
for sheet in wb_.sheets():
if sheet.name in ['Title', ]:
continue
ch_name = AHI_BAND_NAMES.get(
sheet.name.strip(), sheet.name.strip())
sheet_names.append(sheet.name.strip())
self.rsr[ch_name] = {'wavelength': None,
'response': None}
wvl = np.array(
sheet.col_values(0, start_rowx=5, end_rowx=5453))
resp = np.array(
sheet.col_values(2, start_rowx=5, end_rowx=5453))
self.rsr[ch_name]['wavelength'] = wvl
self.rsr[ch_name]['response'] = resp | python | def _load(self, filename=None):
"""Load the Himawari AHI RSR data for the band requested
"""
if not filename:
filename = self.filename
wb_ = open_workbook(filename)
self.rsr = {}
sheet_names = []
for sheet in wb_.sheets():
if sheet.name in ['Title', ]:
continue
ch_name = AHI_BAND_NAMES.get(
sheet.name.strip(), sheet.name.strip())
sheet_names.append(sheet.name.strip())
self.rsr[ch_name] = {'wavelength': None,
'response': None}
wvl = np.array(
sheet.col_values(0, start_rowx=5, end_rowx=5453))
resp = np.array(
sheet.col_values(2, start_rowx=5, end_rowx=5453))
self.rsr[ch_name]['wavelength'] = wvl
self.rsr[ch_name]['response'] = resp | [
"def",
"_load",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"filename",
"wb_",
"=",
"open_workbook",
"(",
"filename",
")",
"self",
".",
"rsr",
"=",
"{",
"}",
"sheet_names",
"=",
"["... | Load the Himawari AHI RSR data for the band requested | [
"Load",
"the",
"Himawari",
"AHI",
"RSR",
"data",
"for",
"the",
"band",
"requested"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/ahi_reader.py#L87-L109 | train | 29,226 |
pytroll/pyspectral | bin/composite_rsr_plot.py | plot_band | def plot_band(plt_in, band_name, rsr_obj, **kwargs):
"""Do the plotting of one band"""
if 'platform_name_in_legend' in kwargs:
platform_name_in_legend = kwargs['platform_name_in_legend']
else:
platform_name_in_legend = False
detectors = rsr_obj.rsr[band_name].keys()
# for det in detectors:
det = sorted(detectors)[0]
resp = rsr_obj.rsr[band_name][det]['response']
wvl = rsr_obj.rsr[band_name][det]['wavelength']
resp = np.ma.masked_less_equal(resp, minimum_response)
wvl = np.ma.masked_array(wvl, resp.mask)
resp.compressed()
wvl.compressed()
if platform_name_in_legend:
plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
platform=rsr_obj.platform_name, band=band_name))
else:
plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))
return plt_in | python | def plot_band(plt_in, band_name, rsr_obj, **kwargs):
"""Do the plotting of one band"""
if 'platform_name_in_legend' in kwargs:
platform_name_in_legend = kwargs['platform_name_in_legend']
else:
platform_name_in_legend = False
detectors = rsr_obj.rsr[band_name].keys()
# for det in detectors:
det = sorted(detectors)[0]
resp = rsr_obj.rsr[band_name][det]['response']
wvl = rsr_obj.rsr[band_name][det]['wavelength']
resp = np.ma.masked_less_equal(resp, minimum_response)
wvl = np.ma.masked_array(wvl, resp.mask)
resp.compressed()
wvl.compressed()
if platform_name_in_legend:
plt_in.plot(wvl, resp, label='{platform} - {band}'.format(
platform=rsr_obj.platform_name, band=band_name))
else:
plt_in.plot(wvl, resp, label='{band}'.format(band=band_name))
return plt_in | [
"def",
"plot_band",
"(",
"plt_in",
",",
"band_name",
",",
"rsr_obj",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'platform_name_in_legend'",
"in",
"kwargs",
":",
"platform_name_in_legend",
"=",
"kwargs",
"[",
"'platform_name_in_legend'",
"]",
"else",
":",
"platfor... | Do the plotting of one band | [
"Do",
"the",
"plotting",
"of",
"one",
"band"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/bin/composite_rsr_plot.py#L35-L59 | train | 29,227 |
pytroll/pyspectral | pyspectral/utils.py | convert2wavenumber | def convert2wavenumber(rsr):
"""
Take rsr data set with all channels and detectors for an instrument
each with a set of wavelengths and normalised responses and
convert to wavenumbers and responses
:rsr: Relative Spectral Response function (all bands)
Returns:
:retv: Relative Spectral Responses in wave number space
:info: Dictionary with scale (to go convert to SI units) and unit
"""
retv = {}
for chname in rsr.keys(): # Go through bands/channels
retv[chname] = {}
for det in rsr[chname].keys(): # Go through detectors
retv[chname][det] = {}
if 'wavenumber' in rsr[chname][det].keys():
# Make a copy. Data are already in wave number space
retv[chname][det] = rsr[chname][det].copy()
LOG.debug("RSR data already in wavenumber space. No conversion needed.")
continue
for sat in rsr[chname][det].keys():
if sat == "wavelength":
# micro meters to cm
wnum = 1. / (1e-4 * rsr[chname][det][sat])
retv[chname][det]['wavenumber'] = wnum[::-1]
elif sat == "response":
# Flip the response array:
if type(rsr[chname][det][sat]) is dict:
retv[chname][det][sat] = {}
for name in rsr[chname][det][sat].keys():
resp = rsr[chname][det][sat][name]
retv[chname][det][sat][name] = resp[::-1]
else:
resp = rsr[chname][det][sat]
retv[chname][det][sat] = resp[::-1]
unit = 'cm-1'
si_scale = 100.0
return retv, {'unit': unit, 'si_scale': si_scale} | python | def convert2wavenumber(rsr):
"""
Take rsr data set with all channels and detectors for an instrument
each with a set of wavelengths and normalised responses and
convert to wavenumbers and responses
:rsr: Relative Spectral Response function (all bands)
Returns:
:retv: Relative Spectral Responses in wave number space
:info: Dictionary with scale (to go convert to SI units) and unit
"""
retv = {}
for chname in rsr.keys(): # Go through bands/channels
retv[chname] = {}
for det in rsr[chname].keys(): # Go through detectors
retv[chname][det] = {}
if 'wavenumber' in rsr[chname][det].keys():
# Make a copy. Data are already in wave number space
retv[chname][det] = rsr[chname][det].copy()
LOG.debug("RSR data already in wavenumber space. No conversion needed.")
continue
for sat in rsr[chname][det].keys():
if sat == "wavelength":
# micro meters to cm
wnum = 1. / (1e-4 * rsr[chname][det][sat])
retv[chname][det]['wavenumber'] = wnum[::-1]
elif sat == "response":
# Flip the response array:
if type(rsr[chname][det][sat]) is dict:
retv[chname][det][sat] = {}
for name in rsr[chname][det][sat].keys():
resp = rsr[chname][det][sat][name]
retv[chname][det][sat][name] = resp[::-1]
else:
resp = rsr[chname][det][sat]
retv[chname][det][sat] = resp[::-1]
unit = 'cm-1'
si_scale = 100.0
return retv, {'unit': unit, 'si_scale': si_scale} | [
"def",
"convert2wavenumber",
"(",
"rsr",
")",
":",
"retv",
"=",
"{",
"}",
"for",
"chname",
"in",
"rsr",
".",
"keys",
"(",
")",
":",
"# Go through bands/channels",
"retv",
"[",
"chname",
"]",
"=",
"{",
"}",
"for",
"det",
"in",
"rsr",
"[",
"chname",
"]... | Take rsr data set with all channels and detectors for an instrument
each with a set of wavelengths and normalised responses and
convert to wavenumbers and responses
:rsr: Relative Spectral Response function (all bands)
Returns:
:retv: Relative Spectral Responses in wave number space
:info: Dictionary with scale (to go convert to SI units) and unit | [
"Take",
"rsr",
"data",
"set",
"with",
"all",
"channels",
"and",
"detectors",
"for",
"an",
"instrument",
"each",
"with",
"a",
"set",
"of",
"wavelengths",
"and",
"normalised",
"responses",
"and",
"convert",
"to",
"wavenumbers",
"and",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L192-L234 | train | 29,228 |
pytroll/pyspectral | pyspectral/utils.py | get_bandname_from_wavelength | def get_bandname_from_wavelength(sensor, wavelength, rsr, epsilon=0.1, multiple_bands=False):
"""Get the bandname from h5 rsr provided the approximate wavelength."""
# channel_list = [channel for channel in rsr.rsr if abs(
# rsr.rsr[channel]['det-1']['central_wavelength'] - wavelength) < epsilon]
chdist_min = 2.0
chfound = []
for channel in rsr:
chdist = abs(
rsr[channel]['det-1']['central_wavelength'] - wavelength)
if chdist < chdist_min and chdist < epsilon:
chfound.append(BANDNAMES.get(sensor, BANDNAMES['generic']).get(channel, channel))
if len(chfound) == 1:
return chfound[0]
elif len(chfound) > 1:
bstrlist = ['band={}'.format(b) for b in chfound]
if not multiple_bands:
raise AttributeError("More than one band found with that wavelength! {}".format(str(bstrlist)))
else:
LOG.debug("More than one band found with requested wavelength: %s", str(bstrlist))
return chfound
else:
return None | python | def get_bandname_from_wavelength(sensor, wavelength, rsr, epsilon=0.1, multiple_bands=False):
"""Get the bandname from h5 rsr provided the approximate wavelength."""
# channel_list = [channel for channel in rsr.rsr if abs(
# rsr.rsr[channel]['det-1']['central_wavelength'] - wavelength) < epsilon]
chdist_min = 2.0
chfound = []
for channel in rsr:
chdist = abs(
rsr[channel]['det-1']['central_wavelength'] - wavelength)
if chdist < chdist_min and chdist < epsilon:
chfound.append(BANDNAMES.get(sensor, BANDNAMES['generic']).get(channel, channel))
if len(chfound) == 1:
return chfound[0]
elif len(chfound) > 1:
bstrlist = ['band={}'.format(b) for b in chfound]
if not multiple_bands:
raise AttributeError("More than one band found with that wavelength! {}".format(str(bstrlist)))
else:
LOG.debug("More than one band found with requested wavelength: %s", str(bstrlist))
return chfound
else:
return None | [
"def",
"get_bandname_from_wavelength",
"(",
"sensor",
",",
"wavelength",
",",
"rsr",
",",
"epsilon",
"=",
"0.1",
",",
"multiple_bands",
"=",
"False",
")",
":",
"# channel_list = [channel for channel in rsr.rsr if abs(",
"# rsr.rsr[channel]['det-1']['central_wavelength'] - wavel... | Get the bandname from h5 rsr provided the approximate wavelength. | [
"Get",
"the",
"bandname",
"from",
"h5",
"rsr",
"provided",
"the",
"approximate",
"wavelength",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L259-L282 | train | 29,229 |
pytroll/pyspectral | pyspectral/utils.py | download_rsr | def download_rsr(**kwargs):
"""Download the pre-compiled hdf5 formatet relative spectral response functions
from the internet
"""
#
import tarfile
import requests
TQDM_LOADED = True
try:
from tqdm import tqdm
except ImportError:
TQDM_LOADED = False
dest_dir = kwargs.get('dest_dir', LOCAL_RSR_DIR)
dry_run = kwargs.get('dry_run', False)
LOG.info("Download RSR files and store in directory %s", dest_dir)
filename = os.path.join(dest_dir, "pyspectral_rsr_data.tgz")
LOG.debug("Get data. URL: %s", HTTP_PYSPECTRAL_RSR)
LOG.debug("Destination = %s", dest_dir)
if dry_run:
return
response = requests.get(HTTP_PYSPECTRAL_RSR)
if TQDM_LOADED:
with open(filename, "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
else:
with open(filename, "wb") as handle:
for data in response.iter_content():
handle.write(data)
tar = tarfile.open(filename)
tar.extractall(dest_dir)
tar.close()
os.remove(filename) | python | def download_rsr(**kwargs):
"""Download the pre-compiled hdf5 formatet relative spectral response functions
from the internet
"""
#
import tarfile
import requests
TQDM_LOADED = True
try:
from tqdm import tqdm
except ImportError:
TQDM_LOADED = False
dest_dir = kwargs.get('dest_dir', LOCAL_RSR_DIR)
dry_run = kwargs.get('dry_run', False)
LOG.info("Download RSR files and store in directory %s", dest_dir)
filename = os.path.join(dest_dir, "pyspectral_rsr_data.tgz")
LOG.debug("Get data. URL: %s", HTTP_PYSPECTRAL_RSR)
LOG.debug("Destination = %s", dest_dir)
if dry_run:
return
response = requests.get(HTTP_PYSPECTRAL_RSR)
if TQDM_LOADED:
with open(filename, "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
else:
with open(filename, "wb") as handle:
for data in response.iter_content():
handle.write(data)
tar = tarfile.open(filename)
tar.extractall(dest_dir)
tar.close()
os.remove(filename) | [
"def",
"download_rsr",
"(",
"*",
"*",
"kwargs",
")",
":",
"#",
"import",
"tarfile",
"import",
"requests",
"TQDM_LOADED",
"=",
"True",
"try",
":",
"from",
"tqdm",
"import",
"tqdm",
"except",
"ImportError",
":",
"TQDM_LOADED",
"=",
"False",
"dest_dir",
"=",
... | Download the pre-compiled hdf5 formatet relative spectral response functions
from the internet | [
"Download",
"the",
"pre",
"-",
"compiled",
"hdf5",
"formatet",
"relative",
"spectral",
"response",
"functions",
"from",
"the",
"internet"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L343-L382 | train | 29,230 |
pytroll/pyspectral | pyspectral/utils.py | download_luts | def download_luts(**kwargs):
"""Download the luts from internet."""
#
import tarfile
import requests
TQDM_LOADED = True
try:
from tqdm import tqdm
except ImportError:
TQDM_LOADED = False
dry_run = kwargs.get('dry_run', False)
if 'aerosol_type' in kwargs:
if isinstance(kwargs['aerosol_type'], (list, tuple, set)):
aerosol_types = kwargs['aerosol_type']
else:
aerosol_types = [kwargs['aerosol_type'], ]
else:
aerosol_types = HTTPS_RAYLEIGH_LUTS.keys()
chunk_size = 10124
for subname in aerosol_types:
LOG.debug('Aerosol type: %s', subname)
http = HTTPS_RAYLEIGH_LUTS[subname]
LOG.debug('URL = %s', http)
subdir_path = RAYLEIGH_LUT_DIRS[subname]
try:
LOG.debug('Create directory: %s', subdir_path)
if not dry_run:
os.makedirs(subdir_path)
except OSError:
if not os.path.isdir(subdir_path):
raise
if dry_run:
continue
response = requests.get(http)
total_size = int(response.headers['content-length'])
filename = os.path.join(
subdir_path, "pyspectral_rayleigh_correction_luts.tgz")
if TQDM_LOADED:
with open(filename, "wb") as handle:
for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size),
total=(total_size / chunk_size), unit='kB'):
handle.write(data)
else:
with open(filename, "wb") as handle:
for data in response.iter_content():
handle.write(data)
tar = tarfile.open(filename)
tar.extractall(subdir_path)
tar.close()
os.remove(filename) | python | def download_luts(**kwargs):
"""Download the luts from internet."""
#
import tarfile
import requests
TQDM_LOADED = True
try:
from tqdm import tqdm
except ImportError:
TQDM_LOADED = False
dry_run = kwargs.get('dry_run', False)
if 'aerosol_type' in kwargs:
if isinstance(kwargs['aerosol_type'], (list, tuple, set)):
aerosol_types = kwargs['aerosol_type']
else:
aerosol_types = [kwargs['aerosol_type'], ]
else:
aerosol_types = HTTPS_RAYLEIGH_LUTS.keys()
chunk_size = 10124
for subname in aerosol_types:
LOG.debug('Aerosol type: %s', subname)
http = HTTPS_RAYLEIGH_LUTS[subname]
LOG.debug('URL = %s', http)
subdir_path = RAYLEIGH_LUT_DIRS[subname]
try:
LOG.debug('Create directory: %s', subdir_path)
if not dry_run:
os.makedirs(subdir_path)
except OSError:
if not os.path.isdir(subdir_path):
raise
if dry_run:
continue
response = requests.get(http)
total_size = int(response.headers['content-length'])
filename = os.path.join(
subdir_path, "pyspectral_rayleigh_correction_luts.tgz")
if TQDM_LOADED:
with open(filename, "wb") as handle:
for data in tqdm(iterable=response.iter_content(chunk_size=chunk_size),
total=(total_size / chunk_size), unit='kB'):
handle.write(data)
else:
with open(filename, "wb") as handle:
for data in response.iter_content():
handle.write(data)
tar = tarfile.open(filename)
tar.extractall(subdir_path)
tar.close()
os.remove(filename) | [
"def",
"download_luts",
"(",
"*",
"*",
"kwargs",
")",
":",
"#",
"import",
"tarfile",
"import",
"requests",
"TQDM_LOADED",
"=",
"True",
"try",
":",
"from",
"tqdm",
"import",
"tqdm",
"except",
"ImportError",
":",
"TQDM_LOADED",
"=",
"False",
"dry_run",
"=",
... | Download the luts from internet. | [
"Download",
"the",
"luts",
"from",
"internet",
"."
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L385-L444 | train | 29,231 |
pytroll/pyspectral | pyspectral/utils.py | get_logger | def get_logger(name):
"""Return logger with null handle
"""
log = logging.getLogger(name)
if not log.handlers:
log.addHandler(NullHandler())
return log | python | def get_logger(name):
"""Return logger with null handle
"""
log = logging.getLogger(name)
if not log.handlers:
log.addHandler(NullHandler())
return log | [
"def",
"get_logger",
"(",
"name",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"if",
"not",
"log",
".",
"handlers",
":",
"log",
".",
"addHandler",
"(",
"NullHandler",
"(",
")",
")",
"return",
"log"
] | Return logger with null handle | [
"Return",
"logger",
"with",
"null",
"handle"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/utils.py#L492-L499 | train | 29,232 |
pytroll/pyspectral | rsr_convert_scripts/aatsr_reader.py | AatsrRSR._load | def _load(self, filename=None):
"""Read the AATSR rsr data"""
if not filename:
filename = self.aatsr_path
wb_ = open_workbook(filename)
for sheet in wb_.sheets():
ch_name = sheet.name.strip()
if ch_name == 'aatsr_' + self.bandname:
data = np.array([s.split() for s in
sheet.col_values(0,
start_rowx=3, end_rowx=258)])
data = data.astype('f')
wvl = data[:, 0]
resp = data[:, 1]
self.rsr = {'wavelength': wvl, 'response': resp} | python | def _load(self, filename=None):
"""Read the AATSR rsr data"""
if not filename:
filename = self.aatsr_path
wb_ = open_workbook(filename)
for sheet in wb_.sheets():
ch_name = sheet.name.strip()
if ch_name == 'aatsr_' + self.bandname:
data = np.array([s.split() for s in
sheet.col_values(0,
start_rowx=3, end_rowx=258)])
data = data.astype('f')
wvl = data[:, 0]
resp = data[:, 1]
self.rsr = {'wavelength': wvl, 'response': resp} | [
"def",
"_load",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"aatsr_path",
"wb_",
"=",
"open_workbook",
"(",
"filename",
")",
"for",
"sheet",
"in",
"wb_",
".",
"sheets",
"(",
")",
":... | Read the AATSR rsr data | [
"Read",
"the",
"AATSR",
"rsr",
"data"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/aatsr_reader.py#L60-L78 | train | 29,233 |
pytroll/pyspectral | rsr_convert_scripts/oli_reader.py | OliRSR._load | def _load(self, scale=0.001):
"""Load the Landsat OLI relative spectral responses
"""
with open_workbook(self.path) as wb_:
for sheet in wb_.sheets():
if sheet.name in ['Plot of AllBands', ]:
continue
ch_name = OLI_BAND_NAMES.get(sheet.name.strip())
if ch_name != self.bandname:
continue
wvl = sheet.col_values(0, 2)
resp = sheet.col_values(1, 2)
self.rsr = {'wavelength': np.array(wvl) / 1000.,
'response': np.array(resp)}
break | python | def _load(self, scale=0.001):
"""Load the Landsat OLI relative spectral responses
"""
with open_workbook(self.path) as wb_:
for sheet in wb_.sheets():
if sheet.name in ['Plot of AllBands', ]:
continue
ch_name = OLI_BAND_NAMES.get(sheet.name.strip())
if ch_name != self.bandname:
continue
wvl = sheet.col_values(0, 2)
resp = sheet.col_values(1, 2)
self.rsr = {'wavelength': np.array(wvl) / 1000.,
'response': np.array(resp)}
break | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"0.001",
")",
":",
"with",
"open_workbook",
"(",
"self",
".",
"path",
")",
"as",
"wb_",
":",
"for",
"sheet",
"in",
"wb_",
".",
"sheets",
"(",
")",
":",
"if",
"sheet",
".",
"name",
"in",
"[",
"'Plot ... | Load the Landsat OLI relative spectral responses | [
"Load",
"the",
"Landsat",
"OLI",
"relative",
"spectral",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/oli_reader.py#L67-L85 | train | 29,234 |
pytroll/pyspectral | rsr_convert_scripts/metimage_rsr.py | MetImageRSR._load | def _load(self, scale=1.0):
"""Load the MetImage RSR data for the band requested"""
data = np.genfromtxt(self.requested_band_filename,
unpack=True,
names=['wavenumber',
'response'],
skip_header=4)
# Data are wavenumbers in cm-1:
wavelength = 1. / data['wavenumber'] * 10000.
response = data['response']
# The real MetImage has 24 detectors. However, for now we store the
# single rsr as 'detector-1', indicating that there will be multiple
# detectors in the future:
detectors = {}
detectors['det-1'] = {'wavelength': wavelength, 'response': response}
self.rsr = detectors | python | def _load(self, scale=1.0):
"""Load the MetImage RSR data for the band requested"""
data = np.genfromtxt(self.requested_band_filename,
unpack=True,
names=['wavenumber',
'response'],
skip_header=4)
# Data are wavenumbers in cm-1:
wavelength = 1. / data['wavenumber'] * 10000.
response = data['response']
# The real MetImage has 24 detectors. However, for now we store the
# single rsr as 'detector-1', indicating that there will be multiple
# detectors in the future:
detectors = {}
detectors['det-1'] = {'wavelength': wavelength, 'response': response}
self.rsr = detectors | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"data",
"=",
"np",
".",
"genfromtxt",
"(",
"self",
".",
"requested_band_filename",
",",
"unpack",
"=",
"True",
",",
"names",
"=",
"[",
"'wavenumber'",
",",
"'response'",
"]",
",",
"skip_h... | Load the MetImage RSR data for the band requested | [
"Load",
"the",
"MetImage",
"RSR",
"data",
"for",
"the",
"band",
"requested"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/metimage_rsr.py#L71-L88 | train | 29,235 |
pytroll/pyspectral | pyspectral/near_infrared_reflectance.py | Calculator.emissive_part_3x | def emissive_part_3x(self, tb=True):
"""Get the emissive part of the 3.x band"""
try:
# Emissive part:
self._e3x = self._rad3x_t11 * (1 - self._r3x)
# Unsure how much sense it makes to apply the co2 correction term here!?
# FIXME!
# self._e3x *= self._rad3x_correction
except TypeError:
LOG.warning(
"Couldn't derive the emissive part \n" +
"Please derive the relfectance prior to requesting the emissive part")
if tb:
return self.radiance2tb(self._e3x)
else:
return self._e3x | python | def emissive_part_3x(self, tb=True):
"""Get the emissive part of the 3.x band"""
try:
# Emissive part:
self._e3x = self._rad3x_t11 * (1 - self._r3x)
# Unsure how much sense it makes to apply the co2 correction term here!?
# FIXME!
# self._e3x *= self._rad3x_correction
except TypeError:
LOG.warning(
"Couldn't derive the emissive part \n" +
"Please derive the relfectance prior to requesting the emissive part")
if tb:
return self.radiance2tb(self._e3x)
else:
return self._e3x | [
"def",
"emissive_part_3x",
"(",
"self",
",",
"tb",
"=",
"True",
")",
":",
"try",
":",
"# Emissive part:",
"self",
".",
"_e3x",
"=",
"self",
".",
"_rad3x_t11",
"*",
"(",
"1",
"-",
"self",
".",
"_r3x",
")",
"# Unsure how much sense it makes to apply the co2 corr... | Get the emissive part of the 3.x band | [
"Get",
"the",
"emissive",
"part",
"of",
"the",
"3",
".",
"x",
"band"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/near_infrared_reflectance.py#L165-L182 | train | 29,236 |
pytroll/pyspectral | rsr_convert_scripts/olci_rsr.py | OlciRSR._load | def _load(self, scale=0.001):
"""Load the OLCI relative spectral responses
"""
ncf = Dataset(self.path, 'r')
bandnum = OLCI_BAND_NAMES.index(self.bandname)
# cam = 0
# view = 0
# resp = ncf.variables[
# 'spectral_response_function'][bandnum, cam, view, :]
# wvl = ncf.variables[
# 'spectral_response_function_wavelength'][bandnum, cam, view, :] * scale
resp = ncf.variables[
'mean_spectral_response_function'][bandnum, :]
wvl = ncf.variables[
'mean_spectral_response_function_wavelength'][bandnum, :] * scale
self.rsr = {'wavelength': wvl, 'response': resp} | python | def _load(self, scale=0.001):
"""Load the OLCI relative spectral responses
"""
ncf = Dataset(self.path, 'r')
bandnum = OLCI_BAND_NAMES.index(self.bandname)
# cam = 0
# view = 0
# resp = ncf.variables[
# 'spectral_response_function'][bandnum, cam, view, :]
# wvl = ncf.variables[
# 'spectral_response_function_wavelength'][bandnum, cam, view, :] * scale
resp = ncf.variables[
'mean_spectral_response_function'][bandnum, :]
wvl = ncf.variables[
'mean_spectral_response_function_wavelength'][bandnum, :] * scale
self.rsr = {'wavelength': wvl, 'response': resp} | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"0.001",
")",
":",
"ncf",
"=",
"Dataset",
"(",
"self",
".",
"path",
",",
"'r'",
")",
"bandnum",
"=",
"OLCI_BAND_NAMES",
".",
"index",
"(",
"self",
".",
"bandname",
")",
"# cam = 0",
"# view = 0",
"# resp ... | Load the OLCI relative spectral responses | [
"Load",
"the",
"OLCI",
"relative",
"spectral",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/olci_rsr.py#L73-L91 | train | 29,237 |
pytroll/pyspectral | rsr_convert_scripts/modis_rsr.py | ModisRSR._get_bandfilenames | def _get_bandfilenames(self):
"""Get the MODIS rsr filenames"""
path = self.path
for band in MODIS_BAND_NAMES:
bnum = int(band)
LOG.debug("Band = %s", str(band))
if self.platform_name == 'EOS-Terra':
filename = os.path.join(path,
"rsr.{0:d}.inb.final".format(bnum))
else:
if bnum in [5, 6, 7] + range(20, 37):
filename = os.path.join(
path, "{0:>02d}.tv.1pct.det".format(bnum))
else:
filename = os.path.join(
path, "{0:>02d}.amb.1pct.det".format(bnum))
self.filenames[band] = filename | python | def _get_bandfilenames(self):
"""Get the MODIS rsr filenames"""
path = self.path
for band in MODIS_BAND_NAMES:
bnum = int(band)
LOG.debug("Band = %s", str(band))
if self.platform_name == 'EOS-Terra':
filename = os.path.join(path,
"rsr.{0:d}.inb.final".format(bnum))
else:
if bnum in [5, 6, 7] + range(20, 37):
filename = os.path.join(
path, "{0:>02d}.tv.1pct.det".format(bnum))
else:
filename = os.path.join(
path, "{0:>02d}.amb.1pct.det".format(bnum))
self.filenames[band] = filename | [
"def",
"_get_bandfilenames",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"path",
"for",
"band",
"in",
"MODIS_BAND_NAMES",
":",
"bnum",
"=",
"int",
"(",
"band",
")",
"LOG",
".",
"debug",
"(",
"\"Band = %s\"",
",",
"str",
"(",
"band",
")",
")",
"i... | Get the MODIS rsr filenames | [
"Get",
"the",
"MODIS",
"rsr",
"filenames"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/modis_rsr.py#L73-L91 | train | 29,238 |
pytroll/pyspectral | rsr_convert_scripts/modis_rsr.py | ModisRSR._load | def _load(self):
"""Load the MODIS RSR data for the band requested"""
if self.is_sw or self.platform_name == 'EOS-Aqua':
scale = 0.001
else:
scale = 1.0
detector = read_modis_response(self.requested_band_filename, scale)
self.rsr = detector
if self._sort:
self.sort() | python | def _load(self):
"""Load the MODIS RSR data for the band requested"""
if self.is_sw or self.platform_name == 'EOS-Aqua':
scale = 0.001
else:
scale = 1.0
detector = read_modis_response(self.requested_band_filename, scale)
self.rsr = detector
if self._sort:
self.sort() | [
"def",
"_load",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_sw",
"or",
"self",
".",
"platform_name",
"==",
"'EOS-Aqua'",
":",
"scale",
"=",
"0.001",
"else",
":",
"scale",
"=",
"1.0",
"detector",
"=",
"read_modis_response",
"(",
"self",
".",
"requested_... | Load the MODIS RSR data for the band requested | [
"Load",
"the",
"MODIS",
"RSR",
"data",
"for",
"the",
"band",
"requested"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/modis_rsr.py#L93-L102 | train | 29,239 |
pytroll/pyspectral | rsr_convert_scripts/viirs_rsr.py | ViirsRSR._get_bandfilenames | def _get_bandfilenames(self, **options):
"""Get filename for each band"""
conf = options[self.platform_name + '-viirs']
rootdir = conf['rootdir']
for section in conf:
if not section.startswith('section'):
continue
bandnames = conf[section]['bands']
for band in bandnames:
filename = os.path.join(rootdir, conf[section]['filename'])
self.bandfilenames[band] = compose(
filename, {'bandname': band}) | python | def _get_bandfilenames(self, **options):
"""Get filename for each band"""
conf = options[self.platform_name + '-viirs']
rootdir = conf['rootdir']
for section in conf:
if not section.startswith('section'):
continue
bandnames = conf[section]['bands']
for band in bandnames:
filename = os.path.join(rootdir, conf[section]['filename'])
self.bandfilenames[band] = compose(
filename, {'bandname': band}) | [
"def",
"_get_bandfilenames",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"conf",
"=",
"options",
"[",
"self",
".",
"platform_name",
"+",
"'-viirs'",
"]",
"rootdir",
"=",
"conf",
"[",
"'rootdir'",
"]",
"for",
"section",
"in",
"conf",
":",
"if",
"no... | Get filename for each band | [
"Get",
"filename",
"for",
"each",
"band"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/viirs_rsr.py#L126-L138 | train | 29,240 |
pytroll/pyspectral | rsr_convert_scripts/viirs_rsr.py | ViirsRSR._get_bandfile | def _get_bandfile(self, **options):
"""Get the VIIRS rsr filename"""
# Need to understand why there are A&B files for band M16. FIXME!
# Anyway, the absolute response differences are small, below 0.05
# LOG.debug("paths = %s", str(self.bandfilenames))
path = self.bandfilenames[self.bandname]
if not os.path.exists(path):
raise IOError("Couldn't find an existing file for this band ({band}): {path}".format(
band=self.bandname, path=path))
self.filename = path
return | python | def _get_bandfile(self, **options):
"""Get the VIIRS rsr filename"""
# Need to understand why there are A&B files for band M16. FIXME!
# Anyway, the absolute response differences are small, below 0.05
# LOG.debug("paths = %s", str(self.bandfilenames))
path = self.bandfilenames[self.bandname]
if not os.path.exists(path):
raise IOError("Couldn't find an existing file for this band ({band}): {path}".format(
band=self.bandname, path=path))
self.filename = path
return | [
"def",
"_get_bandfile",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"# Need to understand why there are A&B files for band M16. FIXME!",
"# Anyway, the absolute response differences are small, below 0.05",
"# LOG.debug(\"paths = %s\", str(self.bandfilenames))",
"path",
"=",
"self"... | Get the VIIRS rsr filename | [
"Get",
"the",
"VIIRS",
"rsr",
"filename"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/viirs_rsr.py#L140-L154 | train | 29,241 |
pytroll/pyspectral | rsr_convert_scripts/viirs_rsr.py | ViirsRSR._load | def _load(self, scale=0.001):
"""Load the VIIRS RSR data for the band requested"""
if self.bandname == 'DNB':
header_lines_to_skip = N_HEADER_LINES_DNB[self.platform_name]
else:
header_lines_to_skip = N_HEADER_LINES[self.platform_name]
try:
data = np.genfromtxt(self.filename,
unpack=True, skip_header=header_lines_to_skip,
names=NAMES1[self.platform_name],
dtype=DTYPE1[self.platform_name])
except ValueError:
data = np.genfromtxt(self.filename,
unpack=True, skip_header=N_HEADER_LINES[
self.platform_name],
names=NAMES2[self.platform_name],
dtype=DTYPE2[self.platform_name])
wavelength = data['wavelength'] * scale
response = data['response']
det = data['detector']
detectors = {}
for idx in range(int(max(det))):
detectors["det-{0:d}".format(idx + 1)] = {}
detectors[
"det-{0:d}".format(idx + 1)]['wavelength'] = np.repeat(wavelength, np.equal(det, idx + 1))
detectors[
"det-{0:d}".format(idx + 1)]['response'] = np.repeat(response, np.equal(det, idx + 1))
self.rsr = detectors | python | def _load(self, scale=0.001):
"""Load the VIIRS RSR data for the band requested"""
if self.bandname == 'DNB':
header_lines_to_skip = N_HEADER_LINES_DNB[self.platform_name]
else:
header_lines_to_skip = N_HEADER_LINES[self.platform_name]
try:
data = np.genfromtxt(self.filename,
unpack=True, skip_header=header_lines_to_skip,
names=NAMES1[self.platform_name],
dtype=DTYPE1[self.platform_name])
except ValueError:
data = np.genfromtxt(self.filename,
unpack=True, skip_header=N_HEADER_LINES[
self.platform_name],
names=NAMES2[self.platform_name],
dtype=DTYPE2[self.platform_name])
wavelength = data['wavelength'] * scale
response = data['response']
det = data['detector']
detectors = {}
for idx in range(int(max(det))):
detectors["det-{0:d}".format(idx + 1)] = {}
detectors[
"det-{0:d}".format(idx + 1)]['wavelength'] = np.repeat(wavelength, np.equal(det, idx + 1))
detectors[
"det-{0:d}".format(idx + 1)]['response'] = np.repeat(response, np.equal(det, idx + 1))
self.rsr = detectors | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"0.001",
")",
":",
"if",
"self",
".",
"bandname",
"==",
"'DNB'",
":",
"header_lines_to_skip",
"=",
"N_HEADER_LINES_DNB",
"[",
"self",
".",
"platform_name",
"]",
"else",
":",
"header_lines_to_skip",
"=",
"N_HEAD... | Load the VIIRS RSR data for the band requested | [
"Load",
"the",
"VIIRS",
"RSR",
"data",
"for",
"the",
"band",
"requested"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/viirs_rsr.py#L156-L187 | train | 29,242 |
pytroll/pyspectral | rsr_convert_scripts/msi_reader.py | MsiRSR._load | def _load(self, scale=0.001):
"""Load the Sentinel-2 MSI relative spectral responses
"""
with open_workbook(self.path) as wb_:
for sheet in wb_.sheets():
if sheet.name not in SHEET_HEADERS.keys():
continue
plt_short_name = PLATFORM_SHORT_NAME.get(self.platform_name)
if plt_short_name != SHEET_HEADERS.get(sheet.name):
continue
wvl = sheet.col_values(0, 1)
for idx in range(1, sheet.row_len(0)):
ch_name = MSI_BAND_NAMES[plt_short_name].get(str(sheet.col_values(idx, 0, 1)[0]))
if ch_name != self.bandname:
continue
resp = sheet.col_values(idx, 1)
resp = np.array(resp)
resp = np.where(resp == '', 0, resp).astype('float32')
mask = np.less_equal(resp, 0.00001)
wvl0 = np.ma.masked_array(wvl, mask=mask)
wvl_mask = np.ma.masked_outside(wvl, wvl0.min() - 2, wvl0.max() + 2)
wvl = wvl_mask.compressed()
resp = np.ma.masked_array(resp, mask=wvl_mask.mask).compressed()
self.rsr = {'wavelength': wvl / 1000., 'response': resp}
break
break | python | def _load(self, scale=0.001):
"""Load the Sentinel-2 MSI relative spectral responses
"""
with open_workbook(self.path) as wb_:
for sheet in wb_.sheets():
if sheet.name not in SHEET_HEADERS.keys():
continue
plt_short_name = PLATFORM_SHORT_NAME.get(self.platform_name)
if plt_short_name != SHEET_HEADERS.get(sheet.name):
continue
wvl = sheet.col_values(0, 1)
for idx in range(1, sheet.row_len(0)):
ch_name = MSI_BAND_NAMES[plt_short_name].get(str(sheet.col_values(idx, 0, 1)[0]))
if ch_name != self.bandname:
continue
resp = sheet.col_values(idx, 1)
resp = np.array(resp)
resp = np.where(resp == '', 0, resp).astype('float32')
mask = np.less_equal(resp, 0.00001)
wvl0 = np.ma.masked_array(wvl, mask=mask)
wvl_mask = np.ma.masked_outside(wvl, wvl0.min() - 2, wvl0.max() + 2)
wvl = wvl_mask.compressed()
resp = np.ma.masked_array(resp, mask=wvl_mask.mask).compressed()
self.rsr = {'wavelength': wvl / 1000., 'response': resp}
break
break | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"0.001",
")",
":",
"with",
"open_workbook",
"(",
"self",
".",
"path",
")",
"as",
"wb_",
":",
"for",
"sheet",
"in",
"wb_",
".",
"sheets",
"(",
")",
":",
"if",
"sheet",
".",
"name",
"not",
"in",
"SHEE... | Load the Sentinel-2 MSI relative spectral responses | [
"Load",
"the",
"Sentinel",
"-",
"2",
"MSI",
"relative",
"spectral",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/msi_reader.py#L95-L127 | train | 29,243 |
pytroll/pyspectral | rsr_convert_scripts/slstr_rsr.py | SlstrRSR._load | def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.requested_band_filename, 'r')
wvl = ncf.variables['wavelength'][:] * scale
resp = ncf.variables['response'][:]
self.rsr = {'wavelength': wvl, 'response': resp} | python | def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.requested_band_filename, 'r')
wvl = ncf.variables['wavelength'][:] * scale
resp = ncf.variables['response'][:]
self.rsr = {'wavelength': wvl, 'response': resp} | [
"def",
"_load",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"LOG",
".",
"debug",
"(",
"\"File: %s\"",
",",
"str",
"(",
"self",
".",
"requested_band_filename",
")",
")",
"ncf",
"=",
"Dataset",
"(",
"self",
".",
"requested_band_filename",
",",
"'r'",
... | Load the SLSTR relative spectral responses | [
"Load",
"the",
"SLSTR",
"relative",
"spectral",
"responses"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/rsr_convert_scripts/slstr_rsr.py#L69-L79 | train | 29,244 |
pytroll/pyspectral | pyspectral/config.py | get_config | def get_config():
"""Get the configuration from file"""
if CONFIG_FILE is not None:
configfile = CONFIG_FILE
else:
configfile = BUILTIN_CONFIG_FILE
config = {}
with open(configfile, 'r') as fp_:
config = recursive_dict_update(config, yaml.load(fp_, Loader=UnsafeLoader))
app_dirs = AppDirs('pyspectral', 'pytroll')
user_datadir = app_dirs.user_data_dir
config['rsr_dir'] = expanduser(config.get('rsr_dir', user_datadir))
config['rayleigh_dir'] = expanduser(config.get('rayleigh_dir', user_datadir))
return config | python | def get_config():
"""Get the configuration from file"""
if CONFIG_FILE is not None:
configfile = CONFIG_FILE
else:
configfile = BUILTIN_CONFIG_FILE
config = {}
with open(configfile, 'r') as fp_:
config = recursive_dict_update(config, yaml.load(fp_, Loader=UnsafeLoader))
app_dirs = AppDirs('pyspectral', 'pytroll')
user_datadir = app_dirs.user_data_dir
config['rsr_dir'] = expanduser(config.get('rsr_dir', user_datadir))
config['rayleigh_dir'] = expanduser(config.get('rayleigh_dir', user_datadir))
return config | [
"def",
"get_config",
"(",
")",
":",
"if",
"CONFIG_FILE",
"is",
"not",
"None",
":",
"configfile",
"=",
"CONFIG_FILE",
"else",
":",
"configfile",
"=",
"BUILTIN_CONFIG_FILE",
"config",
"=",
"{",
"}",
"with",
"open",
"(",
"configfile",
",",
"'r'",
")",
"as",
... | Get the configuration from file | [
"Get",
"the",
"configuration",
"from",
"file"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/config.py#L71-L87 | train | 29,245 |
pytroll/pyspectral | pyspectral/rayleigh.py | Rayleigh._get_lutfiles_version | def _get_lutfiles_version(self):
"""Check the version of the atm correction luts from the version file in the
specific aerosol correction directory
"""
basedir = RAYLEIGH_LUT_DIRS[self._aerosol_type]
lutfiles_version_path = os.path.join(basedir,
ATM_CORRECTION_LUT_VERSION[self._aerosol_type]['filename'])
if not os.path.exists(lutfiles_version_path):
return "v0.0.0"
with open(lutfiles_version_path, 'r') as fpt:
# Get the version from the file
return fpt.readline().strip() | python | def _get_lutfiles_version(self):
"""Check the version of the atm correction luts from the version file in the
specific aerosol correction directory
"""
basedir = RAYLEIGH_LUT_DIRS[self._aerosol_type]
lutfiles_version_path = os.path.join(basedir,
ATM_CORRECTION_LUT_VERSION[self._aerosol_type]['filename'])
if not os.path.exists(lutfiles_version_path):
return "v0.0.0"
with open(lutfiles_version_path, 'r') as fpt:
# Get the version from the file
return fpt.readline().strip() | [
"def",
"_get_lutfiles_version",
"(",
"self",
")",
":",
"basedir",
"=",
"RAYLEIGH_LUT_DIRS",
"[",
"self",
".",
"_aerosol_type",
"]",
"lutfiles_version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"ATM_CORRECTION_LUT_VERSION",
"[",
"self",
".",... | Check the version of the atm correction luts from the version file in the
specific aerosol correction directory | [
"Check",
"the",
"version",
"of",
"the",
"atm",
"correction",
"luts",
"from",
"the",
"version",
"file",
"in",
"the",
"specific",
"aerosol",
"correction",
"directory"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rayleigh.py#L147-L161 | train | 29,246 |
pytroll/pyspectral | pyspectral/rayleigh.py | Rayleigh.get_effective_wavelength | def get_effective_wavelength(self, bandname):
"""Get the effective wavelength with Rayleigh scattering in mind"""
try:
rsr = RelativeSpectralResponse(self.platform_name, self.sensor)
except(IOError, OSError):
LOG.exception(
"No spectral responses for this platform and sensor: %s %s", self.platform_name, self.sensor)
if isinstance(bandname, (float, integer_types)):
LOG.warning(
"Effective wavelength is set to the requested band wavelength = %f", bandname)
return bandname
msg = ("Can't get effective wavelength for band %s on platform %s and sensor %s" %
(str(bandname), self.platform_name, self.sensor))
raise KeyError(msg)
if isinstance(bandname, str):
bandname = BANDNAMES.get(self.sensor, BANDNAMES['generic']).get(bandname, bandname)
elif isinstance(bandname, (float, integer_types)):
if not(0.4 < bandname < 0.8):
raise BandFrequencyOutOfRange(
'Requested band frequency should be between 0.4 and 0.8 microns!')
bandname = get_bandname_from_wavelength(self.sensor, bandname, rsr.rsr)
wvl, resp = rsr.rsr[bandname][
'det-1']['wavelength'], rsr.rsr[bandname]['det-1']['response']
cwvl = get_central_wave(wvl, resp, weight=1. / wvl**4)
LOG.debug("Band name: %s Effective wavelength: %f", bandname, cwvl)
return cwvl | python | def get_effective_wavelength(self, bandname):
"""Get the effective wavelength with Rayleigh scattering in mind"""
try:
rsr = RelativeSpectralResponse(self.platform_name, self.sensor)
except(IOError, OSError):
LOG.exception(
"No spectral responses for this platform and sensor: %s %s", self.platform_name, self.sensor)
if isinstance(bandname, (float, integer_types)):
LOG.warning(
"Effective wavelength is set to the requested band wavelength = %f", bandname)
return bandname
msg = ("Can't get effective wavelength for band %s on platform %s and sensor %s" %
(str(bandname), self.platform_name, self.sensor))
raise KeyError(msg)
if isinstance(bandname, str):
bandname = BANDNAMES.get(self.sensor, BANDNAMES['generic']).get(bandname, bandname)
elif isinstance(bandname, (float, integer_types)):
if not(0.4 < bandname < 0.8):
raise BandFrequencyOutOfRange(
'Requested band frequency should be between 0.4 and 0.8 microns!')
bandname = get_bandname_from_wavelength(self.sensor, bandname, rsr.rsr)
wvl, resp = rsr.rsr[bandname][
'det-1']['wavelength'], rsr.rsr[bandname]['det-1']['response']
cwvl = get_central_wave(wvl, resp, weight=1. / wvl**4)
LOG.debug("Band name: %s Effective wavelength: %f", bandname, cwvl)
return cwvl | [
"def",
"get_effective_wavelength",
"(",
"self",
",",
"bandname",
")",
":",
"try",
":",
"rsr",
"=",
"RelativeSpectralResponse",
"(",
"self",
".",
"platform_name",
",",
"self",
".",
"sensor",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"LOG",
".... | Get the effective wavelength with Rayleigh scattering in mind | [
"Get",
"the",
"effective",
"wavelength",
"with",
"Rayleigh",
"scattering",
"in",
"mind"
] | fd296c0e0bdf5364fa180134a1292665d6bc50a3 | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/rayleigh.py#L163-L193 | train | 29,247 |
grst/geos | geos/geometry.py | griditer | def griditer(x, y, ncol, nrow=None, step=1):
"""
Iterate through a grid of tiles.
Args:
x (int): x start-coordinate
y (int): y start-coordinate
ncol (int): number of tile columns
nrow (int): number of tile rows. If not specified, this
defaults to ncol, s.t. a quadratic region is
generated
step (int): clear. Analogous to range().
Yields:
Tuple: all tuples (x, y) in the region delimited by
(x, y), (x + ncol, y + ncol).
"""
if nrow is None:
nrow = ncol
yield from itertools.product(range(x, x + ncol, step),
range(y, y + nrow, step)) | python | def griditer(x, y, ncol, nrow=None, step=1):
"""
Iterate through a grid of tiles.
Args:
x (int): x start-coordinate
y (int): y start-coordinate
ncol (int): number of tile columns
nrow (int): number of tile rows. If not specified, this
defaults to ncol, s.t. a quadratic region is
generated
step (int): clear. Analogous to range().
Yields:
Tuple: all tuples (x, y) in the region delimited by
(x, y), (x + ncol, y + ncol).
"""
if nrow is None:
nrow = ncol
yield from itertools.product(range(x, x + ncol, step),
range(y, y + nrow, step)) | [
"def",
"griditer",
"(",
"x",
",",
"y",
",",
"ncol",
",",
"nrow",
"=",
"None",
",",
"step",
"=",
"1",
")",
":",
"if",
"nrow",
"is",
"None",
":",
"nrow",
"=",
"ncol",
"yield",
"from",
"itertools",
".",
"product",
"(",
"range",
"(",
"x",
",",
"x",... | Iterate through a grid of tiles.
Args:
x (int): x start-coordinate
y (int): y start-coordinate
ncol (int): number of tile columns
nrow (int): number of tile rows. If not specified, this
defaults to ncol, s.t. a quadratic region is
generated
step (int): clear. Analogous to range().
Yields:
Tuple: all tuples (x, y) in the region delimited by
(x, y), (x + ncol, y + ncol). | [
"Iterate",
"through",
"a",
"grid",
"of",
"tiles",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/geometry.py#L37-L58 | train | 29,248 |
grst/geos | geos/geometry.py | bboxiter | def bboxiter(tile_bounds, tiles_per_row_per_region=1):
"""
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
See `kml` module description for more details. Leaving the
default value '1' simply yields all tiles in the bounding box.
Note:
If the number of regions would not be an integer due to specification
of the `tiles_per_row_per_region` parameter, the boundaries will
be rounded to the next smaller or next larger integer respectively.
Example:
We have the following bounding box with size 2x2 and set
tiles_per_row_per_region = 2, delimited by the coordinates (x, y)::
(5,5)--- ---
| |
| |
| |
--- ---(9,7)
Although this could be represented in one single region with two
tiles per row, it will create four regions::
(2,2)--- --- (5/2 = 2.5 -> 2, 5/2 = 2.5 -> 2)
| | |
--- ---
| | |
--- ---(5,4) (9/2 = 4.5 -> 5, 7/2 = 3.5 -> 4)
Yields:
Tuple: all tuples (x, y) in the region delimited by the TileBB
"""
x_lower = math.floor(tile_bounds.min.x / tiles_per_row_per_region)
y_lower = math.floor(tile_bounds.min.y / tiles_per_row_per_region)
ncol = math.ceil(tile_bounds.max.x / tiles_per_row_per_region) - x_lower
nrow = math.ceil(tile_bounds.max.y / tiles_per_row_per_region) - y_lower
yield from griditer(x_lower, y_lower, ncol, nrow) | python | def bboxiter(tile_bounds, tiles_per_row_per_region=1):
"""
Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
See `kml` module description for more details. Leaving the
default value '1' simply yields all tiles in the bounding box.
Note:
If the number of regions would not be an integer due to specification
of the `tiles_per_row_per_region` parameter, the boundaries will
be rounded to the next smaller or next larger integer respectively.
Example:
We have the following bounding box with size 2x2 and set
tiles_per_row_per_region = 2, delimited by the coordinates (x, y)::
(5,5)--- ---
| |
| |
| |
--- ---(9,7)
Although this could be represented in one single region with two
tiles per row, it will create four regions::
(2,2)--- --- (5/2 = 2.5 -> 2, 5/2 = 2.5 -> 2)
| | |
--- ---
| | |
--- ---(5,4) (9/2 = 4.5 -> 5, 7/2 = 3.5 -> 4)
Yields:
Tuple: all tuples (x, y) in the region delimited by the TileBB
"""
x_lower = math.floor(tile_bounds.min.x / tiles_per_row_per_region)
y_lower = math.floor(tile_bounds.min.y / tiles_per_row_per_region)
ncol = math.ceil(tile_bounds.max.x / tiles_per_row_per_region) - x_lower
nrow = math.ceil(tile_bounds.max.y / tiles_per_row_per_region) - y_lower
yield from griditer(x_lower, y_lower, ncol, nrow) | [
"def",
"bboxiter",
"(",
"tile_bounds",
",",
"tiles_per_row_per_region",
"=",
"1",
")",
":",
"x_lower",
"=",
"math",
".",
"floor",
"(",
"tile_bounds",
".",
"min",
".",
"x",
"/",
"tiles_per_row_per_region",
")",
"y_lower",
"=",
"math",
".",
"floor",
"(",
"ti... | Iterate through a grid of regions defined by a TileBB.
Args:
tile_bounds (GridBB):
tiles_per_row_per_region: Combine multiple tiles in one region.
E.g. if set to two, four tiles will be combined in one region.
See `kml` module description for more details. Leaving the
default value '1' simply yields all tiles in the bounding box.
Note:
If the number of regions would not be an integer due to specification
of the `tiles_per_row_per_region` parameter, the boundaries will
be rounded to the next smaller or next larger integer respectively.
Example:
We have the following bounding box with size 2x2 and set
tiles_per_row_per_region = 2, delimited by the coordinates (x, y)::
(5,5)--- ---
| |
| |
| |
--- ---(9,7)
Although this could be represented in one single region with two
tiles per row, it will create four regions::
(2,2)--- --- (5/2 = 2.5 -> 2, 5/2 = 2.5 -> 2)
| | |
--- ---
| | |
--- ---(5,4) (9/2 = 4.5 -> 5, 7/2 = 3.5 -> 4)
Yields:
Tuple: all tuples (x, y) in the region delimited by the TileBB | [
"Iterate",
"through",
"a",
"grid",
"of",
"regions",
"defined",
"by",
"a",
"TileBB",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/geometry.py#L61-L105 | train | 29,249 |
grst/geos | geos/geometry.py | TileCoordinate.resolution | def resolution(self):
"""
Get the tile resolution at the current position.
The scale in WG84 depends on
* the zoom level (obviously)
* the latitude
* the tile size
References:
* http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale
* http://gis.stackexchange.com/questions/7430/what-ratio-scales-do-google-maps-zoom-levels-correspond-to
Returns:
float: meters per pixel
"""
geo_coords = self.to_geographic()
resolution = abs(_initialresolution * math.cos(geo_coords.lat * _pi_180) / (2**self.zoom))
return resolution | python | def resolution(self):
"""
Get the tile resolution at the current position.
The scale in WG84 depends on
* the zoom level (obviously)
* the latitude
* the tile size
References:
* http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale
* http://gis.stackexchange.com/questions/7430/what-ratio-scales-do-google-maps-zoom-levels-correspond-to
Returns:
float: meters per pixel
"""
geo_coords = self.to_geographic()
resolution = abs(_initialresolution * math.cos(geo_coords.lat * _pi_180) / (2**self.zoom))
return resolution | [
"def",
"resolution",
"(",
"self",
")",
":",
"geo_coords",
"=",
"self",
".",
"to_geographic",
"(",
")",
"resolution",
"=",
"abs",
"(",
"_initialresolution",
"*",
"math",
".",
"cos",
"(",
"geo_coords",
".",
"lat",
"*",
"_pi_180",
")",
"/",
"(",
"2",
"**"... | Get the tile resolution at the current position.
The scale in WG84 depends on
* the zoom level (obviously)
* the latitude
* the tile size
References:
* http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale
* http://gis.stackexchange.com/questions/7430/what-ratio-scales-do-google-maps-zoom-levels-correspond-to
Returns:
float: meters per pixel | [
"Get",
"the",
"tile",
"resolution",
"at",
"the",
"current",
"position",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/geometry.py#L295-L313 | train | 29,250 |
grst/geos | geos/geometry.py | RegionCoordinate.get_tiles | def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
yield TileCoordinate(self.root_tile.zoom, x, y) | python | def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
yield TileCoordinate(self.root_tile.zoom, x, y) | [
"def",
"get_tiles",
"(",
"self",
")",
":",
"for",
"x",
",",
"y",
"in",
"griditer",
"(",
"self",
".",
"root_tile",
".",
"x",
",",
"self",
".",
"root_tile",
".",
"y",
",",
"ncol",
"=",
"self",
".",
"tiles_per_row",
")",
":",
"yield",
"TileCoordinate",
... | Get all TileCoordinates contained in the region | [
"Get",
"all",
"TileCoordinates",
"contained",
"in",
"the",
"region"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/geometry.py#L356-L359 | train | 29,251 |
grst/geos | geos/server.py | maps_json | def maps_json():
"""
Generates a json object which serves as bridge between
the web interface and the map source collection.
All attributes relevant for openlayers are converted into
JSON and served through this route.
Returns:
Response: All map sources as JSON object.
"""
map_sources = {
id: {
"id": map_source.id,
"name": map_source.name,
"folder": map_source.folder,
"min_zoom": map_source.min_zoom,
"max_zoom": map_source.max_zoom,
"layers": [
{
"min_zoom": layer.min_zoom,
"max_zoom": layer.max_zoom,
"tile_url": layer.tile_url.replace("$", ""),
} for layer in map_source.layers
]
} for id, map_source in app.config["mapsources"].items()
}
return jsonify(map_sources) | python | def maps_json():
"""
Generates a json object which serves as bridge between
the web interface and the map source collection.
All attributes relevant for openlayers are converted into
JSON and served through this route.
Returns:
Response: All map sources as JSON object.
"""
map_sources = {
id: {
"id": map_source.id,
"name": map_source.name,
"folder": map_source.folder,
"min_zoom": map_source.min_zoom,
"max_zoom": map_source.max_zoom,
"layers": [
{
"min_zoom": layer.min_zoom,
"max_zoom": layer.max_zoom,
"tile_url": layer.tile_url.replace("$", ""),
} for layer in map_source.layers
]
} for id, map_source in app.config["mapsources"].items()
}
return jsonify(map_sources) | [
"def",
"maps_json",
"(",
")",
":",
"map_sources",
"=",
"{",
"id",
":",
"{",
"\"id\"",
":",
"map_source",
".",
"id",
",",
"\"name\"",
":",
"map_source",
".",
"name",
",",
"\"folder\"",
":",
"map_source",
".",
"folder",
",",
"\"min_zoom\"",
":",
"map_sourc... | Generates a json object which serves as bridge between
the web interface and the map source collection.
All attributes relevant for openlayers are converted into
JSON and served through this route.
Returns:
Response: All map sources as JSON object. | [
"Generates",
"a",
"json",
"object",
"which",
"serves",
"as",
"bridge",
"between",
"the",
"web",
"interface",
"and",
"the",
"map",
"source",
"collection",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L25-L53 | train | 29,252 |
grst/geos | geos/server.py | map_to_pdf | def map_to_pdf(map_source, zoom, x, y, width, height):
"""
Generate a PDF at the given position.
Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate
width (float): width of the pdf in mm
height (float): height of the pdf in mm
Returns:
"""
map_source = app.config["mapsources"][map_source]
pdf_file = print_map(map_source, x=float(x), y=float(y),
zoom=int(zoom), width=float(width), height=float(height), format='pdf')
return send_file(pdf_file,
attachment_filename="map.pdf",
as_attachment=True) | python | def map_to_pdf(map_source, zoom, x, y, width, height):
"""
Generate a PDF at the given position.
Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate
width (float): width of the pdf in mm
height (float): height of the pdf in mm
Returns:
"""
map_source = app.config["mapsources"][map_source]
pdf_file = print_map(map_source, x=float(x), y=float(y),
zoom=int(zoom), width=float(width), height=float(height), format='pdf')
return send_file(pdf_file,
attachment_filename="map.pdf",
as_attachment=True) | [
"def",
"map_to_pdf",
"(",
"map_source",
",",
"zoom",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"map_source",
"=",
"app",
".",
"config",
"[",
"\"mapsources\"",
"]",
"[",
"map_source",
"]",
"pdf_file",
"=",
"print_map",
"(",
"map_source",
... | Generate a PDF at the given position.
Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate
width (float): width of the pdf in mm
height (float): height of the pdf in mm
Returns: | [
"Generate",
"a",
"PDF",
"at",
"the",
"given",
"position",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L57-L77 | train | 29,253 |
grst/geos | geos/server.py | kml_master | def kml_master():
"""KML master document for loading all maps in Google Earth"""
kml_doc = KMLMaster(app.config["url_formatter"], app.config["mapsources"].values())
return kml_response(kml_doc) | python | def kml_master():
"""KML master document for loading all maps in Google Earth"""
kml_doc = KMLMaster(app.config["url_formatter"], app.config["mapsources"].values())
return kml_response(kml_doc) | [
"def",
"kml_master",
"(",
")",
":",
"kml_doc",
"=",
"KMLMaster",
"(",
"app",
".",
"config",
"[",
"\"url_formatter\"",
"]",
",",
"app",
".",
"config",
"[",
"\"mapsources\"",
"]",
".",
"values",
"(",
")",
")",
"return",
"kml_response",
"(",
"kml_doc",
")"
... | KML master document for loading all maps in Google Earth | [
"KML",
"master",
"document",
"for",
"loading",
"all",
"maps",
"in",
"Google",
"Earth"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L81-L84 | train | 29,254 |
grst/geos | geos/server.py | kml_map_root | def kml_map_root(map_source):
"""KML for a given map"""
map = app.config["mapsources"][map_source]
kml_doc = KMLMapRoot(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"])
return kml_response(kml_doc) | python | def kml_map_root(map_source):
"""KML for a given map"""
map = app.config["mapsources"][map_source]
kml_doc = KMLMapRoot(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"])
return kml_response(kml_doc) | [
"def",
"kml_map_root",
"(",
"map_source",
")",
":",
"map",
"=",
"app",
".",
"config",
"[",
"\"mapsources\"",
"]",
"[",
"map_source",
"]",
"kml_doc",
"=",
"KMLMapRoot",
"(",
"app",
".",
"config",
"[",
"\"url_formatter\"",
"]",
",",
"map",
",",
"app",
".",... | KML for a given map | [
"KML",
"for",
"a",
"given",
"map"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L88-L92 | train | 29,255 |
grst/geos | geos/server.py | kml_region | def kml_region(map_source, z, x, y):
"""KML region fetched by a Google Earth network link. """
map = app.config["mapsources"][map_source]
kml_doc = KMLRegion(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"],
z, x, y)
return kml_response(kml_doc) | python | def kml_region(map_source, z, x, y):
"""KML region fetched by a Google Earth network link. """
map = app.config["mapsources"][map_source]
kml_doc = KMLRegion(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"],
z, x, y)
return kml_response(kml_doc) | [
"def",
"kml_region",
"(",
"map_source",
",",
"z",
",",
"x",
",",
"y",
")",
":",
"map",
"=",
"app",
".",
"config",
"[",
"\"mapsources\"",
"]",
"[",
"map_source",
"]",
"kml_doc",
"=",
"KMLRegion",
"(",
"app",
".",
"config",
"[",
"\"url_formatter\"",
"]",... | KML region fetched by a Google Earth network link. | [
"KML",
"region",
"fetched",
"by",
"a",
"Google",
"Earth",
"network",
"link",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L96-L101 | train | 29,256 |
grst/geos | pykml_geos/util.py | count_elements | def count_elements(doc):
"Counts the number of times each element is used in a document"
summary = {}
for el in doc.iter():
try:
namespace, element_name = re.search('^{(.+)}(.+)$', el.tag).groups()
except:
namespace = None
element_name = el.tag
if not summary.has_key(namespace):
summary[namespace] = {}
if not summary[namespace].has_key(element_name):
summary[namespace][element_name] = 1
else:
summary[namespace][element_name] += 1
return summary | python | def count_elements(doc):
"Counts the number of times each element is used in a document"
summary = {}
for el in doc.iter():
try:
namespace, element_name = re.search('^{(.+)}(.+)$', el.tag).groups()
except:
namespace = None
element_name = el.tag
if not summary.has_key(namespace):
summary[namespace] = {}
if not summary[namespace].has_key(element_name):
summary[namespace][element_name] = 1
else:
summary[namespace][element_name] += 1
return summary | [
"def",
"count_elements",
"(",
"doc",
")",
":",
"summary",
"=",
"{",
"}",
"for",
"el",
"in",
"doc",
".",
"iter",
"(",
")",
":",
"try",
":",
"namespace",
",",
"element_name",
"=",
"re",
".",
"search",
"(",
"'^{(.+)}(.+)$'",
",",
"el",
".",
"tag",
")"... | Counts the number of times each element is used in a document | [
"Counts",
"the",
"number",
"of",
"times",
"each",
"element",
"is",
"used",
"in",
"a",
"document"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/pykml_geos/util.py#L8-L23 | train | 29,257 |
grst/geos | pykml_geos/factory.py | get_factory_object_name | def get_factory_object_name(namespace):
"Returns the correct factory object for a given namespace"
factory_map = {
'http://www.opengis.net/kml/2.2': 'KML',
'http://www.w3.org/2005/Atom': 'ATOM',
'http://www.google.com/kml/ext/2.2': 'GX'
}
if namespace:
if factory_map.has_key(namespace):
factory_object_name = factory_map[namespace]
else:
factory_object_name = None
else:
# use the KML factory object as the default, if no namespace is given
factory_object_name = 'KML'
return factory_object_name | python | def get_factory_object_name(namespace):
"Returns the correct factory object for a given namespace"
factory_map = {
'http://www.opengis.net/kml/2.2': 'KML',
'http://www.w3.org/2005/Atom': 'ATOM',
'http://www.google.com/kml/ext/2.2': 'GX'
}
if namespace:
if factory_map.has_key(namespace):
factory_object_name = factory_map[namespace]
else:
factory_object_name = None
else:
# use the KML factory object as the default, if no namespace is given
factory_object_name = 'KML'
return factory_object_name | [
"def",
"get_factory_object_name",
"(",
"namespace",
")",
":",
"factory_map",
"=",
"{",
"'http://www.opengis.net/kml/2.2'",
":",
"'KML'",
",",
"'http://www.w3.org/2005/Atom'",
":",
"'ATOM'",
",",
"'http://www.google.com/kml/ext/2.2'",
":",
"'GX'",
"}",
"if",
"namespace",
... | Returns the correct factory object for a given namespace | [
"Returns",
"the",
"correct",
"factory",
"object",
"for",
"a",
"given",
"namespace"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/pykml_geos/factory.py#L39-L55 | train | 29,258 |
grst/geos | geos/kml.py | kml_element_name | def kml_element_name(grid_coords, elem_id="KML"):
"""
Create a unique element name for KML
Args:
grid_coords (GridCoordinate):
elem_id (str):
>>> kml_element_name(GridCoordinate(zoom=5, x=42, y=60), elem_id="NL")
'NL_5_42_60'
"""
return "_".join(str(x) for x in [elem_id, grid_coords.zoom, grid_coords.x, grid_coords.y]) | python | def kml_element_name(grid_coords, elem_id="KML"):
"""
Create a unique element name for KML
Args:
grid_coords (GridCoordinate):
elem_id (str):
>>> kml_element_name(GridCoordinate(zoom=5, x=42, y=60), elem_id="NL")
'NL_5_42_60'
"""
return "_".join(str(x) for x in [elem_id, grid_coords.zoom, grid_coords.x, grid_coords.y]) | [
"def",
"kml_element_name",
"(",
"grid_coords",
",",
"elem_id",
"=",
"\"KML\"",
")",
":",
"return",
"\"_\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"[",
"elem_id",
",",
"grid_coords",
".",
"zoom",
",",
"grid_coords",
".",
"x",
",",
... | Create a unique element name for KML
Args:
grid_coords (GridCoordinate):
elem_id (str):
>>> kml_element_name(GridCoordinate(zoom=5, x=42, y=60), elem_id="NL")
'NL_5_42_60' | [
"Create",
"a",
"unique",
"element",
"name",
"for",
"KML"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/kml.py#L62-L73 | train | 29,259 |
grst/geos | geos/kml.py | URLFormatter.get_abs_url | def get_abs_url(self, rel_url):
"""
Create an absolute url from a relative one.
>>> url_formatter = URLFormatter("example.com", 80)
>>> url_formatter.get_abs_url("kml_master.kml")
'http://example.com:80/kml_master.kml'
"""
rel_url = rel_url.lstrip("/")
return "{}://{}:{}/{}".format(self.url_scheme, self.host, self.port, rel_url) | python | def get_abs_url(self, rel_url):
"""
Create an absolute url from a relative one.
>>> url_formatter = URLFormatter("example.com", 80)
>>> url_formatter.get_abs_url("kml_master.kml")
'http://example.com:80/kml_master.kml'
"""
rel_url = rel_url.lstrip("/")
return "{}://{}:{}/{}".format(self.url_scheme, self.host, self.port, rel_url) | [
"def",
"get_abs_url",
"(",
"self",
",",
"rel_url",
")",
":",
"rel_url",
"=",
"rel_url",
".",
"lstrip",
"(",
"\"/\"",
")",
"return",
"\"{}://{}:{}/{}\"",
".",
"format",
"(",
"self",
".",
"url_scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
... | Create an absolute url from a relative one.
>>> url_formatter = URLFormatter("example.com", 80)
>>> url_formatter.get_abs_url("kml_master.kml")
'http://example.com:80/kml_master.kml' | [
"Create",
"an",
"absolute",
"url",
"from",
"a",
"relative",
"one",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/kml.py#L212-L221 | train | 29,260 |
grst/geos | geos/kml.py | URLFormatter.get_map_url | def get_map_url(self, mapsource, grid_coords):
""" Get URL to a map region. """
return self.get_abs_url(
"/maps/{}/{}/{}/{}.kml".format(mapsource.id, grid_coords.zoom,
grid_coords.x, grid_coords.y)) | python | def get_map_url(self, mapsource, grid_coords):
""" Get URL to a map region. """
return self.get_abs_url(
"/maps/{}/{}/{}/{}.kml".format(mapsource.id, grid_coords.zoom,
grid_coords.x, grid_coords.y)) | [
"def",
"get_map_url",
"(",
"self",
",",
"mapsource",
",",
"grid_coords",
")",
":",
"return",
"self",
".",
"get_abs_url",
"(",
"\"/maps/{}/{}/{}/{}.kml\"",
".",
"format",
"(",
"mapsource",
".",
"id",
",",
"grid_coords",
".",
"zoom",
",",
"grid_coords",
".",
"... | Get URL to a map region. | [
"Get",
"URL",
"to",
"a",
"map",
"region",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/kml.py#L226-L230 | train | 29,261 |
grst/geos | geos/kml.py | KMLMaster.add_maps | def add_maps(self, parent, root_path=""):
"""
Recursively add maps in a folder hierarchy.
Args:
parent (KMLElement): KMLElement to which we want to append child folders or maps respectively
root_path (str): path of 'parent'
"""
for mapsource in self.map_folders[root_path]['maps']:
parent.append(self.get_network_link(mapsource))
for folder in self.map_folders[root_path]['folders']:
kml_folder_obj = kml_folder(folder)
parent.append(kml_folder_obj)
self.add_maps(parent=kml_folder_obj, root_path=F_SEP.join((root_path, folder))) | python | def add_maps(self, parent, root_path=""):
"""
Recursively add maps in a folder hierarchy.
Args:
parent (KMLElement): KMLElement to which we want to append child folders or maps respectively
root_path (str): path of 'parent'
"""
for mapsource in self.map_folders[root_path]['maps']:
parent.append(self.get_network_link(mapsource))
for folder in self.map_folders[root_path]['folders']:
kml_folder_obj = kml_folder(folder)
parent.append(kml_folder_obj)
self.add_maps(parent=kml_folder_obj, root_path=F_SEP.join((root_path, folder))) | [
"def",
"add_maps",
"(",
"self",
",",
"parent",
",",
"root_path",
"=",
"\"\"",
")",
":",
"for",
"mapsource",
"in",
"self",
".",
"map_folders",
"[",
"root_path",
"]",
"[",
"'maps'",
"]",
":",
"parent",
".",
"append",
"(",
"self",
".",
"get_network_link",
... | Recursively add maps in a folder hierarchy.
Args:
parent (KMLElement): KMLElement to which we want to append child folders or maps respectively
root_path (str): path of 'parent' | [
"Recursively",
"add",
"maps",
"in",
"a",
"folder",
"hierarchy",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/kml.py#L289-L302 | train | 29,262 |
grst/geos | pykml_geos/helpers.py | separate_namespace | def separate_namespace(qname):
"Separates the namespace from the element"
import re
try:
namespace, element_name = re.search('^{(.+)}(.+)$', qname).groups()
except:
namespace = None
element_name = qname
return namespace, element_name | python | def separate_namespace(qname):
"Separates the namespace from the element"
import re
try:
namespace, element_name = re.search('^{(.+)}(.+)$', qname).groups()
except:
namespace = None
element_name = qname
return namespace, element_name | [
"def",
"separate_namespace",
"(",
"qname",
")",
":",
"import",
"re",
"try",
":",
"namespace",
",",
"element_name",
"=",
"re",
".",
"search",
"(",
"'^{(.+)}(.+)$'",
",",
"qname",
")",
".",
"groups",
"(",
")",
"except",
":",
"namespace",
"=",
"None",
"elem... | Separates the namespace from the element | [
"Separates",
"the",
"namespace",
"from",
"the",
"element"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/pykml_geos/helpers.py#L11-L19 | train | 29,263 |
grst/geos | geos/print.py | print_map | def print_map(map_source, x, y, zoom=14, width=297, height=210, dpi=300, format="pdf"):
"""
Download map tiles and stitch them together in a single image, ready for printing.
Args:
map_source (MapSource): Map to download
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
format (str): output format. Anything supported by ``Pillow.Image.save``. E.g. "pdf", "jpeg", "png".
Returns:
str: path of temporary output file.
"""
bbox = get_print_bbox(x, y, zoom, width, height, dpi)
tiles = [
get_tiles(tile_layer, bbox) for tile_layer in map_source.layers if
tile_layer.min_zoom <= zoom <= tile_layer.max_zoom
]
img = stitch_map(tiles, width, height, bbox, dpi)
outfile = NamedTemporaryFile(delete=False)
img.save(outfile, format, quality=100, dpi=(dpi, dpi))
outfile.close()
return outfile.name | python | def print_map(map_source, x, y, zoom=14, width=297, height=210, dpi=300, format="pdf"):
"""
Download map tiles and stitch them together in a single image, ready for printing.
Args:
map_source (MapSource): Map to download
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
format (str): output format. Anything supported by ``Pillow.Image.save``. E.g. "pdf", "jpeg", "png".
Returns:
str: path of temporary output file.
"""
bbox = get_print_bbox(x, y, zoom, width, height, dpi)
tiles = [
get_tiles(tile_layer, bbox) for tile_layer in map_source.layers if
tile_layer.min_zoom <= zoom <= tile_layer.max_zoom
]
img = stitch_map(tiles, width, height, bbox, dpi)
outfile = NamedTemporaryFile(delete=False)
img.save(outfile, format, quality=100, dpi=(dpi, dpi))
outfile.close()
return outfile.name | [
"def",
"print_map",
"(",
"map_source",
",",
"x",
",",
"y",
",",
"zoom",
"=",
"14",
",",
"width",
"=",
"297",
",",
"height",
"=",
"210",
",",
"dpi",
"=",
"300",
",",
"format",
"=",
"\"pdf\"",
")",
":",
"bbox",
"=",
"get_print_bbox",
"(",
"x",
",",... | Download map tiles and stitch them together in a single image, ready for printing.
Args:
map_source (MapSource): Map to download
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
format (str): output format. Anything supported by ``Pillow.Image.save``. E.g. "pdf", "jpeg", "png".
Returns:
str: path of temporary output file. | [
"Download",
"map",
"tiles",
"and",
"stitch",
"them",
"together",
"in",
"a",
"single",
"image",
"ready",
"for",
"printing",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L43-L70 | train | 29,264 |
grst/geos | geos/print.py | get_print_bbox | def get_print_bbox(x, y, zoom, width, height, dpi):
"""
Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
Returns:
GridBB: Bounding box of the map in TileCoordinates.
>>> str(get_print_bbox(4164462.1505763642, 985738.7965919945, 14, 297, 150, 120))
'<tile min: <zoom: 14, x: 9891, y: 7786>, max: <zoom: 14, x: 9897, y: 7790>>'
"""
tiles_h = width * dpi_to_dpmm(dpi) / TILE_SIZE
tiles_v = height * dpi_to_dpmm(dpi) / TILE_SIZE
mercator_coords = MercatorCoordinate(x, y)
tile_coords = mercator_coords.to_tile(zoom)
tile_bb = GridBB(zoom,
min_x=tile_coords.x - math.ceil(tiles_h / 2),
max_x=tile_coords.x + math.ceil(tiles_h / 2),
min_y=tile_coords.y - math.ceil(tiles_v / 2),
max_y=tile_coords.y + math.ceil(tiles_v / 2))
return tile_bb | python | def get_print_bbox(x, y, zoom, width, height, dpi):
"""
Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
Returns:
GridBB: Bounding box of the map in TileCoordinates.
>>> str(get_print_bbox(4164462.1505763642, 985738.7965919945, 14, 297, 150, 120))
'<tile min: <zoom: 14, x: 9891, y: 7786>, max: <zoom: 14, x: 9897, y: 7790>>'
"""
tiles_h = width * dpi_to_dpmm(dpi) / TILE_SIZE
tiles_v = height * dpi_to_dpmm(dpi) / TILE_SIZE
mercator_coords = MercatorCoordinate(x, y)
tile_coords = mercator_coords.to_tile(zoom)
tile_bb = GridBB(zoom,
min_x=tile_coords.x - math.ceil(tiles_h / 2),
max_x=tile_coords.x + math.ceil(tiles_h / 2),
min_y=tile_coords.y - math.ceil(tiles_v / 2),
max_y=tile_coords.y + math.ceil(tiles_v / 2))
return tile_bb | [
"def",
"get_print_bbox",
"(",
"x",
",",
"y",
",",
"zoom",
",",
"width",
",",
"height",
",",
"dpi",
")",
":",
"tiles_h",
"=",
"width",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")",
"/",
"TILE_SIZE",
"tiles_v",
"=",
"height",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")"... | Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
Returns:
GridBB: Bounding box of the map in TileCoordinates.
>>> str(get_print_bbox(4164462.1505763642, 985738.7965919945, 14, 297, 150, 120))
'<tile min: <zoom: 14, x: 9891, y: 7786>, max: <zoom: 14, x: 9897, y: 7790>>' | [
"Calculate",
"the",
"tile",
"bounding",
"box",
"based",
"on",
"position",
"map",
"size",
"and",
"resolution",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L73-L103 | train | 29,265 |
grst/geos | geos/print.py | download_tile | def download_tile(map_layer, zoom, x, y):
"""
Download a given tile from the tile server.
Args:
map_layer (MapLayer): MapLayer object which provides the tile-url.
zoom (int): zoom level
x (int): Tile-x-coordinate
y (int): Tile-y-coordinate
Returns:
file: temporary file containing the downloaded image.
"""
try:
tile_url = map_layer.get_tile_url(zoom, x, y)
tmp_file, headers = urllib.request.urlretrieve(tile_url)
return (x, y), tmp_file
except URLError as e:
app.logger.info("Error downloading tile x={}, y={}, z={} for layer {}: {}".format(
x, y, zoom, map_layer, e.reason))
return (x, y), pkg_resources.resource_filename("geos", "static/empty_tile.png") | python | def download_tile(map_layer, zoom, x, y):
"""
Download a given tile from the tile server.
Args:
map_layer (MapLayer): MapLayer object which provides the tile-url.
zoom (int): zoom level
x (int): Tile-x-coordinate
y (int): Tile-y-coordinate
Returns:
file: temporary file containing the downloaded image.
"""
try:
tile_url = map_layer.get_tile_url(zoom, x, y)
tmp_file, headers = urllib.request.urlretrieve(tile_url)
return (x, y), tmp_file
except URLError as e:
app.logger.info("Error downloading tile x={}, y={}, z={} for layer {}: {}".format(
x, y, zoom, map_layer, e.reason))
return (x, y), pkg_resources.resource_filename("geos", "static/empty_tile.png") | [
"def",
"download_tile",
"(",
"map_layer",
",",
"zoom",
",",
"x",
",",
"y",
")",
":",
"try",
":",
"tile_url",
"=",
"map_layer",
".",
"get_tile_url",
"(",
"zoom",
",",
"x",
",",
"y",
")",
"tmp_file",
",",
"headers",
"=",
"urllib",
".",
"request",
".",
... | Download a given tile from the tile server.
Args:
map_layer (MapLayer): MapLayer object which provides the tile-url.
zoom (int): zoom level
x (int): Tile-x-coordinate
y (int): Tile-y-coordinate
Returns:
file: temporary file containing the downloaded image. | [
"Download",
"a",
"given",
"tile",
"from",
"the",
"tile",
"server",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L106-L127 | train | 29,266 |
grst/geos | geos/print.py | get_tiles | def get_tiles(map_layer, bbox, n_workers=N_DOWNLOAD_WORKERS):
"""
Download tiles.
Args:
map_source (MapSource):
bbox (TileBB): Bounding box delimiting the map
n_workers (int): number of threads to used for downloading.
Returns:
dict of file: Dictionary mapping coordinates to temporary files.
Example::
{
(x, y) : <FileHandle>
}
"""
p = Pool(n_workers)
tiles = {}
for (x, y), tmp_file in p.imap_unordered(_download_tile_wrapper, zip(itertools.repeat(map_layer),
itertools.repeat(bbox.zoom),
*zip(*bboxiter(bbox)))):
app.logger.info("Downloaded tile x={}, y={}, z={}".format(x, y, bbox.zoom))
tiles[(x, y)] = tmp_file
return tiles | python | def get_tiles(map_layer, bbox, n_workers=N_DOWNLOAD_WORKERS):
"""
Download tiles.
Args:
map_source (MapSource):
bbox (TileBB): Bounding box delimiting the map
n_workers (int): number of threads to used for downloading.
Returns:
dict of file: Dictionary mapping coordinates to temporary files.
Example::
{
(x, y) : <FileHandle>
}
"""
p = Pool(n_workers)
tiles = {}
for (x, y), tmp_file in p.imap_unordered(_download_tile_wrapper, zip(itertools.repeat(map_layer),
itertools.repeat(bbox.zoom),
*zip(*bboxiter(bbox)))):
app.logger.info("Downloaded tile x={}, y={}, z={}".format(x, y, bbox.zoom))
tiles[(x, y)] = tmp_file
return tiles | [
"def",
"get_tiles",
"(",
"map_layer",
",",
"bbox",
",",
"n_workers",
"=",
"N_DOWNLOAD_WORKERS",
")",
":",
"p",
"=",
"Pool",
"(",
"n_workers",
")",
"tiles",
"=",
"{",
"}",
"for",
"(",
"x",
",",
"y",
")",
",",
"tmp_file",
"in",
"p",
".",
"imap_unordere... | Download tiles.
Args:
map_source (MapSource):
bbox (TileBB): Bounding box delimiting the map
n_workers (int): number of threads to used for downloading.
Returns:
dict of file: Dictionary mapping coordinates to temporary files.
Example::
{
(x, y) : <FileHandle>
} | [
"Download",
"tiles",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L135-L162 | train | 29,267 |
grst/geos | geos/print.py | stitch_map | def stitch_map(tiles, width, height, bbox, dpi):
"""
Merge tiles together into one image.
Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch
Returns:
PIL.Image: merged map.
"""
size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi)))
background = Image.new('RGBA', size, (255, 255, 255))
for layer in tiles:
layer_img = Image.new("RGBA", size)
for (x, y), tile_path in layer.items():
tile = Image.open(tile_path)
layer_img.paste(tile, ((x - bbox.min.x) * TILE_SIZE, (y - bbox.min.y) * TILE_SIZE))
background = Image.alpha_composite(background, layer_img)
add_scales_bar(background, bbox)
return background.convert("RGB") | python | def stitch_map(tiles, width, height, bbox, dpi):
"""
Merge tiles together into one image.
Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch
Returns:
PIL.Image: merged map.
"""
size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi)))
background = Image.new('RGBA', size, (255, 255, 255))
for layer in tiles:
layer_img = Image.new("RGBA", size)
for (x, y), tile_path in layer.items():
tile = Image.open(tile_path)
layer_img.paste(tile, ((x - bbox.min.x) * TILE_SIZE, (y - bbox.min.y) * TILE_SIZE))
background = Image.alpha_composite(background, layer_img)
add_scales_bar(background, bbox)
return background.convert("RGB") | [
"def",
"stitch_map",
"(",
"tiles",
",",
"width",
",",
"height",
",",
"bbox",
",",
"dpi",
")",
":",
"size",
"=",
"(",
"int",
"(",
"width",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")",
")",
",",
"int",
"(",
"height",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")",
")... | Merge tiles together into one image.
Args:
tiles (list of dict of file): tiles for each layer
width (float): page width in mm
height (height): page height in mm
dpi (dpi): resolution in dots per inch
Returns:
PIL.Image: merged map. | [
"Merge",
"tiles",
"together",
"into",
"one",
"image",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L165-L188 | train | 29,268 |
grst/geos | geos/print.py | add_scales_bar | def add_scales_bar(img, bbox):
"""
Add a scales bar to the map.
Calculates the resolution at the current latitude and
inserts the corresponding scales bar on the map.
Args:
img (Image): Image object to which the scales bar will be added.
bbox (TileBB): boundaries of the map
"""
tc = TileCoordinate(bbox.min.zoom, bbox.min.x, bbox.min.y)
meters_per_pixel = tc.resolution()
one_km_bar = int(1000 * (1 / meters_per_pixel))
col_black = (0, 0, 0)
line_start = (100, img.size[1] - 100) # px
line_end = (line_start[0] + one_km_bar, line_start[1])
whiskers_left = [line_start[0], line_start[1] - 15, line_start[0], line_start[1] + 15]
whiskers_right = [line_end[0], line_end[1] - 15, line_end[0], line_end[1] + 15]
draw = ImageDraw.Draw(img)
draw.line([line_start, line_end], fill=col_black, width=5)
draw.line(whiskers_left, fill=col_black, width=2)
draw.line(whiskers_right, fill=col_black, width=2)
draw.text((line_start[0] + 10, line_start[1] + 10), fill=col_black, text="1 km")
del draw | python | def add_scales_bar(img, bbox):
"""
Add a scales bar to the map.
Calculates the resolution at the current latitude and
inserts the corresponding scales bar on the map.
Args:
img (Image): Image object to which the scales bar will be added.
bbox (TileBB): boundaries of the map
"""
tc = TileCoordinate(bbox.min.zoom, bbox.min.x, bbox.min.y)
meters_per_pixel = tc.resolution()
one_km_bar = int(1000 * (1 / meters_per_pixel))
col_black = (0, 0, 0)
line_start = (100, img.size[1] - 100) # px
line_end = (line_start[0] + one_km_bar, line_start[1])
whiskers_left = [line_start[0], line_start[1] - 15, line_start[0], line_start[1] + 15]
whiskers_right = [line_end[0], line_end[1] - 15, line_end[0], line_end[1] + 15]
draw = ImageDraw.Draw(img)
draw.line([line_start, line_end], fill=col_black, width=5)
draw.line(whiskers_left, fill=col_black, width=2)
draw.line(whiskers_right, fill=col_black, width=2)
draw.text((line_start[0] + 10, line_start[1] + 10), fill=col_black, text="1 km")
del draw | [
"def",
"add_scales_bar",
"(",
"img",
",",
"bbox",
")",
":",
"tc",
"=",
"TileCoordinate",
"(",
"bbox",
".",
"min",
".",
"zoom",
",",
"bbox",
".",
"min",
".",
"x",
",",
"bbox",
".",
"min",
".",
"y",
")",
"meters_per_pixel",
"=",
"tc",
".",
"resolutio... | Add a scales bar to the map.
Calculates the resolution at the current latitude and
inserts the corresponding scales bar on the map.
Args:
img (Image): Image object to which the scales bar will be added.
bbox (TileBB): boundaries of the map | [
"Add",
"a",
"scales",
"bar",
"to",
"the",
"map",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L191-L218 | train | 29,269 |
grst/geos | pykml_geos/parser.py | fromstring | def fromstring(text, schema=None):
"""Parses a KML text string
This function parses a KML text string and optionally validates it against
a provided schema object"""
if schema:
parser = objectify.makeparser(schema = schema.schema)
return objectify.fromstring(text, parser=parser)
else:
return objectify.fromstring(text) | python | def fromstring(text, schema=None):
"""Parses a KML text string
This function parses a KML text string and optionally validates it against
a provided schema object"""
if schema:
parser = objectify.makeparser(schema = schema.schema)
return objectify.fromstring(text, parser=parser)
else:
return objectify.fromstring(text) | [
"def",
"fromstring",
"(",
"text",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
":",
"parser",
"=",
"objectify",
".",
"makeparser",
"(",
"schema",
"=",
"schema",
".",
"schema",
")",
"return",
"objectify",
".",
"fromstring",
"(",
"text",
",",
"p... | Parses a KML text string
This function parses a KML text string and optionally validates it against
a provided schema object | [
"Parses",
"a",
"KML",
"text",
"string",
"This",
"function",
"parses",
"a",
"KML",
"text",
"string",
"and",
"optionally",
"validates",
"it",
"against",
"a",
"provided",
"schema",
"object"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/pykml_geos/parser.py#L32-L41 | train | 29,270 |
grst/geos | pykml_geos/parser.py | parse | def parse(fileobject, schema=None):
"""Parses a file object
This functon parses a KML file object, and optionally validates it against
a provided schema.
"""
if schema:
# with validation
parser = objectify.makeparser(schema = schema.schema, strip_cdata=False)
return objectify.parse(fileobject, parser=parser)
else:
# without validation
return objectify.parse(fileobject) | python | def parse(fileobject, schema=None):
"""Parses a file object
This functon parses a KML file object, and optionally validates it against
a provided schema.
"""
if schema:
# with validation
parser = objectify.makeparser(schema = schema.schema, strip_cdata=False)
return objectify.parse(fileobject, parser=parser)
else:
# without validation
return objectify.parse(fileobject) | [
"def",
"parse",
"(",
"fileobject",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
":",
"# with validation",
"parser",
"=",
"objectify",
".",
"makeparser",
"(",
"schema",
"=",
"schema",
".",
"schema",
",",
"strip_cdata",
"=",
"False",
")",
"return",
... | Parses a file object
This functon parses a KML file object, and optionally validates it against
a provided schema. | [
"Parses",
"a",
"file",
"object",
"This",
"functon",
"parses",
"a",
"KML",
"file",
"object",
"and",
"optionally",
"validates",
"it",
"against",
"a",
"provided",
"schema",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/pykml_geos/parser.py#L43-L55 | train | 29,271 |
grst/geos | geos/mapsource.py | load_maps | def load_maps(maps_dir):
"""
Load all xml map sources from a given directory.
Args:
maps_dir: path to directory to search for maps
Returns:
dict of MapSource:
"""
maps_dir = os.path.abspath(maps_dir)
maps = {}
for root, dirnames, filenames in os.walk(maps_dir):
for filename in filenames:
if filename.endswith(".xml"):
xml_file = os.path.join(root, filename)
map = MapSource.from_xml(xml_file, maps_dir)
if map.id in maps:
raise MapSourceException("duplicate map id: {} in file {}".format(map.id, xml_file))
else:
maps[map.id] = map
return maps | python | def load_maps(maps_dir):
"""
Load all xml map sources from a given directory.
Args:
maps_dir: path to directory to search for maps
Returns:
dict of MapSource:
"""
maps_dir = os.path.abspath(maps_dir)
maps = {}
for root, dirnames, filenames in os.walk(maps_dir):
for filename in filenames:
if filename.endswith(".xml"):
xml_file = os.path.join(root, filename)
map = MapSource.from_xml(xml_file, maps_dir)
if map.id in maps:
raise MapSourceException("duplicate map id: {} in file {}".format(map.id, xml_file))
else:
maps[map.id] = map
return maps | [
"def",
"load_maps",
"(",
"maps_dir",
")",
":",
"maps_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"maps_dir",
")",
"maps",
"=",
"{",
"}",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"maps_dir",
")",
":",
"f... | Load all xml map sources from a given directory.
Args:
maps_dir: path to directory to search for maps
Returns:
dict of MapSource: | [
"Load",
"all",
"xml",
"map",
"sources",
"from",
"a",
"given",
"directory",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L11-L33 | train | 29,272 |
grst/geos | geos/mapsource.py | walk_mapsources | def walk_mapsources(mapsources, root=""):
"""
recursively walk through foldernames of mapsources.
Like os.walk, only for a list of mapsources.
Args:
mapsources (list of MapSource):
Yields:
(root, foldernames, maps)
>>> mapsources = load_maps("test/mapsources")
>>> pprint([x for x in walk_mapsources(mapsources.values())])
[('',
['asia', 'europe'],
[<MapSource: osm1 (root 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm10 (root 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/asia',
[],
[<MapSource: osm6 (asia), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe',
['france', 'germany', 'switzerland'],
[<MapSource: osm4 (eruope 1), n_layers: 1, min_zoom:1, max_zoom:18>]),
('/europe/france',
[],
[<MapSource: osm2 (europe/france 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm3 (europe/france 2), n_layers: 1, min_zoom:1, max_zoom:18>,
<MapSource: osm5 (europe/france 3), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/germany',
[],
[<MapSource: osm7 (europe/germany 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm8 (europe/germany 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/switzerland',
[],
[<MapSource: osm9 (europe/switzerland), n_layers: 1, min_zoom:5, max_zoom:18>])]
"""
def get_first_folder(path):
"""
Get the first folder in a path
> get_first_folder("europe/switzerland/bs")
europe
"""
path = path[len(root):]
path = path.lstrip(F_SEP)
return path.split(F_SEP)[0]
path_tuples = sorted(((get_first_folder(m.folder), m) for m in mapsources), key=lambda x: x[0])
groups = {k: [x for x in g] for k, g in itertools.groupby(path_tuples, lambda x: x[0])}
folders = sorted([x for x in groups.keys() if x != ""])
mapsources = sorted([t[1] for t in groups.get("", [])], key=lambda x: x.id)
yield (root, folders, mapsources)
for fd in folders:
yield from walk_mapsources([t[1] for t in groups[fd]], F_SEP.join([root, fd])) | python | def walk_mapsources(mapsources, root=""):
"""
recursively walk through foldernames of mapsources.
Like os.walk, only for a list of mapsources.
Args:
mapsources (list of MapSource):
Yields:
(root, foldernames, maps)
>>> mapsources = load_maps("test/mapsources")
>>> pprint([x for x in walk_mapsources(mapsources.values())])
[('',
['asia', 'europe'],
[<MapSource: osm1 (root 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm10 (root 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/asia',
[],
[<MapSource: osm6 (asia), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe',
['france', 'germany', 'switzerland'],
[<MapSource: osm4 (eruope 1), n_layers: 1, min_zoom:1, max_zoom:18>]),
('/europe/france',
[],
[<MapSource: osm2 (europe/france 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm3 (europe/france 2), n_layers: 1, min_zoom:1, max_zoom:18>,
<MapSource: osm5 (europe/france 3), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/germany',
[],
[<MapSource: osm7 (europe/germany 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm8 (europe/germany 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/switzerland',
[],
[<MapSource: osm9 (europe/switzerland), n_layers: 1, min_zoom:5, max_zoom:18>])]
"""
def get_first_folder(path):
"""
Get the first folder in a path
> get_first_folder("europe/switzerland/bs")
europe
"""
path = path[len(root):]
path = path.lstrip(F_SEP)
return path.split(F_SEP)[0]
path_tuples = sorted(((get_first_folder(m.folder), m) for m in mapsources), key=lambda x: x[0])
groups = {k: [x for x in g] for k, g in itertools.groupby(path_tuples, lambda x: x[0])}
folders = sorted([x for x in groups.keys() if x != ""])
mapsources = sorted([t[1] for t in groups.get("", [])], key=lambda x: x.id)
yield (root, folders, mapsources)
for fd in folders:
yield from walk_mapsources([t[1] for t in groups[fd]], F_SEP.join([root, fd])) | [
"def",
"walk_mapsources",
"(",
"mapsources",
",",
"root",
"=",
"\"\"",
")",
":",
"def",
"get_first_folder",
"(",
"path",
")",
":",
"\"\"\"\n Get the first folder in a path\n > get_first_folder(\"europe/switzerland/bs\")\n europe\n \"\"\"",
"path",
"=",... | recursively walk through foldernames of mapsources.
Like os.walk, only for a list of mapsources.
Args:
mapsources (list of MapSource):
Yields:
(root, foldernames, maps)
>>> mapsources = load_maps("test/mapsources")
>>> pprint([x for x in walk_mapsources(mapsources.values())])
[('',
['asia', 'europe'],
[<MapSource: osm1 (root 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm10 (root 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/asia',
[],
[<MapSource: osm6 (asia), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe',
['france', 'germany', 'switzerland'],
[<MapSource: osm4 (eruope 1), n_layers: 1, min_zoom:1, max_zoom:18>]),
('/europe/france',
[],
[<MapSource: osm2 (europe/france 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm3 (europe/france 2), n_layers: 1, min_zoom:1, max_zoom:18>,
<MapSource: osm5 (europe/france 3), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/germany',
[],
[<MapSource: osm7 (europe/germany 1), n_layers: 1, min_zoom:5, max_zoom:18>,
<MapSource: osm8 (europe/germany 2), n_layers: 1, min_zoom:5, max_zoom:18>]),
('/europe/switzerland',
[],
[<MapSource: osm9 (europe/switzerland), n_layers: 1, min_zoom:5, max_zoom:18>])] | [
"recursively",
"walk",
"through",
"foldernames",
"of",
"mapsources",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L36-L90 | train | 29,273 |
grst/geos | geos/mapsource.py | MapLayer.get_tile_url | def get_tile_url(self, zoom, x, y):
"""
Fill the placeholders of the tile url with zoom, x and y.
>>> ms = MapSource.from_xml("mapsources/osm.xml")
>>> ms.get_tile_url(42, 43, 44)
'http://tile.openstreetmap.org/42/43/44.png'
"""
return self.tile_url.format(**{"$z": zoom, "$x": x, "$y": y}) | python | def get_tile_url(self, zoom, x, y):
"""
Fill the placeholders of the tile url with zoom, x and y.
>>> ms = MapSource.from_xml("mapsources/osm.xml")
>>> ms.get_tile_url(42, 43, 44)
'http://tile.openstreetmap.org/42/43/44.png'
"""
return self.tile_url.format(**{"$z": zoom, "$x": x, "$y": y}) | [
"def",
"get_tile_url",
"(",
"self",
",",
"zoom",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"tile_url",
".",
"format",
"(",
"*",
"*",
"{",
"\"$z\"",
":",
"zoom",
",",
"\"$x\"",
":",
"x",
",",
"\"$y\"",
":",
"y",
"}",
")"
] | Fill the placeholders of the tile url with zoom, x and y.
>>> ms = MapSource.from_xml("mapsources/osm.xml")
>>> ms.get_tile_url(42, 43, 44)
'http://tile.openstreetmap.org/42/43/44.png' | [
"Fill",
"the",
"placeholders",
"of",
"the",
"tile",
"url",
"with",
"zoom",
"x",
"and",
"y",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L114-L122 | train | 29,274 |
grst/geos | geos/mapsource.py | MapSource.min_zoom | def min_zoom(self):
"""
Get the minimal zoom level of all layers.
Returns:
int: the minimum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
"""
zoom_levels = [map_layer.min_zoom for map_layer in self.layers]
return min(zoom_levels) | python | def min_zoom(self):
"""
Get the minimal zoom level of all layers.
Returns:
int: the minimum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
"""
zoom_levels = [map_layer.min_zoom for map_layer in self.layers]
return min(zoom_levels) | [
"def",
"min_zoom",
"(",
"self",
")",
":",
"zoom_levels",
"=",
"[",
"map_layer",
".",
"min_zoom",
"for",
"map_layer",
"in",
"self",
".",
"layers",
"]",
"return",
"min",
"(",
"zoom_levels",
")"
] | Get the minimal zoom level of all layers.
Returns:
int: the minimum of all zoom levels of all layers
Raises:
ValueError: if no layers exist | [
"Get",
"the",
"minimal",
"zoom",
"level",
"of",
"all",
"layers",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L161-L173 | train | 29,275 |
grst/geos | geos/mapsource.py | MapSource.max_zoom | def max_zoom(self):
"""
Get the maximal zoom level of all layers.
Returns:
int: the maximum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
"""
zoom_levels = [map_layer.max_zoom for map_layer in self.layers]
return max(zoom_levels) | python | def max_zoom(self):
"""
Get the maximal zoom level of all layers.
Returns:
int: the maximum of all zoom levels of all layers
Raises:
ValueError: if no layers exist
"""
zoom_levels = [map_layer.max_zoom for map_layer in self.layers]
return max(zoom_levels) | [
"def",
"max_zoom",
"(",
"self",
")",
":",
"zoom_levels",
"=",
"[",
"map_layer",
".",
"max_zoom",
"for",
"map_layer",
"in",
"self",
".",
"layers",
"]",
"return",
"max",
"(",
"zoom_levels",
")"
] | Get the maximal zoom level of all layers.
Returns:
int: the maximum of all zoom levels of all layers
Raises:
ValueError: if no layers exist | [
"Get",
"the",
"maximal",
"zoom",
"level",
"of",
"all",
"layers",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L176-L188 | train | 29,276 |
grst/geos | geos/mapsource.py | MapSource.parse_xml_boundary | def parse_xml_boundary(xml_region):
"""
Get the geographic bounds from an XML element
Args:
xml_region (Element): The <region> tag as XML Element
Returns:
GeographicBB:
"""
try:
bounds = {}
for boundary in xml_region.getchildren():
bounds[boundary.tag] = float(boundary.text)
bbox = GeographicBB(min_lon=bounds["west"], max_lon=bounds["east"],
min_lat=bounds["south"], max_lat=bounds["north"])
return bbox
except (KeyError, ValueError):
raise MapSourceException("region boundaries are invalid. ") | python | def parse_xml_boundary(xml_region):
"""
Get the geographic bounds from an XML element
Args:
xml_region (Element): The <region> tag as XML Element
Returns:
GeographicBB:
"""
try:
bounds = {}
for boundary in xml_region.getchildren():
bounds[boundary.tag] = float(boundary.text)
bbox = GeographicBB(min_lon=bounds["west"], max_lon=bounds["east"],
min_lat=bounds["south"], max_lat=bounds["north"])
return bbox
except (KeyError, ValueError):
raise MapSourceException("region boundaries are invalid. ") | [
"def",
"parse_xml_boundary",
"(",
"xml_region",
")",
":",
"try",
":",
"bounds",
"=",
"{",
"}",
"for",
"boundary",
"in",
"xml_region",
".",
"getchildren",
"(",
")",
":",
"bounds",
"[",
"boundary",
".",
"tag",
"]",
"=",
"float",
"(",
"boundary",
".",
"te... | Get the geographic bounds from an XML element
Args:
xml_region (Element): The <region> tag as XML Element
Returns:
GeographicBB: | [
"Get",
"the",
"geographic",
"bounds",
"from",
"an",
"XML",
"element"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L191-L209 | train | 29,277 |
grst/geos | geos/mapsource.py | MapSource.parse_xml_layers | def parse_xml_layers(xml_layers):
"""
Get the MapLayers from an XML element
Args:
xml_layers (Element): The <layers> tag as XML Element
Returns:
list of MapLayer:
"""
layers = []
for custom_map_source in xml_layers.getchildren():
layers.append(MapSource.parse_xml_layer(custom_map_source))
return layers | python | def parse_xml_layers(xml_layers):
"""
Get the MapLayers from an XML element
Args:
xml_layers (Element): The <layers> tag as XML Element
Returns:
list of MapLayer:
"""
layers = []
for custom_map_source in xml_layers.getchildren():
layers.append(MapSource.parse_xml_layer(custom_map_source))
return layers | [
"def",
"parse_xml_layers",
"(",
"xml_layers",
")",
":",
"layers",
"=",
"[",
"]",
"for",
"custom_map_source",
"in",
"xml_layers",
".",
"getchildren",
"(",
")",
":",
"layers",
".",
"append",
"(",
"MapSource",
".",
"parse_xml_layer",
"(",
"custom_map_source",
")"... | Get the MapLayers from an XML element
Args:
xml_layers (Element): The <layers> tag as XML Element
Returns:
list of MapLayer: | [
"Get",
"the",
"MapLayers",
"from",
"an",
"XML",
"element"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L212-L226 | train | 29,278 |
grst/geos | geos/mapsource.py | MapSource.parse_xml_layer | def parse_xml_layer(xml_custom_map_source):
"""
Get one MapLayer from an XML element
Args:
xml_custom_map_source (Element): The <customMapSource> element tag wrapped
in a <layers> tag as XML Element
Returns:
MapLayer:
"""
map_layer = MapLayer()
try:
for elem in xml_custom_map_source.getchildren():
if elem.tag == 'url':
map_layer.tile_url = elem.text
elif elem.tag == 'minZoom':
map_layer.min_zoom = int(elem.text)
elif elem.tag == 'maxZoom':
map_layer.max_zoom = int(elem.text)
except ValueError:
raise MapSourceException("minZoom/maxZoom must be an integer. ")
if map_layer.tile_url is None:
raise MapSourceException("Layer requires a tile_url parameter. ")
return map_layer | python | def parse_xml_layer(xml_custom_map_source):
"""
Get one MapLayer from an XML element
Args:
xml_custom_map_source (Element): The <customMapSource> element tag wrapped
in a <layers> tag as XML Element
Returns:
MapLayer:
"""
map_layer = MapLayer()
try:
for elem in xml_custom_map_source.getchildren():
if elem.tag == 'url':
map_layer.tile_url = elem.text
elif elem.tag == 'minZoom':
map_layer.min_zoom = int(elem.text)
elif elem.tag == 'maxZoom':
map_layer.max_zoom = int(elem.text)
except ValueError:
raise MapSourceException("minZoom/maxZoom must be an integer. ")
if map_layer.tile_url is None:
raise MapSourceException("Layer requires a tile_url parameter. ")
return map_layer | [
"def",
"parse_xml_layer",
"(",
"xml_custom_map_source",
")",
":",
"map_layer",
"=",
"MapLayer",
"(",
")",
"try",
":",
"for",
"elem",
"in",
"xml_custom_map_source",
".",
"getchildren",
"(",
")",
":",
"if",
"elem",
".",
"tag",
"==",
"'url'",
":",
"map_layer",
... | Get one MapLayer from an XML element
Args:
xml_custom_map_source (Element): The <customMapSource> element tag wrapped
in a <layers> tag as XML Element
Returns:
MapLayer: | [
"Get",
"one",
"MapLayer",
"from",
"an",
"XML",
"element"
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L229-L256 | train | 29,279 |
grst/geos | geos/mapsource.py | MapSource.from_xml | def from_xml(xml_path, mapsource_prefix=""):
"""
Create a MapSource object from a MOBAC
mapsource xml.
Args:
xml_path: path to the MOBAC mapsource xml file.
mapsource_prefix: root path of the mapsource folder.
Used to determine relative path within the maps
directory.
Note:
The Meta-Information is read from the xml
<id>, <folder>, <name> tags. If <id> is not available it defaults
to the xml file basename. If <folder> is not available if defaults to
the folder of the xml file with the `mapsource_prefix` removed.
The function first tries <url>, <minZoom>, <maxZoom> from <customMapSource>
tags within the <layers> tag. If the <layers> tag is not available,
the function tries to find <url>, <minZoom> and <maxZoom> on the top level.
If none of thie information is found, a MapSourceException is raised.
Returns:
MapSource:
Raises:
MapSourceException: when the xml file could not be parsed properly.
"""
xmldoc = xml.etree.ElementTree.parse(xml_path).getroot()
map_id = os.path.splitext(os.path.basename(xml_path))[0]
map_name = map_id
map_folder = re.sub("^" + re.escape(mapsource_prefix), "", os.path.dirname(xml_path))
bbox = None
layers = None
for elem in xmldoc.getchildren():
if elem.tag == 'id':
map_id = elem.text
elif elem.tag == 'name':
map_name = elem.text
elif elem.tag == 'folder':
map_folder = elem.text
elif elem.tag == 'region':
bbox = MapSource.parse_xml_boundary(elem)
elif elem.tag == 'layers':
layers = MapSource.parse_xml_layers(elem)
if map_folder is None:
map_folder = "" # fallback if bad specification in xml
if layers is None: # layers tag not found, expect url etc. in main xmldoc
layers = [MapSource.parse_xml_layer(xmldoc)]
ms = MapSource(map_id, map_name, map_folder, bbox=bbox)
ms.layers = layers
return ms | python | def from_xml(xml_path, mapsource_prefix=""):
"""
Create a MapSource object from a MOBAC
mapsource xml.
Args:
xml_path: path to the MOBAC mapsource xml file.
mapsource_prefix: root path of the mapsource folder.
Used to determine relative path within the maps
directory.
Note:
The Meta-Information is read from the xml
<id>, <folder>, <name> tags. If <id> is not available it defaults
to the xml file basename. If <folder> is not available if defaults to
the folder of the xml file with the `mapsource_prefix` removed.
The function first tries <url>, <minZoom>, <maxZoom> from <customMapSource>
tags within the <layers> tag. If the <layers> tag is not available,
the function tries to find <url>, <minZoom> and <maxZoom> on the top level.
If none of thie information is found, a MapSourceException is raised.
Returns:
MapSource:
Raises:
MapSourceException: when the xml file could not be parsed properly.
"""
xmldoc = xml.etree.ElementTree.parse(xml_path).getroot()
map_id = os.path.splitext(os.path.basename(xml_path))[0]
map_name = map_id
map_folder = re.sub("^" + re.escape(mapsource_prefix), "", os.path.dirname(xml_path))
bbox = None
layers = None
for elem in xmldoc.getchildren():
if elem.tag == 'id':
map_id = elem.text
elif elem.tag == 'name':
map_name = elem.text
elif elem.tag == 'folder':
map_folder = elem.text
elif elem.tag == 'region':
bbox = MapSource.parse_xml_boundary(elem)
elif elem.tag == 'layers':
layers = MapSource.parse_xml_layers(elem)
if map_folder is None:
map_folder = "" # fallback if bad specification in xml
if layers is None: # layers tag not found, expect url etc. in main xmldoc
layers = [MapSource.parse_xml_layer(xmldoc)]
ms = MapSource(map_id, map_name, map_folder, bbox=bbox)
ms.layers = layers
return ms | [
"def",
"from_xml",
"(",
"xml_path",
",",
"mapsource_prefix",
"=",
"\"\"",
")",
":",
"xmldoc",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"parse",
"(",
"xml_path",
")",
".",
"getroot",
"(",
")",
"map_id",
"=",
"os",
".",
"path",
".",
"splitext",... | Create a MapSource object from a MOBAC
mapsource xml.
Args:
xml_path: path to the MOBAC mapsource xml file.
mapsource_prefix: root path of the mapsource folder.
Used to determine relative path within the maps
directory.
Note:
The Meta-Information is read from the xml
<id>, <folder>, <name> tags. If <id> is not available it defaults
to the xml file basename. If <folder> is not available if defaults to
the folder of the xml file with the `mapsource_prefix` removed.
The function first tries <url>, <minZoom>, <maxZoom> from <customMapSource>
tags within the <layers> tag. If the <layers> tag is not available,
the function tries to find <url>, <minZoom> and <maxZoom> on the top level.
If none of thie information is found, a MapSourceException is raised.
Returns:
MapSource:
Raises:
MapSourceException: when the xml file could not be parsed properly. | [
"Create",
"a",
"MapSource",
"object",
"from",
"a",
"MOBAC",
"mapsource",
"xml",
"."
] | ea15abcc5d8f86c9051df55e489b7d941b51a638 | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/mapsource.py#L259-L315 | train | 29,280 |
python-cas/python-cas | cas.py | SingleLogoutMixin.get_saml_slos | def get_saml_slos(cls, logout_request):
"""returns saml logout ticket info"""
try:
root = etree.fromstring(logout_request)
return root.xpath(
"//samlp:SessionIndex",
namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"})
except etree.XMLSyntaxError:
return None | python | def get_saml_slos(cls, logout_request):
"""returns saml logout ticket info"""
try:
root = etree.fromstring(logout_request)
return root.xpath(
"//samlp:SessionIndex",
namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"})
except etree.XMLSyntaxError:
return None | [
"def",
"get_saml_slos",
"(",
"cls",
",",
"logout_request",
")",
":",
"try",
":",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"logout_request",
")",
"return",
"root",
".",
"xpath",
"(",
"\"//samlp:SessionIndex\"",
",",
"namespaces",
"=",
"{",
"'samlp'",
":"... | returns saml logout ticket info | [
"returns",
"saml",
"logout",
"ticket",
"info"
] | 42fc76fbd2e50f167e752eba4bf5b0df74a83978 | https://github.com/python-cas/python-cas/blob/42fc76fbd2e50f167e752eba4bf5b0df74a83978/cas.py#L18-L26 | train | 29,281 |
python-cas/python-cas | cas.py | SingleLogoutMixin.verify_logout_request | def verify_logout_request(cls, logout_request, ticket):
"""verifies the single logout request came from the CAS server
returns True if the logout_request is valid, False otherwise
"""
try:
session_index = cls.get_saml_slos(logout_request)
session_index = session_index[0].text
if session_index == ticket:
return True
else:
return False
except (AttributeError, IndexError):
return False | python | def verify_logout_request(cls, logout_request, ticket):
"""verifies the single logout request came from the CAS server
returns True if the logout_request is valid, False otherwise
"""
try:
session_index = cls.get_saml_slos(logout_request)
session_index = session_index[0].text
if session_index == ticket:
return True
else:
return False
except (AttributeError, IndexError):
return False | [
"def",
"verify_logout_request",
"(",
"cls",
",",
"logout_request",
",",
"ticket",
")",
":",
"try",
":",
"session_index",
"=",
"cls",
".",
"get_saml_slos",
"(",
"logout_request",
")",
"session_index",
"=",
"session_index",
"[",
"0",
"]",
".",
"text",
"if",
"s... | verifies the single logout request came from the CAS server
returns True if the logout_request is valid, False otherwise | [
"verifies",
"the",
"single",
"logout",
"request",
"came",
"from",
"the",
"CAS",
"server",
"returns",
"True",
"if",
"the",
"logout_request",
"is",
"valid",
"False",
"otherwise"
] | 42fc76fbd2e50f167e752eba4bf5b0df74a83978 | https://github.com/python-cas/python-cas/blob/42fc76fbd2e50f167e752eba4bf5b0df74a83978/cas.py#L29-L41 | train | 29,282 |
python-cas/python-cas | cas.py | CASClientWithSAMLV1.verify_ticket | def verify_ticket(self, ticket, **kwargs):
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure.
"""
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
page = self.fetch_saml_validation(ticket)
try:
user = None
attributes = {}
response = page.content
tree = ElementTree.fromstring(response)
# Find the authentication status
success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode')
if success is not None and success.attrib['Value'].endswith(':Success'):
# User is validated
name_identifier = tree.find('.//' + SAML_1_0_ASSERTION_NS + 'NameIdentifier')
if name_identifier is not None:
user = name_identifier.text
attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute')
for at in attrs:
if self.username_attribute in list(at.attrib.values()):
user = at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text
attributes['uid'] = user
values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue')
if len(values) > 1:
values_array = []
for v in values:
values_array.append(v.text)
attributes[at.attrib['AttributeName']] = values_array
else:
attributes[at.attrib['AttributeName']] = values[0].text
return user, attributes, None
finally:
page.close() | python | def verify_ticket(self, ticket, **kwargs):
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure.
"""
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
page = self.fetch_saml_validation(ticket)
try:
user = None
attributes = {}
response = page.content
tree = ElementTree.fromstring(response)
# Find the authentication status
success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode')
if success is not None and success.attrib['Value'].endswith(':Success'):
# User is validated
name_identifier = tree.find('.//' + SAML_1_0_ASSERTION_NS + 'NameIdentifier')
if name_identifier is not None:
user = name_identifier.text
attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute')
for at in attrs:
if self.username_attribute in list(at.attrib.values()):
user = at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text
attributes['uid'] = user
values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue')
if len(values) > 1:
values_array = []
for v in values:
values_array.append(v.text)
attributes[at.attrib['AttributeName']] = values_array
else:
attributes[at.attrib['AttributeName']] = values[0].text
return user, attributes, None
finally:
page.close() | [
"def",
"verify_ticket",
"(",
"self",
",",
"ticket",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"from",
"xml",
".",
"etree",
"import",
"ElementTree",
"except",
"ImportError",
":",
"from",
"elementtree",
"import",
"ElementTree",
"page",
"=",
"self",
".",... | Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila <carlewis@gmail.com>
Returns username and attributes on success and None,None on failure. | [
"Verifies",
"CAS",
"3",
".",
"0",
"+",
"XML",
"-",
"based",
"authentication",
"ticket",
"and",
"returns",
"extended",
"attributes",
"."
] | 42fc76fbd2e50f167e752eba4bf5b0df74a83978 | https://github.com/python-cas/python-cas/blob/42fc76fbd2e50f167e752eba4bf5b0df74a83978/cas.py#L282-L326 | train | 29,283 |
disqus/gargoyle | gargoyle/conditions.py | ConditionSet.get_field_value | def get_field_value(self, instance, field_name):
"""
Given an instance, and the name of an attribute, returns the value
of that attribute on the instance.
Default behavior will map the ``percent`` attribute to ``id``.
"""
# XXX: can we come up w/ a better API?
# Ensure we map ``percent`` to the ``id`` column
if field_name == 'percent':
field_name = 'id'
value = getattr(instance, field_name)
if callable(value):
value = value()
return value | python | def get_field_value(self, instance, field_name):
"""
Given an instance, and the name of an attribute, returns the value
of that attribute on the instance.
Default behavior will map the ``percent`` attribute to ``id``.
"""
# XXX: can we come up w/ a better API?
# Ensure we map ``percent`` to the ``id`` column
if field_name == 'percent':
field_name = 'id'
value = getattr(instance, field_name)
if callable(value):
value = value()
return value | [
"def",
"get_field_value",
"(",
"self",
",",
"instance",
",",
"field_name",
")",
":",
"# XXX: can we come up w/ a better API?",
"# Ensure we map ``percent`` to the ``id`` column",
"if",
"field_name",
"==",
"'percent'",
":",
"field_name",
"=",
"'id'",
"value",
"=",
"getattr... | Given an instance, and the name of an attribute, returns the value
of that attribute on the instance.
Default behavior will map the ``percent`` attribute to ``id``. | [
"Given",
"an",
"instance",
"and",
"the",
"name",
"of",
"an",
"attribute",
"returns",
"the",
"value",
"of",
"that",
"attribute",
"on",
"the",
"instance",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/conditions.py#L240-L254 | train | 29,284 |
disqus/gargoyle | gargoyle/conditions.py | ConditionSet.has_active_condition | def has_active_condition(self, conditions, instances):
"""
Given a list of instances, and the conditions active for
this switch, returns a boolean reprsenting if any
conditional is met, including a non-instance default.
"""
return_value = None
for instance in itertools.chain(instances, [None]):
if not self.can_execute(instance):
continue
result = self.is_active(instance, conditions)
if result is False:
return False
elif result is True:
return_value = True
return return_value | python | def has_active_condition(self, conditions, instances):
"""
Given a list of instances, and the conditions active for
this switch, returns a boolean reprsenting if any
conditional is met, including a non-instance default.
"""
return_value = None
for instance in itertools.chain(instances, [None]):
if not self.can_execute(instance):
continue
result = self.is_active(instance, conditions)
if result is False:
return False
elif result is True:
return_value = True
return return_value | [
"def",
"has_active_condition",
"(",
"self",
",",
"conditions",
",",
"instances",
")",
":",
"return_value",
"=",
"None",
"for",
"instance",
"in",
"itertools",
".",
"chain",
"(",
"instances",
",",
"[",
"None",
"]",
")",
":",
"if",
"not",
"self",
".",
"can_... | Given a list of instances, and the conditions active for
this switch, returns a boolean reprsenting if any
conditional is met, including a non-instance default. | [
"Given",
"a",
"list",
"of",
"instances",
"and",
"the",
"conditions",
"active",
"for",
"this",
"switch",
"returns",
"a",
"boolean",
"reprsenting",
"if",
"any",
"conditional",
"is",
"met",
"including",
"a",
"non",
"-",
"instance",
"default",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/conditions.py#L256-L271 | train | 29,285 |
disqus/gargoyle | gargoyle/conditions.py | ConditionSet.is_active | def is_active(self, instance, conditions):
"""
Given an instance, and the conditions active for this switch, returns
a boolean representing if the feature is active.
"""
return_value = None
for name, field in self.fields.iteritems():
field_conditions = conditions.get(self.get_namespace(), {}).get(name)
if field_conditions:
value = self.get_field_value(instance, name)
for status, condition in field_conditions:
exclude = status == EXCLUDE
if field.is_active(condition, value):
if exclude:
return False
return_value = True
else:
if exclude:
return_value = True
return return_value | python | def is_active(self, instance, conditions):
"""
Given an instance, and the conditions active for this switch, returns
a boolean representing if the feature is active.
"""
return_value = None
for name, field in self.fields.iteritems():
field_conditions = conditions.get(self.get_namespace(), {}).get(name)
if field_conditions:
value = self.get_field_value(instance, name)
for status, condition in field_conditions:
exclude = status == EXCLUDE
if field.is_active(condition, value):
if exclude:
return False
return_value = True
else:
if exclude:
return_value = True
return return_value | [
"def",
"is_active",
"(",
"self",
",",
"instance",
",",
"conditions",
")",
":",
"return_value",
"=",
"None",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"iteritems",
"(",
")",
":",
"field_conditions",
"=",
"conditions",
".",
"get",
"(",... | Given an instance, and the conditions active for this switch, returns
a boolean representing if the feature is active. | [
"Given",
"an",
"instance",
"and",
"the",
"conditions",
"active",
"for",
"this",
"switch",
"returns",
"a",
"boolean",
"representing",
"if",
"the",
"feature",
"is",
"active",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/conditions.py#L273-L292 | train | 29,286 |
disqus/gargoyle | gargoyle/nexus_modules.py | json | def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
"success": False,
"data": exc.message
}
except Switch.DoesNotExist:
response = {
"success": False,
"data": "Switch cannot be found"
}
except ValidationError, e:
response = {
"success": False,
"data": u','.join(map(unicode, e.messages)),
}
except Exception:
if settings.DEBUG:
import traceback
traceback.print_exc()
raise
return HttpResponse(dumps(response), content_type="application/json")
wrapper = wraps(func)(wrapper)
return wrapper | python | def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
"success": False,
"data": exc.message
}
except Switch.DoesNotExist:
response = {
"success": False,
"data": "Switch cannot be found"
}
except ValidationError, e:
response = {
"success": False,
"data": u','.join(map(unicode, e.messages)),
}
except Exception:
if settings.DEBUG:
import traceback
traceback.print_exc()
raise
return HttpResponse(dumps(response), content_type="application/json")
wrapper = wraps(func)(wrapper)
return wrapper | [
"def",
"json",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"{",
"\"success\"",
":",
"True",
",",
"\"data\"",
":",
"func",
"(",
"self",
","... | Decorator to make JSON views simpler | [
"Decorator",
"to",
"make",
"JSON",
"views",
"simpler"
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/nexus_modules.py#L40-L71 | train | 29,287 |
disqus/gargoyle | gargoyle/builtins.py | UserConditionSet.is_active | def is_active(self, instance, conditions):
"""
value is the current value of the switch
instance is the instance of our type
"""
if isinstance(instance, User):
return super(UserConditionSet, self).is_active(instance, conditions)
# HACK: allow is_authenticated to work on AnonymousUser
condition = conditions.get(self.get_namespace(), {}).get('is_anonymous')
if condition is not None:
return bool(condition)
return None | python | def is_active(self, instance, conditions):
"""
value is the current value of the switch
instance is the instance of our type
"""
if isinstance(instance, User):
return super(UserConditionSet, self).is_active(instance, conditions)
# HACK: allow is_authenticated to work on AnonymousUser
condition = conditions.get(self.get_namespace(), {}).get('is_anonymous')
if condition is not None:
return bool(condition)
return None | [
"def",
"is_active",
"(",
"self",
",",
"instance",
",",
"conditions",
")",
":",
"if",
"isinstance",
"(",
"instance",
",",
"User",
")",
":",
"return",
"super",
"(",
"UserConditionSet",
",",
"self",
")",
".",
"is_active",
"(",
"instance",
",",
"conditions",
... | value is the current value of the switch
instance is the instance of our type | [
"value",
"is",
"the",
"current",
"value",
"of",
"the",
"switch",
"instance",
"is",
"the",
"instance",
"of",
"our",
"type"
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/builtins.py#L41-L53 | train | 29,288 |
disqus/gargoyle | gargoyle/__init__.py | autodiscover | def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
for app in settings.INSTALLED_APPS:
# Attempt to import the app's gargoyle module.
before_import_registry = copy.copy(gargoyle._registry)
try:
import_module('%s.gargoyle' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
gargoyle._registry = before_import_registry
# load builtins
__import__('gargoyle.builtins') | python | def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
for app in settings.INSTALLED_APPS:
# Attempt to import the app's gargoyle module.
before_import_registry = copy.copy(gargoyle._registry)
try:
import_module('%s.gargoyle' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
gargoyle._registry = before_import_registry
# load builtins
__import__('gargoyle.builtins') | [
"def",
"autodiscover",
"(",
")",
":",
"import",
"copy",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"# Attempt to ... | Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want. | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"admin",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"to",
"register",
"any",
"admin",
"bits",
"they",
"may",
"want",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/__init__.py#L20-L42 | train | 29,289 |
disqus/gargoyle | gargoyle/models.py | Switch.add_condition | def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
assert isinstance(condition, basestring), 'conditions must be strings'
namespace = condition_set.get_namespace()
if namespace not in self.value:
self.value[namespace] = {}
if field_name not in self.value[namespace]:
self.value[namespace][field_name] = []
if condition not in self.value[namespace][field_name]:
self.value[namespace][field_name].append((exclude and EXCLUDE or INCLUDE, condition))
if commit:
self.save() | python | def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
assert isinstance(condition, basestring), 'conditions must be strings'
namespace = condition_set.get_namespace()
if namespace not in self.value:
self.value[namespace] = {}
if field_name not in self.value[namespace]:
self.value[namespace][field_name] = []
if condition not in self.value[namespace][field_name]:
self.value[namespace][field_name].append((exclude and EXCLUDE or INCLUDE, condition))
if commit:
self.save() | [
"def",
"add_condition",
"(",
"self",
",",
"manager",
",",
"condition_set",
",",
"field_name",
",",
"condition",
",",
"exclude",
"=",
"False",
",",
"commit",
"=",
"True",
")",
":",
"condition_set",
"=",
"manager",
".",
"get_condition_set_by_id",
"(",
"condition... | Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_condition(condition_set_id, 'percent', [0, 50], exclude=False) #doctest: +SKIP | [
"Adds",
"a",
"new",
"condition",
"and",
"registers",
"it",
"in",
"the",
"global",
"gargoyle",
"switch",
"manager",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/models.py#L127-L151 | train | 29,290 |
disqus/gargoyle | gargoyle/models.py | Switch.clear_conditions | def clear_conditions(self, manager, condition_set, field_name=None, commit=True):
"""
Clears conditions given a set of parameters.
If ``commit`` is ``False``, the data will not be written to the database.
Clear all conditions given a ConditionSet, and a field name:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id, 'percent') #doctest: +SKIP
You can also clear all conditions given a ConditionSet:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
namespace = condition_set.get_namespace()
if namespace not in self.value:
return
if not field_name:
del self.value[namespace]
elif field_name not in self.value[namespace]:
return
else:
del self.value[namespace][field_name]
if commit:
self.save() | python | def clear_conditions(self, manager, condition_set, field_name=None, commit=True):
"""
Clears conditions given a set of parameters.
If ``commit`` is ``False``, the data will not be written to the database.
Clear all conditions given a ConditionSet, and a field name:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id, 'percent') #doctest: +SKIP
You can also clear all conditions given a ConditionSet:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
namespace = condition_set.get_namespace()
if namespace not in self.value:
return
if not field_name:
del self.value[namespace]
elif field_name not in self.value[namespace]:
return
else:
del self.value[namespace][field_name]
if commit:
self.save() | [
"def",
"clear_conditions",
"(",
"self",
",",
"manager",
",",
"condition_set",
",",
"field_name",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"condition_set",
"=",
"manager",
".",
"get_condition_set_by_id",
"(",
"condition_set",
")",
"namespace",
"=",
"c... | Clears conditions given a set of parameters.
If ``commit`` is ``False``, the data will not be written to the database.
Clear all conditions given a ConditionSet, and a field name:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id, 'percent') #doctest: +SKIP
You can also clear all conditions given a ConditionSet:
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.clear_conditions(condition_set_id) #doctest: +SKIP | [
"Clears",
"conditions",
"given",
"a",
"set",
"of",
"parameters",
"."
] | 47a79e34b093d56e11c344296d6b78854ed35f12 | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/models.py#L184-L217 | train | 29,291 |
aparo/pyes | pyes/facets.py | FacetFactory.add_term_facet | def add_term_facet(self, *args, **kwargs):
"""Add a term factory facet"""
self.facets.append(TermFacet(*args, **kwargs)) | python | def add_term_facet(self, *args, **kwargs):
"""Add a term factory facet"""
self.facets.append(TermFacet(*args, **kwargs)) | [
"def",
"add_term_facet",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"facets",
".",
"append",
"(",
"TermFacet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Add a term factory facet | [
"Add",
"a",
"term",
"factory",
"facet"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/facets.py#L12-L14 | train | 29,292 |
aparo/pyes | pyes/facets.py | FacetFactory.add_date_facet | def add_date_facet(self, *args, **kwargs):
"""Add a date factory facet"""
self.facets.append(DateHistogramFacet(*args, **kwargs)) | python | def add_date_facet(self, *args, **kwargs):
"""Add a date factory facet"""
self.facets.append(DateHistogramFacet(*args, **kwargs)) | [
"def",
"add_date_facet",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"facets",
".",
"append",
"(",
"DateHistogramFacet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Add a date factory facet | [
"Add",
"a",
"date",
"factory",
"facet"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/facets.py#L16-L18 | train | 29,293 |
aparo/pyes | pyes/facets.py | FacetFactory.add_geo_facet | def add_geo_facet(self, *args, **kwargs):
"""Add a geo factory facet"""
self.facets.append(GeoDistanceFacet(*args, **kwargs)) | python | def add_geo_facet(self, *args, **kwargs):
"""Add a geo factory facet"""
self.facets.append(GeoDistanceFacet(*args, **kwargs)) | [
"def",
"add_geo_facet",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"facets",
".",
"append",
"(",
"GeoDistanceFacet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Add a geo factory facet | [
"Add",
"a",
"geo",
"factory",
"facet"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/facets.py#L20-L22 | train | 29,294 |
aparo/pyes | pyes/utils/imports.py | symbol_by_name | def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
^- class name
or using ':' to separate module and symbol::
celery.concurrency.processes:TaskPool
If `aliases` is provided, a dict containing short name/long name
mappings, the name is looked up in the aliases first.
Examples:
>>> symbol_by_name("celery.concurrency.processes.TaskPool")
<class 'celery.concurrency.processes.TaskPool'>
>>> symbol_by_name("default", {
... "default": "celery.concurrency.processes.TaskPool"})
<class 'celery.concurrency.processes.TaskPool'>
# Does not try to look up non-string names.
>>> from celery.concurrency.processes import TaskPool
>>> symbol_by_name(TaskPool) is TaskPool
True
"""
if imp is None:
imp = importlib.import_module
if not isinstance(name, six.string_types):
return name # already a class
name = aliases.get(name) or name
sep = ':' if ':' in name else sep
module_name, _, cls_name = name.rpartition(sep)
if not module_name:
cls_name, module_name = None, package if package else cls_name
try:
try:
module = imp(module_name, package=package, **kwargs)
except ValueError as exc:
raise ValueError("Couldn't import %r: %s" % (name, exc))
return getattr(module, cls_name) if cls_name else module
except (ImportError, AttributeError):
if default is None:
raise
return default | python | def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
^- class name
or using ':' to separate module and symbol::
celery.concurrency.processes:TaskPool
If `aliases` is provided, a dict containing short name/long name
mappings, the name is looked up in the aliases first.
Examples:
>>> symbol_by_name("celery.concurrency.processes.TaskPool")
<class 'celery.concurrency.processes.TaskPool'>
>>> symbol_by_name("default", {
... "default": "celery.concurrency.processes.TaskPool"})
<class 'celery.concurrency.processes.TaskPool'>
# Does not try to look up non-string names.
>>> from celery.concurrency.processes import TaskPool
>>> symbol_by_name(TaskPool) is TaskPool
True
"""
if imp is None:
imp = importlib.import_module
if not isinstance(name, six.string_types):
return name # already a class
name = aliases.get(name) or name
sep = ':' if ':' in name else sep
module_name, _, cls_name = name.rpartition(sep)
if not module_name:
cls_name, module_name = None, package if package else cls_name
try:
try:
module = imp(module_name, package=package, **kwargs)
except ValueError as exc:
raise ValueError("Couldn't import %r: %s" % (name, exc))
return getattr(module, cls_name) if cls_name else module
except (ImportError, AttributeError):
if default is None:
raise
return default | [
"def",
"symbol_by_name",
"(",
"name",
",",
"aliases",
"=",
"{",
"}",
",",
"imp",
"=",
"None",
",",
"package",
"=",
"None",
",",
"sep",
"=",
"'.'",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"imp",
"is",
"None",
":",
"... | Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
^- class name
or using ':' to separate module and symbol::
celery.concurrency.processes:TaskPool
If `aliases` is provided, a dict containing short name/long name
mappings, the name is looked up in the aliases first.
Examples:
>>> symbol_by_name("celery.concurrency.processes.TaskPool")
<class 'celery.concurrency.processes.TaskPool'>
>>> symbol_by_name("default", {
... "default": "celery.concurrency.processes.TaskPool"})
<class 'celery.concurrency.processes.TaskPool'>
# Does not try to look up non-string names.
>>> from celery.concurrency.processes import TaskPool
>>> symbol_by_name(TaskPool) is TaskPool
True | [
"Get",
"symbol",
"by",
"qualified",
"name",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/imports.py#L46-L101 | train | 29,295 |
aparo/pyes | pyes/utils/imports.py | import_from_cwd | def import_from_cwd(module, imp=None, package=None):
"""Import module, but make sure it finds modules
located in the current directory.
Modules located in the current directory has
precedence over modules located in `sys.path`.
"""
if imp is None:
imp = importlib.import_module
with cwd_in_path():
return imp(module, package=package) | python | def import_from_cwd(module, imp=None, package=None):
"""Import module, but make sure it finds modules
located in the current directory.
Modules located in the current directory has
precedence over modules located in `sys.path`.
"""
if imp is None:
imp = importlib.import_module
with cwd_in_path():
return imp(module, package=package) | [
"def",
"import_from_cwd",
"(",
"module",
",",
"imp",
"=",
"None",
",",
"package",
"=",
"None",
")",
":",
"if",
"imp",
"is",
"None",
":",
"imp",
"=",
"importlib",
".",
"import_module",
"with",
"cwd_in_path",
"(",
")",
":",
"return",
"imp",
"(",
"module"... | Import module, but make sure it finds modules
located in the current directory.
Modules located in the current directory has
precedence over modules located in `sys.path`. | [
"Import",
"module",
"but",
"make",
"sure",
"it",
"finds",
"modules",
"located",
"in",
"the",
"current",
"directory",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/imports.py#L148-L158 | train | 29,296 |
aparo/pyes | pyes/es.py | file_to_attachment | def file_to_attachment(filename, filehandler=None):
"""
Convert a file to attachment
"""
if filehandler:
return {'_name': filename,
'content': base64.b64encode(filehandler.read())
}
with open(filename, 'rb') as _file:
return {'_name': filename,
'content': base64.b64encode(_file.read())
} | python | def file_to_attachment(filename, filehandler=None):
"""
Convert a file to attachment
"""
if filehandler:
return {'_name': filename,
'content': base64.b64encode(filehandler.read())
}
with open(filename, 'rb') as _file:
return {'_name': filename,
'content': base64.b64encode(_file.read())
} | [
"def",
"file_to_attachment",
"(",
"filename",
",",
"filehandler",
"=",
"None",
")",
":",
"if",
"filehandler",
":",
"return",
"{",
"'_name'",
":",
"filename",
",",
"'content'",
":",
"base64",
".",
"b64encode",
"(",
"filehandler",
".",
"read",
"(",
")",
")",... | Convert a file to attachment | [
"Convert",
"a",
"file",
"to",
"attachment"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L50-L61 | train | 29,297 |
aparo/pyes | pyes/es.py | ESJsonDecoder.string_to_datetime | def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) > 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) == 10:
try:
return datetime.strptime(obj, "%Y-%m-%d")
except ValueError:
pass
return obj | python | def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) > 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) == 10:
try:
return datetime.strptime(obj, "%Y-%m-%d")
except ValueError:
pass
return obj | [
"def",
"string_to_datetime",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"obj",
")",
"==",
"19",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"obj",
",",
... | Decode a datetime string to a datetime object | [
"Decode",
"a",
"datetime",
"string",
"to",
"a",
"datetime",
"object"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L127-L146 | train | 29,298 |
aparo/pyes | pyes/es.py | ESJsonDecoder.dict_to_object | def dict_to_object(self, d):
"""
Decode datetime value from string to datetime
"""
for k, v in list(d.items()):
if isinstance(v, six.string_types) and len(v) == 19:
# Decode a datetime string to a datetime object
try:
d[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
elif isinstance(v, six.string_types) and len(v) > 20:
try:
d[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
pass
elif isinstance(v, list):
d[k] = [self.string_to_datetime(elem) for elem in v]
return DotDict(d) | python | def dict_to_object(self, d):
"""
Decode datetime value from string to datetime
"""
for k, v in list(d.items()):
if isinstance(v, six.string_types) and len(v) == 19:
# Decode a datetime string to a datetime object
try:
d[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
elif isinstance(v, six.string_types) and len(v) > 20:
try:
d[k] = datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
pass
elif isinstance(v, list):
d[k] = [self.string_to_datetime(elem) for elem in v]
return DotDict(d) | [
"def",
"dict_to_object",
"(",
"self",
",",
"d",
")",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"v",
")",
"==",
"... | Decode datetime value from string to datetime | [
"Decode",
"datetime",
"value",
"from",
"string",
"to",
"datetime"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L149-L167 | train | 29,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.