after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def end_time(self):
"""Return the end time of the object."""
try:
# MSG:
try:
return datetime.strptime(
self.nc.attrs["time_coverage_end"], "%Y-%m-%dT%H:%M:%SZ"
)
except TypeError:
return datetime.strptime(
self.nc.attrs["time_coverage_end"].astype(str), "%Y-%m-%dT%H:%M:%SZ"
)
except ValueError:
# PPS:
return datetime.strptime(self.nc.attrs["time_coverage_end"], "%Y%m%dT%H%M%S%fZ")
|
def end_time(self):
try:
# MSG:
return datetime.strptime(
self.nc.attrs["time_coverage_end"], "%Y-%m-%dT%H:%M:%SZ"
)
except ValueError:
# PPS:
return datetime.strptime(self.nc.attrs["time_coverage_end"], "%Y%m%dT%H%M%S%fZ")
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __init__(self, filename, filename_info, filetype_info, cal):
super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
self.cal = cal.nc
|
def __init__(self, filename, filename_info, filetype_info):
super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
self.nc = h5netcdf.File(filename, "r")
self.channel = filename_info["dataset_name"]
cal_file = os.path.join(os.path.dirname(filename), "instrument_data.nc")
self.cal = h5netcdf.File(cal_file, "r")
# TODO: get metadata from the manifest file (xfdumanifest.xml)
self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
self.sensor = "olci"
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, key, info):
"""Load a dataset."""
if self.channel != key.name:
return
logger.debug("Reading %s.", key.name)
radiances = self.nc[self.channel + "_radiance"]
if key.calibration == "reflectance":
idx = int(key.name[2:]) - 1
sflux = self._get_solar_flux(idx)
radiances = radiances / sflux * np.pi * 100
radiances.attrs["units"] = "%"
radiances.attrs["platform_name"] = self.platform_name
radiances.attrs["sensor"] = self.sensor
radiances.attrs.update(key.to_dict())
return radiances
|
def get_dataset(self, key, info):
"""Load a dataset"""
if self.channel != key.name:
return
logger.debug("Reading %s.", key.name)
variable = self.nc[self.channel + "_radiance"]
radiances = (
np.ma.masked_equal(variable[:], variable.attrs["_FillValue"], copy=False)
* variable.attrs["scale_factor"]
+ variable.attrs["add_offset"]
)
units = variable.attrs["units"]
if key.calibration == "reflectance":
solar_flux = self.cal["solar_flux"][:]
d_index = np.ma.masked_equal(
self.cal["detector_index"][:],
self.cal["detector_index"].attrs["_FillValue"],
copy=False,
)
idx = int(key.name[2:]) - 1
radiances /= solar_flux[idx, d_index]
radiances *= np.pi * 100
units = "%"
proj = Dataset(
radiances,
copy=False,
units=units,
platform_name=self.platform_name,
sensor=self.sensor,
)
proj.info.update(key.to_dict())
return proj
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, key, info):
"""Load a dataset."""
if key.name not in self.datasets:
return
if self.nc is None:
self.nc = xr.open_dataset(
self.filename,
decode_cf=True,
mask_and_scale=True,
engine="h5netcdf",
chunks={"tie_columns": CHUNK_SIZE, "tie_rows": CHUNK_SIZE},
)
self.nc = self.nc.rename({"tie_columns": "x", "tie_rows": "y"})
logger.debug("Reading %s.", key.name)
l_step = self.nc.attrs["al_subsampling_factor"]
c_step = self.nc.attrs["ac_subsampling_factor"]
if (c_step != 1 or l_step != 1) and self.cache.get(key.name) is None:
if key.name.startswith("satellite"):
zen = self.nc[self.datasets["satellite_zenith_angle"]]
zattrs = zen.attrs
azi = self.nc[self.datasets["satellite_azimuth_angle"]]
aattrs = azi.attrs
elif key.name.startswith("solar"):
zen = self.nc[self.datasets["solar_zenith_angle"]]
zattrs = zen.attrs
azi = self.nc[self.datasets["solar_azimuth_angle"]]
aattrs = azi.attrs
else:
raise NotImplementedError("Don't know how to read " + key.name)
x, y, z = angle2xyz(azi, zen)
shape = x.shape
from geotiepoints.interpolator import Interpolator
tie_lines = np.arange(0, (shape[0] - 1) * l_step + 1, l_step)
tie_cols = np.arange(0, (shape[1] - 1) * c_step + 1, c_step)
lines = np.arange((shape[0] - 1) * l_step + 1)
cols = np.arange((shape[1] - 1) * c_step + 1)
along_track_order = 1
cross_track_order = 3
satint = Interpolator(
[x.values, y.values, z.values],
(tie_lines, tie_cols),
(lines, cols),
along_track_order,
cross_track_order,
)
(
x,
y,
z,
) = satint.interpolate()
del satint
x = xr.DataArray(
da.from_array(x, chunks=(CHUNK_SIZE, CHUNK_SIZE)), dims=["y", "x"]
)
y = xr.DataArray(
da.from_array(y, chunks=(CHUNK_SIZE, CHUNK_SIZE)), dims=["y", "x"]
)
z = xr.DataArray(
da.from_array(z, chunks=(CHUNK_SIZE, CHUNK_SIZE)), dims=["y", "x"]
)
azi, zen = xyz2angle(x, y, z)
azi.attrs = aattrs
zen.attrs = zattrs
if "zenith" in key.name:
values = zen
elif "azimuth" in key.name:
values = azi
else:
raise NotImplementedError("Don't know how to read " + key.name)
if key.name.startswith("satellite"):
self.cache["satellite_zenith_angle"] = zen
self.cache["satellite_azimuth_angle"] = azi
elif key.name.startswith("solar"):
self.cache["solar_zenith_angle"] = zen
self.cache["solar_azimuth_angle"] = azi
elif key.name in self.cache:
values = self.cache[key.name]
else:
values = self.nc[self.datasets[key.name]]
values.attrs["platform_name"] = self.platform_name
values.attrs["sensor"] = self.sensor
values.attrs.update(key.to_dict())
return values
|
def get_dataset(self, key, info):
"""Load a dataset."""
if key.name not in self.datasets:
return
if self.nc is None:
self.nc = h5netcdf.File(self.filename, "r")
logger.debug("Reading %s.", key.name)
l_step = self.nc.attrs["al_subsampling_factor"]
c_step = self.nc.attrs["ac_subsampling_factor"]
if (c_step != 1 or l_step != 1) and key.name not in self.cache:
if key.name.startswith("satellite"):
zen, zattrs = self._get_scaled_variable(
self.datasets["satellite_zenith_angle"]
)
azi, aattrs = self._get_scaled_variable(
self.datasets["satellite_azimuth_angle"]
)
elif key.name.startswith("solar"):
zen, zattrs = self._get_scaled_variable(self.datasets["solar_zenith_angle"])
azi, aattrs = self._get_scaled_variable(
self.datasets["solar_azimuth_angle"]
)
else:
raise NotImplementedError("Don't know how to read " + key.name)
x, y, z = angle2xyz(azi, zen)
shape = x.shape
from geotiepoints.interpolator import Interpolator
tie_lines = np.arange(0, (shape[0] - 1) * l_step + 1, l_step)
tie_cols = np.arange(0, (shape[1] - 1) * c_step + 1, c_step)
lines = np.arange((shape[0] - 1) * l_step + 1)
cols = np.arange((shape[1] - 1) * c_step + 1)
along_track_order = 1
cross_track_order = 3
satint = Interpolator(
[x, y, z],
(tie_lines, tie_cols),
(lines, cols),
along_track_order,
cross_track_order,
)
(
x,
y,
z,
) = satint.interpolate()
azi, zen = xyz2angle(x, y, z)
if "zenith" in key.name:
values, attrs = zen, zattrs
elif "azimuth" in key.name:
values, attrs = azi, aattrs
else:
raise NotImplementedError("Don't know how to read " + key.name)
if key.name.startswith("satellite"):
self.cache["satellite_zenith_angle"] = zen, zattrs
self.cache["satellite_azimuth_angle"] = azi, aattrs
elif key.name.startswith("solar"):
self.cache["solar_zenith_angle"] = zen, zattrs
self.cache["solar_azimuth_angle"] = azi, aattrs
elif key.name in self.cache:
values, attrs = self.cache[key.name]
else:
values, attrs = self._get_scaled_variable(self.datasets[key.name])
units = attrs["units"]
proj = Dataset(
values,
copy=False,
units=units,
platform_name=self.platform_name,
sensor=self.sensor,
)
proj.info.update(key.to_dict())
return proj
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _collect_attrs(self, name, obj):
"""Collect all the attributes for the provided file object."""
for key in obj.ncattrs():
value = getattr(obj, key)
fc_key = "{}/attr/{}".format(name, key)
try:
self.file_content[fc_key] = np2str(value)
except ValueError:
self.file_content[fc_key] = value
|
def _collect_attrs(self, name, obj):
"""Collect all the attributes for the provided file object."""
for key in obj.ncattrs():
value = getattr(obj, key)
value = np.squeeze(value)
if issubclass(value.dtype.type, str) or np.issubdtype(
value.dtype, np.character
):
self.file_content["{}/attr/{}".format(name, key)] = str(value)
else:
self.file_content["{}/attr/{}".format(name, key)] = value
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __getitem__(self, key):
val = self.file_content[key]
if isinstance(val, netCDF4.Variable):
# these datasets are closed and inaccessible when the file is
# closed, need to reopen
# TODO: Handle HDF4 versus NetCDF3 versus NetCDF4
parts = key.rsplit("/", 1)
if len(parts) == 2:
group, key = parts
else:
group = None
val = xr.open_dataset(
self.filename,
group=group,
chunks=CHUNK_SIZE,
mask_and_scale=self.auto_maskandscale,
)[key]
return val
|
def __getitem__(self, key):
val = self.file_content[key]
if isinstance(val, netCDF4.Variable):
# these datasets are closed and inaccessible when the file is
# closed, need to reopen
v = netCDF4.Dataset(self.filename, "r")
val = v[key]
val.set_auto_maskandscale(self.auto_maskandscale)
return val
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_shape(self, ds_id, ds_info):
"""Return data array shape for item specified."""
var_path = ds_info.get("file_key", "{}".format(ds_id.name))
if var_path + "/shape" not in self:
# loading a scalar value
shape = 1
else:
shape = self[var_path + "/shape"]
if "index" in ds_info:
shape = shape[1:]
if "pressure_index" in ds_info:
shape = shape[:-1]
return shape
|
def get_shape(self, ds_id, ds_info):
"""Return data array shape for item specified."""
var_path = ds_info.get("file_key", "{}".format(ds_id.name))
shape = self[var_path + "/shape"]
if "index" in ds_info:
shape = shape[1:]
if "pressure_index" in ds_info:
shape = shape[:-1]
return shape
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, dataset_id, ds_info):
"""Load data array and metadata for specified dataset"""
var_path = ds_info.get("file_key", "{}".format(dataset_id.name))
metadata = self.get_metadata(dataset_id, ds_info)
valid_min, valid_max = self[var_path + "/attr/valid_range"]
fill_value = self.get(var_path + "/attr/_FillValue")
d_tmp = self[var_path]
if "index" in ds_info:
d_tmp = d_tmp[int(ds_info["index"])]
if "pressure_index" in ds_info:
d_tmp = d_tmp[..., int(ds_info["pressure_index"])]
# this is a pressure based field
# include surface_pressure as metadata
sp = self["Surface_Pressure"]
if "surface_pressure" in ds_info:
ds_info["surface_pressure"] = xr.concat((ds_info["surface_pressure"], sp))
else:
ds_info["surface_pressure"] = sp
# include all the pressure levels
ds_info.setdefault("pressure_levels", self["Pressure"][0])
data = d_tmp
if valid_min is not None and valid_max is not None:
# the original .cfg/INI based reader only checked valid_max
data = data.where((data <= valid_max)) # | (data >= valid_min))
if fill_value is not None:
data = data.where(data != fill_value)
data.attrs.update(metadata)
return data
|
def get_dataset(self, dataset_id, ds_info, out=None):
"""Load data array and metadata for specified dataset"""
var_path = ds_info.get("file_key", "{}".format(dataset_id.name))
dtype = ds_info.get("dtype", np.float32)
if var_path + "/shape" not in self:
# loading a scalar value
shape = 1
else:
shape = self.get_shape(dataset_id, ds_info)
file_units = ds_info.get("file_units", self.get(var_path + "/attr/units"))
if out is None:
out = np.ma.empty(shape, dtype=dtype)
out.mask = np.zeros(shape, dtype=np.bool)
out.info = {}
valid_min, valid_max = self[var_path + "/attr/valid_range"]
fill_value = self.get(var_path + "/attr/_FillValue")
d_tmp = np.require(self[var_path][:], dtype=dtype)
if "index" in ds_info:
d_tmp = d_tmp[int(ds_info["index"])]
if "pressure_index" in ds_info:
d_tmp = d_tmp[..., int(ds_info["pressure_index"])]
# this is a pressure based field
# include surface_pressure as metadata
sp = self["Surface_Pressure"][:]
if "surface_pressure" in ds_info:
ds_info["surface_pressure"] = np.concatenate(
(ds_info["surface_pressure"], sp)
)
else:
ds_info["surface_pressure"] = sp
# include all the pressure levels
ds_info.setdefault("pressure_levels", self["Pressure"][0])
out.data[:] = d_tmp
del d_tmp
if valid_min is not None and valid_max is not None:
# the original .cfg/INI based reader only checked valid_max
out.mask[:] |= out.data > valid_max # | (out < valid_min)
if fill_value is not None:
out.mask[:] |= out.data == fill_value
cls = ds_info.pop("container", Dataset)
i = getattr(out, "info", {})
i.update(ds_info)
i.update(dataset_id.to_dict())
i.update(
{
"units": ds_info.get("units", file_units),
"platform": self.platform_name,
"sensor": self.sensor_name,
"start_orbit": self.start_orbit_number,
"end_orbit": self.end_orbit_number,
}
)
if "standard_name" not in i:
sname_path = var_path + "/attr/standard_name"
i["standard_name"] = self.get(sname_path)
if "quality_flag" in i:
i["quality_flag"] = np.concatenate((i["quality_flag"], self["Quality_Flag"][:]))
else:
i["quality_flag"] = self["Quality_Flag"][:]
return cls(out.data, mask=out.mask, copy=False, **i)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs):
"""Configure reader behavior.
Args:
mask_surface (boolean): mask anything below the surface pressure
mask_quality (boolean): mask anything where the `Quality_Flag` metadata is ``!= 1``.
"""
self.pressure_dataset_names = defaultdict(list)
super(NUCAPSReader, self).__init__(config_files, **kwargs)
self.mask_surface = self.info.get("mask_surface", mask_surface)
self.mask_quality = self.info.get("mask_quality", mask_quality)
|
def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs):
"""Configure reader behavior.
Args:
mask_surface (boolean): mask anything below the surface pressure
mask_quality (boolean): mask anything where the `quality_flag` metadata is ``!= 1``.
"""
self.pressure_dataset_names = defaultdict(list)
super(NUCAPSReader, self).__init__(config_files, **kwargs)
self.mask_surface = self.info.get("mask_surface", mask_surface)
self.mask_quality = self.info.get("mask_quality", mask_quality)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def load(self, dataset_keys, pressure_levels=None):
"""Load data from one or more set of files.
:param pressure_levels: mask out certain pressure levels:
True for all levels
(min, max) for a range of pressure levels
[...] list of levels to include
"""
dataset_keys = set(self.get_dataset_key(x) for x in dataset_keys)
if pressure_levels is not None:
# Filter out datasets that don't fit in the correct pressure level
for ds_id in dataset_keys.copy():
ds_info = self.ids[ds_id]
ds_level = ds_info.get("pressure_level")
if ds_level is not None:
if pressure_levels is True:
# they want all pressure levels
continue
elif (
len(pressure_levels) == 2
and pressure_levels[0] <= ds_level <= pressure_levels[1]
):
# given a min and a max pressure level
continue
elif np.isclose(pressure_levels, ds_level).any():
# they asked for this specific pressure level
continue
else:
# they don't want this dataset at this pressure level
LOG.debug("Removing dataset to load: %s", ds_id)
dataset_keys.remove(ds_id)
continue
# Add pressure levels to the datasets to load if needed so
# we can do further filtering after loading
plevels_ds_id = self.get_dataset_key("Pressure_Levels")
remove_plevels = False
if plevels_ds_id not in dataset_keys:
dataset_keys.add(plevels_ds_id)
remove_plevels = True
datasets_loaded = super(NUCAPSReader, self).load(dataset_keys)
if pressure_levels is not None:
if remove_plevels:
plevels_ds = datasets_loaded.pop(plevels_ds_id)
dataset_keys.remove(plevels_ds_id)
else:
plevels_ds = datasets_loaded[plevels_ds_id]
if pressure_levels is True:
cond = None
elif len(pressure_levels) == 2:
cond = (plevels_ds >= pressure_levels[0]) & (
plevels_ds <= pressure_levels[1]
)
else:
cond = plevels_ds == pressure_levels
if cond is not None:
new_plevels = plevels_ds.where(cond, drop=True)
else:
new_plevels = plevels_ds
for ds_id in datasets_loaded.keys():
ds_obj = datasets_loaded[ds_id]
if plevels_ds.dims[0] not in ds_obj.dims:
continue
if cond is not None:
datasets_loaded[ds_id] = ds_obj.where(cond, drop=True)
datasets_loaded[ds_id].attrs["pressure_levels"] = new_plevels
if self.mask_surface:
LOG.debug("Filtering pressure levels at or below the surface pressure")
for ds_id in sorted(dataset_keys):
ds = datasets_loaded[ds_id]
if "surface_pressure" not in ds.attrs or "pressure_levels" not in ds.attrs:
continue
data_pressure = ds.attrs["pressure_levels"]
surface_pressure = ds.attrs["surface_pressure"]
if isinstance(surface_pressure, float):
# scalar needs to become array for each record
surface_pressure = np.repeat(surface_pressure, ds.shape[0])
if surface_pressure.ndim == 1 and surface_pressure.shape[0] == ds.shape[0]:
# surface is one element per record
LOG.debug("Filtering %s at and below the surface pressure", ds_id)
if ds.ndim == 2:
surface_pressure = np.repeat(
surface_pressure[:, None], data_pressure.shape[0], axis=1
)
data_pressure = np.repeat(
data_pressure[None, :], surface_pressure.shape[0], axis=0
)
datasets_loaded[ds_id] = ds.where(data_pressure < surface_pressure)
else:
# entire dataset represents one pressure level
data_pressure = ds.attrs["pressure_level"]
datasets_loaded[ds_id] = ds.where(data_pressure < surface_pressure)
else:
LOG.warning(
"Not sure how to handle shape of 'surface_pressure' metadata"
)
if self.mask_quality:
LOG.debug("Filtering data based on quality flags")
for ds_id in sorted(dataset_keys):
ds = datasets_loaded[ds_id]
if not any(
x for x in ds.attrs["ancillary_variables"] if x.name == "Quality_Flag"
):
continue
quality_flag = datasets_loaded["Quality_Flag"]
if quality_flag.dims[0] not in datasets_loaded[ds_id].dims:
continue
LOG.debug("Masking %s where quality flag doesn't equal 1", ds_id)
datasets_loaded[ds_id] = ds.where(quality_flag == 0)
return datasets_loaded
|
def load(self, dataset_keys, pressure_levels=None):
"""Load data from one or more set of files.
:param pressure_levels: mask out certain pressure levels:
True for all levels
(min, max) for a range of pressure levels
[...] list of levels to include
"""
dataset_keys = set(self.get_dataset_key(x) for x in dataset_keys)
if pressure_levels is not None:
# Filter out datasets that don't fit in the correct pressure level
for ds_id in dataset_keys.copy():
ds_info = self.ids[ds_id]
ds_level = ds_info.get("pressure_level")
if ds_level is not None:
if pressure_levels is True:
# they want all pressure levels
continue
elif (
len(pressure_levels) == 2
and pressure_levels[0] <= ds_level <= pressure_levels[1]
):
# given a min and a max pressure level
continue
elif np.isclose(pressure_levels, ds_level).any():
# they asked for this specific pressure level
continue
else:
# they don't want this dataset at this pressure level
LOG.debug("Removing dataset to load: %s", ds_id)
dataset_keys.remove(ds_id)
continue
# Add pressure levels to the datasets to load if needed so
# we can do further filtering after loading
plevels_ds_id = self.get_dataset_key("Pressure_Levels")
remove_plevels = False
if plevels_ds_id not in dataset_keys:
dataset_keys.add(plevels_ds_id)
remove_plevels = True
datasets_loaded = super(NUCAPSReader, self).load(dataset_keys)
if pressure_levels is not None:
if remove_plevels:
plevels_ds = datasets_loaded.pop(plevels_ds_id)
dataset_keys.remove(plevels_ds_id)
else:
plevels_ds = datasets_loaded[plevels_ds_id]
for ds_id in datasets_loaded.keys():
ds_obj = datasets_loaded[ds_id]
if plevels_ds is None:
LOG.debug("No 'pressure_levels' metadata included in dataset")
continue
if plevels_ds.shape[0] != ds_obj.shape[-1]:
# LOG.debug("Dataset '{}' doesn't contain multiple pressure levels".format(ds_id))
continue
if pressure_levels is True:
levels_mask = np.ones(plevels_ds.shape, dtype=np.bool)
elif len(pressure_levels) == 2:
# given a min and a max pressure level
levels_mask = (plevels_ds <= pressure_levels[1]) & (
plevels_ds >= pressure_levels[0]
)
else:
levels_mask = np.zeros(plevels_ds.shape, dtype=np.bool)
for idx, ds_level in enumerate(plevels_ds):
levels_mask[idx] = np.isclose(pressure_levels, ds_level).any()
datasets_loaded[ds_id] = ds_obj[..., levels_mask]
datasets_loaded[ds_id].info["pressure_levels"] = plevels_ds[levels_mask]
if self.mask_surface:
LOG.debug("Filtering pressure levels at or below the surface pressure")
for ds_id in sorted(dataset_keys):
ds = datasets_loaded[ds_id]
if "surface_pressure" not in ds.info or "pressure_levels" not in ds.info:
continue
data_pressure = ds.info["pressure_levels"]
surface_pressure = ds.info["surface_pressure"]
if isinstance(surface_pressure, float):
# scalar needs to become array for each record
surface_pressure = np.repeat(surface_pressure, ds.shape[0])
if surface_pressure.ndim == 1 and surface_pressure.shape[0] == ds.shape[0]:
# surface is one element per record
LOG.debug("Filtering %s at and below the surface pressure", ds_id)
if ds.ndim == 2:
surface_pressure = np.repeat(
surface_pressure[:, None], data_pressure.shape[0], axis=1
)
data_pressure = np.repeat(
data_pressure[None, :], surface_pressure.shape[0], axis=0
)
ds.mask[data_pressure >= surface_pressure] = True
else:
# entire dataset represents one pressure level
data_pressure = ds.info["pressure_level"]
ds.mask[data_pressure >= surface_pressure] = True
else:
LOG.warning(
"Not sure how to handle shape of 'surface_pressure' metadata"
)
if self.mask_quality:
LOG.debug("Filtering data based on quality flags")
for ds_id in sorted(dataset_keys):
ds = datasets_loaded[ds_id]
if "quality_flag" not in ds.info:
continue
quality_flag = ds.info["quality_flag"]
LOG.debug("Masking %s where quality flag doesn't equal 1", ds_id)
ds.mask[quality_flag != 0, ...] = True
return datasets_loaded
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, dataset_id, ds_info):
var_path = ds_info.get("file_key", "{}".format(dataset_id.name))
metadata = self.get_metadata(dataset_id, ds_info)
valid_min, valid_max = self.get(
var_path + "/attr/valid_range",
self.get(var_path + "/attr/ValidRange", (None, None)),
)
if valid_min is None or valid_max is None:
raise KeyError(
"File variable '{}' has no valid range attribute".format(var_path)
)
fill_name = var_path + "/attr/{}".format(self._fill_name)
if fill_name in self:
fill_value = self[fill_name]
else:
fill_value = None
data = self[var_path]
scale_factor_path = var_path + "/attr/ScaleFactor"
if scale_factor_path in self:
scale_factor = self[scale_factor_path]
scale_offset = self[var_path + "/attr/Offset"]
else:
scale_factor = None
scale_offset = None
if valid_min is not None and valid_max is not None:
# the original .cfg/INI based reader only checked valid_max
data = data.where((data <= valid_max) & (data >= valid_min))
if fill_value is not None:
data = data.where(data != fill_value)
factors = (scale_factor, scale_offset)
factors = self.adjust_scaling_factors(
factors, metadata["file_units"], ds_info.get("units")
)
if factors[0] != 1 or factors[1] != 0:
data = data * factors[0] + factors[1]
data.attrs.update(metadata)
return data
|
def get_dataset(self, dataset_id, ds_info, out=None):
var_path = ds_info.get("file_key", "{}".format(dataset_id.name))
dtype = ds_info.get("dtype", np.float32)
shape = self.get_shape(dataset_id, ds_info)
file_units = ds_info.get("file_units")
if file_units is None:
file_units = self.get(
var_path + "/attr/units", self.get(var_path + "/attr/Units")
)
if file_units is None:
raise KeyError("File variable '{}' has no units attribute".format(var_path))
elif file_units == "deg":
file_units = "degrees"
elif file_units == "Unitless":
file_units = "1"
if out is None:
out = np.ma.empty(shape, dtype=dtype)
out.mask = np.zeros(shape, dtype=np.bool)
valid_min, valid_max = self.get(
var_path + "/attr/valid_range",
self.get(var_path + "/attr/ValidRange", (None, None)),
)
if valid_min is None or valid_max is None:
raise KeyError(
"File variable '{}' has no valid range attribute".format(var_path)
)
fill_name = var_path + "/attr/{}".format(self._fill_name)
if fill_name in self:
fill_value = self[fill_name]
else:
fill_value = None
out.data[:] = np.require(self[var_path][:], dtype=dtype)
scale_factor_path = var_path + "/attr/ScaleFactor"
if scale_factor_path in self:
scale_factor = self[scale_factor_path]
scale_offset = self[var_path + "/attr/Offset"]
else:
scale_factor = None
scale_offset = None
if valid_min is not None and valid_max is not None:
# the original .cfg/INI based reader only checked valid_max
out.mask[:] |= (out.data > valid_max) | (out.data < valid_min)
if fill_value is not None:
out.mask[:] |= out.data == fill_value
factors = (scale_factor, scale_offset)
factors = self.adjust_scaling_factors(factors, file_units, ds_info.get("units"))
if factors[0] != 1 or factors[1] != 0:
out.data[:] *= factors[0]
out.data[:] += factors[1]
i = getattr(out, "info", {})
i.update(ds_info)
i.update(
{
"units": ds_info.get("units", file_units),
"platform": self.platform_name,
"sensor": self.sensor_name,
"start_orbit": self.start_orbit_number,
"end_orbit": self.end_orbit_number,
}
)
i.update(dataset_id.to_dict())
if "standard_name" not in ds_info:
i["standard_name"] = self.get(var_path + "/attr/Title", dataset_id.name)
cls = ds_info.pop("container", Dataset)
return cls(out.data, mask=out.mask, copy=False, **i)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_shape(self, ds_id, ds_info):
var_path = ds_info.get("file_key", "observation_data/{}".format(ds_id.name))
return self.get(var_path + "/shape", 1)
|
def get_shape(self, ds_id, ds_info):
var_path = ds_info.get("file_key", "observation_data/{}".format(ds_id.name))
return self[var_path + "/shape"]
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _load_and_slice(self, var_path, shape, xslice, yslice):
if isinstance(shape, tuple) and len(shape) == 2:
return self[var_path][yslice, xslice]
elif isinstance(shape, tuple) and len(shape) == 1:
return self[var_path][yslice]
else:
return self[var_path]
|
def _load_and_slice(self, dtype, var_path, shape, xslice, yslice):
if isinstance(shape, tuple) and len(shape) == 2:
return np.require(self[var_path][yslice, xslice], dtype=dtype)
elif isinstance(shape, tuple) and len(shape) == 1:
return np.require(self[var_path][yslice], dtype=dtype)
else:
return np.require(self[var_path][:], dtype=dtype)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, dataset_id, ds_info, xslice=slice(None), yslice=slice(None)):
var_path = ds_info.get("file_key", "observation_data/{}".format(dataset_id.name))
metadata = self.get_metadata(dataset_id, ds_info)
shape = metadata["shape"]
if isinstance(shape, tuple) and len(shape) == 2:
# 2D array
if xslice.start is not None:
shape = (shape[0], xslice.stop - xslice.start)
if yslice.start is not None:
shape = (yslice.stop - yslice.start, shape[1])
elif isinstance(shape, tuple) and len(shape) == 1 and yslice.start is not None:
shape = ((yslice.stop - yslice.start) / yslice.step,)
metadata["shape"] = shape
valid_min, valid_max, scale_factor, scale_offset = self._get_dataset_valid_range(
dataset_id, ds_info, var_path
)
if dataset_id.calibration == "radiance" and ds_info["units"] == "W m-2 um-1 sr-1":
data = self._load_and_slice(var_path, shape, xslice, yslice)
elif ds_info.get("units") == "%":
data = self._load_and_slice(var_path, shape, xslice, yslice)
elif ds_info.get("units") == "K":
# normal brightness temperature
# use a special LUT to get the actual values
lut_var_path = ds_info.get("lut", var_path + "_brightness_temperature_lut")
# we get the BT values from a look up table using the scaled radiance integers
# .flatten() currently not supported, workaround: https://github.com/pydata/xarray/issues/1029
data = self[var_path][yslice, xslice]
data = data.stack(name=data.dims).astype(np.int)
coords = data.coords
data = self[lut_var_path][data]
if "dim_0" in data:
# seems like older versions of xarray take the dims from
# 'lut_var_path'. newer versions take 'data' dims
data = data.rename({"dim_0": "name"})
data = data.assign_coords(**coords).unstack("name")
elif shape == 1:
data = self[var_path]
else:
data = self._load_and_slice(var_path, shape, xslice, yslice)
if valid_min is not None and valid_max is not None:
data = data.where((data >= valid_min) & (data <= valid_max))
factors = (scale_factor, scale_offset)
factors = self.adjust_scaling_factors(
factors, metadata["file_units"], ds_info.get("units")
)
if factors[0] != 1 or factors[1] != 0:
data = data * factors[0] + factors[1]
data.attrs.update(metadata)
return data
|
def get_dataset(
self, dataset_id, ds_info, out=None, xslice=slice(None), yslice=slice(None)
):
var_path = ds_info.get("file_key", "observation_data/{}".format(dataset_id.name))
dtype = ds_info.get("dtype", np.float32)
if var_path + "/shape" not in self:
# loading a scalar value
shape = 1
else:
shape = self[var_path + "/shape"]
if isinstance(shape, tuple) and len(shape) == 2:
# 2D array
if xslice.start is not None:
shape = (shape[0], xslice.stop - xslice.start)
if yslice.start is not None:
shape = (yslice.stop - yslice.start, shape[1])
elif isinstance(shape, tuple) and len(shape) == 1 and yslice.start is not None:
shape = ((yslice.stop - yslice.start) / yslice.step,)
file_units = ds_info.get("file_units")
if file_units is None:
try:
file_units = self[var_path + "/attr/units"]
# they were almost completely CF compliant...
if file_units == "none":
file_units = "1"
except KeyError:
# no file units specified
file_units = None
if out is None:
out = np.ma.empty(shape, dtype=dtype)
out.mask = np.zeros(shape, dtype=np.bool)
if dataset_id.calibration == "radiance" and ds_info["units"] == "W m-2 um-1 sr-1":
rad_units_path = var_path + "/attr/radiance_units"
if rad_units_path in self:
# we are getting a reflectance band but we want the radiance values
# special scaling parameters
scale_factor = self[var_path + "/attr/radiance_scale_factor"]
scale_offset = self[var_path + "/attr/radiance_add_offset"]
if file_units is None:
file_units = self[var_path + "/attr/radiance_units"]
if file_units == "Watts/meter^2/steradian/micrometer":
file_units = "W m-2 um-1 sr-1"
else:
# we are getting a btemp band but we want the radiance values
# these are stored directly in the primary variable
scale_factor = self[var_path + "/attr/scale_factor"]
scale_offset = self[var_path + "/attr/add_offset"]
out.data[:] = self._load_and_slice(dtype, var_path, shape, xslice, yslice)
valid_min = self[var_path + "/attr/valid_min"]
valid_max = self[var_path + "/attr/valid_max"]
elif ds_info.get("units") == "%":
# normal reflectance
out.data[:] = self._load_and_slice(dtype, var_path, shape, xslice, yslice)
valid_min = self[var_path + "/attr/valid_min"]
valid_max = self[var_path + "/attr/valid_max"]
scale_factor = self[var_path + "/attr/scale_factor"]
scale_offset = self[var_path + "/attr/add_offset"]
# v1.1 and above of level 1 processing removed 'units' attribute
# for all reflectance channels
if file_units is None:
file_units = "1"
elif ds_info.get("units") == "K":
# normal brightness temperature
# use a special LUT to get the actual values
lut_var_path = ds_info.get("lut", var_path + "_brightness_temperature_lut")
# we get the BT values from a look up table using the scaled radiance integers
out.data[:] = np.require(
self[lut_var_path][:][self[var_path][yslice, xslice].ravel()], dtype=dtype
).reshape(shape)
valid_min = self[lut_var_path + "/attr/valid_min"]
valid_max = self[lut_var_path + "/attr/valid_max"]
scale_factor = scale_offset = None
elif shape == 1:
out.data[:] = self[var_path]
scale_factor = None
scale_offset = None
valid_min = None
valid_max = None
else:
out.data[:] = self._load_and_slice(dtype, var_path, shape, xslice, yslice)
valid_min = self[var_path + "/attr/valid_min"]
valid_max = self[var_path + "/attr/valid_max"]
try:
scale_factor = self[var_path + "/attr/scale_factor"]
scale_offset = self[var_path + "/attr/add_offset"]
except KeyError:
scale_factor = scale_offset = None
if valid_min is not None and valid_max is not None:
out.mask[:] |= (out.data < valid_min) | (out.data > valid_max)
factors = (scale_factor, scale_offset)
factors = self.adjust_scaling_factors(factors, file_units, ds_info.get("units"))
if factors[0] != 1 or factors[1] != 0:
out.data[:] *= factors[0]
out.data[:] += factors[1]
# Get extra metadata
if "/dimension/number_of_scans" in self:
rows_per_scan = int(shape[0] / self["/dimension/number_of_scans"])
ds_info.setdefault("rows_per_scan", rows_per_scan)
i = getattr(out, "info", {})
i.update(ds_info)
i.update(dataset_id.to_dict())
i.update(
{
"units": ds_info.get("units", file_units),
"platform": self.platform_name,
"sensor": self.sensor_name,
"start_orbit": self.start_orbit_number,
"end_orbit": self.end_orbit_number,
}
)
ds_info.update(dataset_id.to_dict())
cls = ds_info.pop("container", Dataset)
return cls(out.data, mask=out.mask, copy=False, **i)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def scale_swath_data(self, data, scaling_factors):
"""Scale swath data using scaling factors and offsets.
Multi-granule (a.k.a. aggregated) files will have more than the usual two values.
"""
num_grans = len(scaling_factors) // 2
gran_size = data.shape[0] // num_grans
factors = scaling_factors.where(scaling_factors > -999)
factors = xr.DataArray(
np.repeat(factors.values[None, :], gran_size, axis=0),
dims=(data.dims[0], "factors"),
)
data = data * factors[:, 0] + factors[:, 1]
return data
|
def scale_swath_data(self, data, mask, scaling_factors):
"""Scale swath data using scaling factors and offsets.
Multi-granule (a.k.a. aggregated) files will have more than the usual two values.
"""
num_grans = len(scaling_factors) // 2
gran_size = data.shape[0] // num_grans
for i in range(num_grans):
start_idx = i * gran_size
end_idx = start_idx + gran_size
m = scaling_factors[i * 2]
b = scaling_factors[i * 2 + 1]
# in rare cases the scaling factors are actually fill values
if m <= -999 or b <= -999:
mask[start_idx:end_idx] = 1
else:
data[start_idx:end_idx] *= m
data[start_idx:end_idx] += b
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def adjust_scaling_factors(self, factors, file_units, output_units):
if file_units == output_units:
LOG.debug("File units and output units are the same (%s)", file_units)
return factors
if factors is None:
factors = xr.DataArray([1, 0])
factors = factors.where(factors != -999.0)
if file_units == "W cm-2 sr-1" and output_units == "W m-2 sr-1":
LOG.debug(
"Adjusting scaling factors to convert '%s' to '%s'",
file_units,
output_units,
)
factors = factors * 10000.0
return factors
elif file_units == "1" and output_units == "%":
LOG.debug(
"Adjusting scaling factors to convert '%s' to '%s'",
file_units,
output_units,
)
factors = factors * 100.0
return factors
else:
return factors
|
def adjust_scaling_factors(self, factors, file_units, output_units):
if file_units == output_units:
LOG.debug("File units and output units are the same (%s)", file_units)
return factors
if factors is None:
factors = [1, 0]
factors = np.array(factors)
if file_units == "W cm-2 sr-1" and output_units == "W m-2 sr-1":
LOG.debug(
"Adjusting scaling factors to convert '%s' to '%s'",
file_units,
output_units,
)
factors[::2] = np.where(factors[::2] != -999, factors[::2] * 10000.0, -999)
factors[1::2] = np.where(factors[1::2] != -999, factors[1::2] * 10000.0, -999)
return factors
elif file_units == "1" and output_units == "%":
LOG.debug(
"Adjusting scaling factors to convert '%s' to '%s'",
file_units,
output_units,
)
factors[::2] = np.where(factors[::2] != -999, factors[::2] * 100.0, -999)
factors[1::2] = np.where(factors[1::2] != -999, factors[1::2] * 100.0, -999)
return factors
else:
return factors
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_dataset(self, dataset_id, ds_info):
var_path = self._generate_file_key(dataset_id, ds_info)
factor_var_path = ds_info.get("factors_key", var_path + "Factors")
data = self[var_path]
is_floating = np.issubdtype(data.dtype, np.floating)
if is_floating:
# If the data is a float then we mask everything <= -999.0
fill_max = float(ds_info.pop("fill_max_float", -999.0))
data = data.where(data > fill_max)
else:
# If the data is an integer then we mask everything >= fill_min_int
fill_min = int(ds_info.pop("fill_min_int", 65528))
data = data.where(data < fill_min)
factors = self.get(factor_var_path)
if factors is None:
LOG.debug("No scaling factors found for %s", dataset_id)
file_units = self.get_file_units(dataset_id, ds_info)
output_units = ds_info.get("units", file_units)
factors = self.adjust_scaling_factors(factors, file_units, output_units)
if factors is not None:
data = self.scale_swath_data(data, factors)
i = getattr(data, "attrs", {})
i.update(ds_info)
i.update(
{
"units": ds_info.get("units", file_units),
"platform_name": self.platform_name,
"sensor": self.sensor_name,
"start_orbit": self.start_orbit_number,
"end_orbit": self.end_orbit_number,
}
)
i.update(dataset_id.to_dict())
data.attrs.update(i)
return data
|
def get_dataset(self, dataset_id, ds_info, out=None):
var_path = self._generate_file_key(dataset_id, ds_info)
factor_var_path = ds_info.get("factors_key", var_path + "Factors")
data = self[var_path]
dtype = ds_info.get("dtype", np.float32)
is_floating = np.issubdtype(data.dtype, np.floating)
if out is not None:
# This assumes that we are promoting the dtypes (ex. float file data -> int array)
# and that it happens automatically when assigning to the existing
# out array
out.data[:] = data
else:
shape = self.get_shape(dataset_id, ds_info)
out = np.ma.empty(shape, dtype=dtype)
out.mask = np.zeros(shape, dtype=np.bool)
if is_floating:
# If the data is a float then we mask everything <= -999.0
fill_max = float(ds_info.pop("fill_max_float", -999.0))
out.mask[:] |= out.data <= fill_max
else:
# If the data is an integer then we mask everything >= fill_min_int
fill_min = int(ds_info.pop("fill_min_int", 65528))
out.mask[:] |= out.data >= fill_min
factors = self.get(factor_var_path)
if factors is None:
LOG.debug("No scaling factors found for %s", dataset_id)
file_units = self.get_file_units(dataset_id, ds_info)
output_units = ds_info.get("units", file_units)
factors = self.adjust_scaling_factors(factors, file_units, output_units)
if factors is not None:
self.scale_swath_data(out.data, out.mask, factors)
i = getattr(out, "info", {})
i.update(ds_info)
i.update(
{
"units": ds_info.get("units", file_units),
"platform_name": self.platform_name,
"sensor": self.sensor_name,
"start_orbit": self.start_orbit_number,
"end_orbit": self.end_orbit_number,
}
)
i.update(dataset_id.to_dict())
cls = ds_info.pop("container", Dataset)
return cls(out.data, mask=out.mask, copy=False, **i)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __init__(
self, config_files, filter_parameters=None, filter_filenames=True, **kwargs
):
super(FileYAMLReader, self).__init__(config_files)
self.file_handlers = {}
self.filter_filenames = self.info.get("filter_filenames", filter_filenames)
self.filter_parameters = filter_parameters or {}
if kwargs:
logger.warning(
"Unrecognized/unused reader keyword argument(s) '{}'".format(kwargs)
)
self.coords_cache = WeakValueDictionary()
|
def __init__(
self, config_files, filter_parameters=None, filter_filenames=True, **kwargs
):
super(FileYAMLReader, self).__init__(config_files)
self.file_handlers = {}
self.filter_filenames = self.info.get("filter_filenames", filter_filenames)
self.filter_parameters = filter_parameters or {}
if kwargs:
logger.warning(
"Unrecognized/unused reader keyword argument(s) '{}'".format(kwargs)
)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _load_dataset_data(
self, file_handlers, dsid, xslice=slice(None), yslice=slice(None)
):
ds_info = self.ids[dsid]
proj = self._load_dataset(dsid, ds_info, file_handlers)
# FIXME: areas could be concatenated here
# Update the metadata
proj.attrs["start_time"] = file_handlers[0].start_time
proj.attrs["end_time"] = file_handlers[-1].end_time
return proj
|
def _load_dataset_data(
self, file_handlers, dsid, xslice=slice(None), yslice=slice(None)
):
ds_info = self.ids[dsid]
try:
# Can we allow the file handlers to do inplace data writes?
[list(fhd.get_shape(dsid, ds_info)) for fhd in file_handlers]
except NotImplementedError:
# FIXME: Is NotImplementedError included in Exception for all
# versions of Python?
proj = self._load_entire_dataset(dsid, ds_info, file_handlers)
else:
proj = self._load_sliced_dataset(dsid, ds_info, file_handlers, xslice, yslice)
# FIXME: areas could be concatenated here
# Update the metadata
proj.info["start_time"] = file_handlers[0].start_time
proj.info["end_time"] = file_handlers[-1].end_time
return proj
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _make_area_from_coords(self, coords):
"""Create an appropriate area with the given *coords*."""
if len(coords) == 2:
lon_sn = coords[0].attrs.get("standard_name")
lat_sn = coords[1].attrs.get("standard_name")
if lon_sn == "longitude" and lat_sn == "latitude":
key = None
try:
key = (coords[0].data.name, coords[1].data.name)
sdef = self.coords_cache.get(key)
except AttributeError:
sdef = None
if sdef is None:
sdef = SwathDefinition(*coords)
if key is not None:
self.coords_cache[key] = sdef
sensor_str = "_".join(self.info["sensors"])
shape_str = "_".join(map(str, coords[0].shape))
sdef.name = "{}_{}_{}_{}".format(
sensor_str, shape_str, coords[0].attrs["name"], coords[1].attrs["name"]
)
return sdef
else:
raise ValueError(
"Coordinates info object missing standard_name key: " + str(coords)
)
elif len(coords) != 0:
raise NameError("Don't know what to do with coordinates " + str(coords))
|
def _make_area_from_coords(self, coords):
"""Create an apropriate area with the given *coords*."""
if len(coords) == 2:
lon_sn = coords[0].info.get("standard_name")
lat_sn = coords[1].info.get("standard_name")
if lon_sn == "longitude" and lat_sn == "latitude":
sdef = SwathDefinition(*coords)
sensor_str = sdef.name = "_".join(self.info["sensors"])
shape_str = "_".join(map(str, coords[0].shape))
sdef.name = "{}_{}_{}_{}".format(
sensor_str, shape_str, coords[0].info["name"], coords[1].info["name"]
)
return sdef
else:
raise ValueError(
"Coordinates info object missing standard_name key: " + str(coords)
)
elif len(coords) != 0:
raise NameError("Don't know what to do with coordinates " + str(coords))
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _load_dataset_with_area(self, dsid, coords):
"""Loads *dsid* and it's area if available."""
file_handlers = self._get_file_handlers(dsid)
if not file_handlers:
return
area = self._load_dataset_area(dsid, file_handlers, coords)
slice_kwargs, area = self._get_slices(area)
try:
ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
except (KeyError, ValueError) as err:
logger.exception("Could not load dataset '%s': %s", dsid, str(err))
return None
if area is not None:
ds.attrs["area"] = area
if (("x" not in ds.coords) or ("y" not in ds.coords)) and hasattr(
area, "get_proj_vectors_dask"
):
ds["x"], ds["y"] = area.get_proj_vectors_dask(CHUNK_SIZE)
return ds
|
def _load_dataset_with_area(self, dsid, coords):
"""Loads *dsid* and it's area if available."""
file_handlers = self._get_file_handlers(dsid)
if not file_handlers:
return
area = self._load_dataset_area(dsid, file_handlers, coords)
slice_kwargs, area = self._get_slices(area)
try:
ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
except (KeyError, ValueError) as err:
logger.exception("Could not load dataset '%s': %s", dsid, str(err))
return None
if area is not None:
ds.info["area"] = area
return ds
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def load(self, dataset_keys, previous_datasets=None):
"""Load `dataset_keys`.
If `previous_datasets` is provided, do not reload those."""
all_datasets = previous_datasets or DatasetDict()
datasets = DatasetDict()
# Include coordinates in the list of datasets to load
dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
coordinates = self._get_coordinates_for_dataset_keys(dsids)
all_dsids = list(set().union(*coordinates.values())) + dsids
for dsid in all_dsids:
if dsid in all_datasets:
continue
coords = [all_datasets.get(cid, None) for cid in coordinates.get(dsid, [])]
ds = self._load_dataset_with_area(dsid, coords)
if ds is not None:
all_datasets[dsid] = ds
if dsid in dsids:
datasets[dsid] = ds
self._load_ancillary_variables(all_datasets)
return datasets
|
def load(self, dataset_keys):
"""Load *dataset_keys*."""
all_datasets = DatasetDict()
datasets = DatasetDict()
# Include coordinates in the list of datasets to load
dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
coordinates = self._get_coordinates_for_dataset_keys(dsids)
all_dsids = list(set().union(*coordinates.values())) + dsids
for dsid in all_dsids:
coords = [all_datasets.get(cid, None) for cid in coordinates.get(dsid, [])]
ds = self._load_dataset_with_area(dsid, coords)
if ds is not None:
all_datasets[dsid] = ds
if dsid in dsids:
datasets[dsid] = ds
return datasets
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_area_file():
"""Find area file(s) to use.
The files are to be named `areas.yaml` or `areas.def`.
"""
paths = config_search_paths("areas.yaml")
if paths:
return paths
else:
return get_config_path("areas.def")
|
def get_area_file():
conf, successes = get_config("satpy.cfg")
if conf is None or not successes:
LOG.warning(
"Couldn't find the satpy.cfg file. Do you have one ? is it in $PPP_CONFIG_DIR ?"
)
return None
try:
fn = os.path.join(
conf.get("projector", "area_directory") or "",
conf.get("projector", "area_file"),
)
return get_config_path(fn)
except configparser.NoSectionError:
LOG.warning("Couldn't find 'projector' section of 'satpy.cfg'")
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def hash_area(area):
"""Get (and set) the hash for the *area*."""
return str(area.__hash__())
|
def hash_area(area):
"""Get (and set) the hash for the *area*."""
try:
return area.kdtree_hash
except AttributeError:
LOG.debug("Computing kd-tree hash for area %s", getattr(area, "name", "swath"))
try:
area_hash = "".join(
(
hashlib.sha1(
json.dumps(area.proj_dict, sort_keys=True).encode("utf-8")
).hexdigest(),
hashlib.sha1(json.dumps(area.area_extent).encode("utf-8")).hexdigest(),
hashlib.sha1(
json.dumps((int(area.shape[0]), int(area.shape[1]))).encode("utf-8")
).hexdigest(),
)
)
except AttributeError:
if not hasattr(area, "lons") or area.lons is None:
lons, lats = area.get_lonlats()
else:
lons, lats = area.lons, area.lats
try:
mask_hash = hashlib.sha1(lons.mask | lats.mask).hexdigest()
except AttributeError:
mask_hash = "False"
area_hash = "".join(
(mask_hash, hashlib.sha1(lons).hexdigest(), hashlib.sha1(lats).hexdigest())
)
area.kdtree_hash = area_hash
return area_hash
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def resample(self, data, cache_dir=False, mask_area=True, **kwargs):
"""Resample the *data*, saving the projection info on disk if *precompute* evaluates to True.
:param mask_area: Provide data mask to `precompute` method to mask invalid data values in geolocation.
"""
if mask_area:
mask = kwargs.get("mask", np.zeros_like(data, dtype=np.bool))
if data.attrs.get("_FillValue"):
mask = xu.logical_and(data, data == data.attrs["_FillValue"])
if hasattr(data, "mask"):
mask = xu.logical_and(data, data.mask)
elif hasattr(data, "isnull"):
mask = xu.logical_and(data, data.isnull())
summing_dims = [dim for dim in data.dims if dim not in ["x", "y"]]
mask = mask.sum(dim=summing_dims).astype(bool)
kwargs["mask"] = mask
cache_id = self.precompute(cache_dir=cache_dir, **kwargs)
data.attrs["_last_resampler"] = self
return self.compute(data, cache_id=cache_id, **kwargs)
|
def resample(self, data, cache_dir=False, mask_area=True, **kwargs):
"""Resample the *data*, saving the projection info on disk if *precompute* evaluates to True.
:param mask_area: Provide data mask to `precompute` method to mask invalid data values in geolocation.
"""
if mask_area and hasattr(data, "mask"):
kwargs.setdefault("mask", data.mask)
cache_id = self.precompute(cache_dir=cache_dir, **kwargs)
return self.compute(data, cache_id=cache_id, **kwargs)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _read_params_from_cache(self, cache_dir, hash_str, filename):
"""Read resampling parameters from cache"""
self.cache = self.caches.pop(hash_str, None)
if self.cache is not None and cache_dir:
self.dump(filename)
elif os.path.exists(filename):
self.cache = dict(np.load(filename))
self.caches[hash_str] = self.cache
|
def _read_params_from_cache(self, cache_dir, hash_str, filename):
"""Read resampling parameters from cache"""
try:
self.cache = self.caches[hash_str]
# trick to keep most used caches away from deletion
del self.caches[hash_str]
self.caches[hash_str] = self.cache
if cache_dir:
self.dump(filename)
return
except KeyError:
if os.path.exists(filename):
self.cache = dict(np.load(filename))
self.caches[hash_str] = self.cache
while len(self.caches) > CACHE_SIZE:
self.caches.popitem(False)
if cache_dir:
self.dump(filename)
else:
self.cache = None
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _update_caches(self, hash_str, cache_dir, filename):
"""Update caches and dump new resampling parameters to disk"""
self.caches[hash_str] = self.cache
if cache_dir:
# XXX: Look in to doing memmap-able files instead
# `arr.tofile(filename)`
self.dump(filename)
|
def _update_caches(self, hash_str, cache_dir, filename):
"""Update caches and dump new resampling parameters to disk"""
self.caches[hash_str] = self.cache
while len(self.caches) > CACHE_SIZE:
self.caches.popitem(False)
if cache_dir:
# XXX: Look in to doing memmap-able files instead
# `arr.tofile(filename)`
self.dump(filename)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def precompute(
self,
mask=None,
radius_of_influence=10000,
epsilon=0,
reduce_data=True,
nprocs=1,
segments=None,
cache_dir=False,
**kwargs,
):
"""Create a KDTree structure and store it for later use.
Note: The `mask` keyword should be provided if geolocation may be valid
where data points are invalid. This defaults to the `mask` attribute of
the `data` numpy masked array passed to the `resample` method.
"""
del kwargs
source_geo_def = mask_source_lonlats(self.source_geo_def, mask)
kd_hash = self.get_hash(
source_geo_def=source_geo_def,
radius_of_influence=radius_of_influence,
epsilon=epsilon,
)
filename = self._create_cache_filename(cache_dir, kd_hash)
self._read_params_from_cache(cache_dir, kd_hash, filename)
if self.resampler is None:
if self.cache is not None:
LOG.debug("Loaded kd-tree parameters")
return self.cache
LOG.debug("Computing kd-tree parameters")
self.resampler = XArrayResamplerNN(
source_geo_def,
self.target_geo_def,
radius_of_influence,
neighbours=1,
epsilon=epsilon,
reduce_data=reduce_data,
nprocs=nprocs,
segments=segments,
)
valid_input_index, valid_output_index, index_array, distance_array = (
self.resampler.get_neighbour_info()
)
# reference call to pristine pyresample
# vii, voi, ia, da = get_neighbour_info(source_geo_def,
# self.target_geo_def,
# radius_of_influence,
# neighbours=1,
# epsilon=epsilon,
# reduce_data=reduce_data,
# nprocs=nprocs,
# segments=segments)
# it's important here not to modify the existing cache dictionary.
if cache_dir:
self.cache = {
"valid_input_index": valid_input_index,
"valid_output_index": valid_output_index,
"index_array": index_array,
"distance_array": distance_array,
"source_geo_def": source_geo_def,
}
self._update_caches(kd_hash, cache_dir, filename)
return self.cache
|
def precompute(
self,
mask=None,
radius_of_influence=10000,
epsilon=0,
reduce_data=True,
nprocs=1,
segments=None,
cache_dir=False,
**kwargs,
):
"""Create a KDTree structure and store it for later use.
Note: The `mask` keyword should be provided if geolocation may be valid where data points are invalid.
This defaults to the `mask` attribute of the `data` numpy masked array passed to the `resample` method.
"""
del kwargs
source_geo_def = mask_source_lonlats(self.source_geo_def, mask)
kd_hash = self.get_hash(
source_geo_def=source_geo_def,
radius_of_influence=radius_of_influence,
epsilon=epsilon,
)
filename = self._create_cache_filename(cache_dir, kd_hash)
self._read_params_from_cache(cache_dir, kd_hash, filename)
if self.cache is not None:
LOG.debug("Loaded kd-tree parameters")
return self.cache
else:
LOG.debug("Computing kd-tree parameters")
valid_input_index, valid_output_index, index_array, distance_array = (
get_neighbour_info(
source_geo_def,
self.target_geo_def,
radius_of_influence,
neighbours=1,
epsilon=epsilon,
reduce_data=reduce_data,
nprocs=nprocs,
segments=segments,
)
)
# it's important here not to modify the existing cache dictionary.
self.cache = {
"valid_input_index": valid_input_index,
"valid_output_index": valid_output_index,
"index_array": index_array,
"distance_array": distance_array,
"source_geo_def": source_geo_def,
}
self._update_caches(kd_hash, cache_dir, filename)
return self.cache
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def compute(
self, data, weight_funcs=None, fill_value=None, with_uncert=False, **kwargs
):
del kwargs
LOG.debug("Resampling " + str(data.name))
if fill_value is None:
fill_value = data.attrs.get("_FillValue")
res = self.resampler.get_sample_from_neighbour_info(data, fill_value)
return res
|
def compute(
self, data, weight_funcs=None, fill_value=None, with_uncert=False, **kwargs
):
del kwargs
return get_sample_from_neighbour_info(
"nn",
self.target_geo_def.shape,
data,
self.cache["valid_input_index"],
self.cache["valid_output_index"],
self.cache["index_array"],
distance_array=self.cache["distance_array"],
weight_funcs=weight_funcs,
fill_value=fill_value,
with_uncert=with_uncert,
)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def compute(
self,
data,
fill_value=0,
weight_count=10000,
weight_min=0.01,
weight_distance_max=1.0,
weight_sum_min=-1.0,
maximum_weight_mode=False,
**kwargs,
):
rows = self.cache["rows"]
cols = self.cache["cols"]
# if the data is scan based then check its metadata or the passed
# kwargs otherwise assume the entire input swath is one large
# "scanline"
rows_per_scan = getattr(data, "info", kwargs).get("rows_per_scan", data.shape[0])
if hasattr(data, "mask"):
mask = data.mask
data = data.data
data[mask] = np.nan
if data.ndim >= 3:
data_in = tuple(data[..., i] for i in range(data.shape[-1]))
else:
data_in = data
num_valid_points, res = fornav(
cols,
rows,
self.target_geo_def,
data_in,
rows_per_scan=rows_per_scan,
weight_count=weight_count,
weight_min=weight_min,
weight_distance_max=weight_distance_max,
weight_sum_min=weight_sum_min,
maximum_weight_mode=maximum_weight_mode,
)
if data.ndim >= 3:
# convert 'res' from tuple of arrays to one array
res = np.dstack(res)
num_valid_points = sum(num_valid_points)
grid_covered_ratio = num_valid_points / float(res.size)
grid_covered = grid_covered_ratio > self.grid_coverage
if not grid_covered:
msg = "EWA resampling only found %f%% of the grid covered "
"(need %f%%)" % (grid_covered_ratio * 100, self.grid_coverage * 100)
raise RuntimeError(msg)
LOG.debug(
"EWA resampling found %f%% of the grid covered" % (grid_covered_ratio * 100)
)
return np.ma.masked_invalid(res)
|
def compute(
self,
data,
fill_value=0,
weight_count=10000,
weight_min=0.01,
weight_distance_max=1.0,
weight_sum_min=-1.0,
maximum_weight_mode=False,
**kwargs,
):
rows = self.cache["rows"]
cols = self.cache["cols"]
# if the data is scan based then check its metadata or the passed
# kwargs otherwise assume the entire input swath is one large
# "scanline"
rows_per_scan = getattr(data, "info", kwargs).get("rows_per_scan", data.shape[0])
if hasattr(data, "mask"):
mask = data.mask
data = data.data
data[mask] = np.nan
if data.ndim >= 3:
data_in = tuple(data[..., i] for i in range(data.shape[-1]))
else:
data_in = data
num_valid_points, res = fornav(
cols,
rows,
self.target_geo_def,
data_in,
rows_per_scan=rows_per_scan,
weight_count=weight_count,
weight_min=weight_min,
weight_distance_max=weight_distance_max,
weight_sum_min=weight_sum_min,
maximum_weight_mode=maximum_weight_mode,
)
if data.ndim >= 3:
# convert 'res' from tuple of arrays to one array
res = np.dstack(res)
num_valid_points = sum(num_valid_points)
grid_covered_ratio = num_valid_points / float(res.size)
grid_covered = grid_covered_ratio > self.grid_coverage
if not grid_covered:
msg = "EWA resampling only found %f%% of the grid covered "
"(need %f%%)" % (grid_covered_ratio * 100, self.grid_coverage * 100)
raise RuntimeError(msg)
LOG.debug(
"EWA resampling found %f%% of the grid covered" % (grid_covered_ratio * 100)
)
return np.ma.masked_invalid(res)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def precompute(
self,
mask=None,
radius_of_influence=50000,
reduce_data=True,
nprocs=1,
segments=None,
cache_dir=False,
**kwargs,
):
"""Create bilinear coefficients and store them for later use.
Note: The `mask` keyword should be provided if geolocation may be valid
where data points are invalid. This defaults to the `mask` attribute of
the `data` numpy masked array passed to the `resample` method.
"""
del kwargs
source_geo_def = mask_source_lonlats(self.source_geo_def, mask)
bil_hash = self.get_hash(
source_geo_def=source_geo_def,
radius_of_influence=radius_of_influence,
mode="bilinear",
)
filename = self._create_cache_filename(cache_dir, bil_hash)
self._read_params_from_cache(cache_dir, bil_hash, filename)
if self.cache is not None:
LOG.debug("Loaded bilinear parameters")
return self.cache
else:
LOG.debug("Computing bilinear parameters")
bilinear_t, bilinear_s, input_idxs, idx_arr = get_bil_info(
source_geo_def,
self.target_geo_def,
radius_of_influence,
neighbours=32,
nprocs=nprocs,
masked=False,
)
self.cache = {
"bilinear_s": bilinear_s,
"bilinear_t": bilinear_t,
"input_idxs": input_idxs,
"idx_arr": idx_arr,
}
self._update_caches(bil_hash, cache_dir, filename)
return self.cache
|
def precompute(
self,
mask=None,
radius_of_influence=50000,
reduce_data=True,
nprocs=1,
segments=None,
cache_dir=False,
**kwargs,
):
"""Create bilinear coefficients and store them for later use.
Note: The `mask` keyword should be provided if geolocation may be valid
where data points are invalid. This defaults to the `mask` attribute of
the `data` numpy masked array passed to the `resample` method.
"""
del kwargs
source_geo_def = mask_source_lonlats(self.source_geo_def, mask)
bil_hash = self.get_hash(
source_geo_def=source_geo_def,
radius_of_influence=radius_of_influence,
mode="bilinear",
)
filename = self._create_cache_filename(cache_dir, bil_hash)
self._read_params_from_cache(cache_dir, bil_hash, filename)
if self.cache is not None:
LOG.debug("Loaded bilinear parameters")
return self.cache
else:
LOG.debug("Computing bilinear parameters")
bilinear_t, bilinear_s, input_idxs, idx_arr = get_bil_info(
source_geo_def,
self.target_geo_def,
radius_of_influence,
neighbours=32,
nprocs=nprocs,
masked=False,
)
self.cache = {
"bilinear_s": bilinear_s,
"bilinear_t": bilinear_t,
"input_idxs": input_idxs,
"idx_arr": idx_arr,
}
self._update_caches(bil_hash, cache_dir, filename)
return self.cache
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def compute(self, data, fill_value=None, **kwargs):
"""Resample the given data using bilinear interpolation"""
del kwargs
target_shape = self.target_geo_def.shape
if data.ndim == 3:
output_shape = list(target_shape)
output_shape.append(data.shape[-1])
res = np.zeros(output_shape, dtype=data.dtype)
for i in range(data.shape[-1]):
res[:, :, i] = get_sample_from_bil_info(
data[:, :, i].ravel(),
self.cache["bilinear_t"],
self.cache["bilinear_s"],
self.cache["input_idxs"],
self.cache["idx_arr"],
output_shape=target_shape,
)
else:
res = get_sample_from_bil_info(
data.ravel(),
self.cache["bilinear_t"],
self.cache["bilinear_s"],
self.cache["input_idxs"],
self.cache["idx_arr"],
output_shape=target_shape,
)
res = np.ma.masked_invalid(res)
return res
|
def compute(self, data, fill_value=None, **kwargs):
"""Resample the given data using bilinear interpolation"""
del kwargs
target_shape = self.target_geo_def.shape
if data.ndim == 3:
output_shape = list(target_shape)
output_shape.append(data.shape[-1])
res = np.zeros(output_shape, dtype=data.dtype)
for i in range(data.shape[-1]):
res[:, :, i] = get_sample_from_bil_info(
data[:, :, i].ravel(),
self.cache["bilinear_t"],
self.cache["bilinear_s"],
self.cache["input_idxs"],
self.cache["idx_arr"],
output_shape=target_shape,
)
else:
res = get_sample_from_bil_info(
data.ravel(),
self.cache["bilinear_t"],
self.cache["bilinear_s"],
self.cache["input_idxs"],
self.cache["idx_arr"],
output_shape=target_shape,
)
res = np.ma.masked_invalid(res)
return res
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def mask_source_lonlats(source_def, mask):
"""Mask source longitudes and latitudes to match data mask"""
source_geo_def = source_def
# the data may have additional masked pixels
# let's compare them to see if we can use the same area
# assume lons and lats mask are the same
if isinstance(source_geo_def, SwathDefinition):
if np.issubsctype(mask.dtype, np.bool):
# copy the source area and use it for the rest of the calculations
LOG.debug("Copying source area to mask invalid dataset points")
# source_geo_def = deepcopy(source_geo_def)
# lons, lats = source_geo_def.get_lonlats()
if np.ndim(mask) == 3:
# FIXME: we should treat 3d arrays (composites) layer by layer!
mask = np.sum(mask, axis=2)
# FIXME: pyresample doesn't seem to like this
# lons = np.tile(lons, (1, 1, mask.shape[2]))
# lats = np.tile(lats, (1, 1, mask.shape[2]))
# use the same data, but make a new mask (i.e. don't affect the original masked array)
# the ma.array function combines the undelying mask with the new
# one (OR)
source_geo_def.lons = source_geo_def.lons.where(~mask)
source_geo_def.lats = source_geo_def.lats.where(~mask)
# source_geo_def.lons = np.ma.array(lons, mask=mask)
# source_geo_def.lats = np.ma.array(lats, mask=mask)
else:
import xarray.ufuncs as xu
return SwathDefinition(
source_geo_def.lons.where(~xu.isnan(mask)),
source_geo_def.lats.where(~xu.isnan(mask)),
)
# This was evil
# source_geo_def.lons = source_geo_def.lons.where(~xu.isnan(mask))
# source_geo_def.lats = source_geo_def.lats.where(~xu.isnan(mask))
return source_geo_def
|
def mask_source_lonlats(source_def, mask):
"""Mask source longitudes and latitudes to match data mask"""
source_geo_def = source_def
# the data may have additional masked pixels
# let's compare them to see if we can use the same area
# assume lons and lats mask are the same
if np.any(mask) and isinstance(source_geo_def, SwathDefinition):
# copy the source area and use it for the rest of the calculations
LOG.debug("Copying source area to mask invalid dataset points")
source_geo_def = deepcopy(source_geo_def)
lons, lats = source_geo_def.get_lonlats()
if np.ndim(mask) == 3:
# FIXME: we should treat 3d arrays (composites) layer by layer!
mask = np.sum(mask, axis=2)
# FIXME: pyresample doesn't seem to like this
# lons = np.tile(lons, (1, 1, mask.shape[2]))
# lats = np.tile(lats, (1, 1, mask.shape[2]))
# use the same data, but make a new mask (i.e. don't affect the original masked array)
# the ma.array function combines the undelying mask with the new
# one (OR)
source_geo_def.lons = np.ma.array(lons, mask=mask)
source_geo_def.lats = np.ma.array(lats, mask=mask)
return source_geo_def
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __init__(
self,
filenames=None,
reader=None,
filter_parameters=None,
reader_kwargs=None,
ppp_config_dir=get_environ_config_dir(),
base_dir=None,
sensor=None,
start_time=None,
end_time=None,
area=None,
):
"""Initialize Scene with Reader and Compositor objects.
To load data `filenames` and preferably `reader` must be specified. If `filenames` is provided without `reader`
then the available readers will be searched for a Reader that can support the provided files. This can take
a considerable amount of time so it is recommended that `reader` always be provided. Note without `filenames`
the Scene is created with no Readers available requiring Datasets to be added manually::
scn = Scene()
scn['my_dataset'] = Dataset(my_data_array, **my_info)
Args:
filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object
should map reader names to a list of filenames for that reader.
reader (str or list): The name of the reader to use for loading the data or a list of names.
filter_parameters (dict): Specify loaded file filtering parameters.
Shortcut for `reader_kwargs['filter_parameters']`.
reader_kwargs (dict): Keyword arguments to pass to specific reader instances.
ppp_config_dir (str): The directory containing the configuration files for satpy.
base_dir (str): (DEPRECATED) The directory to search for files containing the
data to load. If *filenames* is also provided,
this is ignored.
sensor (list or str): (DEPRECATED: Use `find_files_and_readers` function) Limit used files by provided
sensors.
area (AreaDefinition): (DEPRECATED: Use `filter_parameters`) Limit used files by geographic area.
start_time (datetime): (DEPRECATED: Use `filter_parameters`) Limit used files by starting time.
end_time (datetime): (DEPRECATED: Use `filter_parameters`) Limit used files by ending time.
"""
super(Scene, self).__init__()
# Set the PPP_CONFIG_DIR in the environment in case it's used elsewhere in pytroll
LOG.debug("Setting 'PPP_CONFIG_DIR' to '%s'", ppp_config_dir)
os.environ["PPP_CONFIG_DIR"] = self.ppp_config_dir = ppp_config_dir
if not filenames and (start_time or end_time or base_dir):
import warnings
warnings.warn(
"Deprecated: Use "
+ "'from satpy import find_files_and_readers' to find files"
)
from satpy import find_files_and_readers
filenames = find_files_and_readers(
start_time=start_time,
end_time=end_time,
base_dir=base_dir,
reader=reader,
sensor=sensor,
ppp_config_dir=self.ppp_config_dir,
reader_kwargs=reader_kwargs,
)
elif start_time or end_time or area:
import warnings
warnings.warn(
"Deprecated: Use "
+ "'filter_parameters' to filter loaded files by 'start_time', "
+ "'end_time', or 'area'."
)
fp = filter_parameters if filter_parameters else {}
fp.update(
{
"start_time": start_time,
"end_time": end_time,
"area": area,
}
)
filter_parameters = fp
if filter_parameters:
if reader_kwargs is None:
reader_kwargs = {}
reader_kwargs.setdefault("filter_parameters", {}).update(filter_parameters)
self.readers = self.create_reader_instances(
filenames=filenames, reader=reader, reader_kwargs=reader_kwargs
)
self.attrs.update(self._compute_metadata_from_readers())
self.datasets = DatasetDict()
self.cpl = CompositorLoader(self.ppp_config_dir)
comps, mods = self.cpl.load_compositors(self.attrs["sensor"])
self.wishlist = set()
self.dep_tree = DependencyTree(self.readers, comps, mods)
|
def __init__(
self,
filenames=None,
reader=None,
filter_parameters=None,
reader_kwargs=None,
ppp_config_dir=get_environ_config_dir(),
base_dir=None,
sensor=None,
start_time=None,
end_time=None,
area=None,
):
"""Initialize Scene with Reader and Compositor objects.
To load data `filenames` and preferably `reader` must be specified. If `filenames` is provided without `reader`
then the available readers will be searched for a Reader that can support the provided files. This can take
a considerable amount of time so it is recommended that `reader` always be provided. Note without `filenames`
the Scene is created with no Readers available requiring Datasets to be added manually::
scn = Scene()
scn['my_dataset'] = Dataset(my_data_array, **my_info)
Args:
filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object
should map reader names to a list of filenames for that reader.
reader (str or list): The name of the reader to use for loading the data or a list of names.
filter_parameters (dict): Specify loaded file filtering parameters.
Shortcut for `reader_kwargs['filter_parameters']`.
reader_kwargs (dict): Keyword arguments to pass to specific reader instances.
ppp_config_dir (str): The directory containing the configuration files for satpy.
base_dir (str): (DEPRECATED) The directory to search for files containing the
data to load. If *filenames* is also provided,
this is ignored.
sensor (list or str): (DEPRECATED: Use `find_files_and_readers` function) Limit used files by provided
sensors.
area (AreaDefinition): (DEPRECATED: Use `filter_parameters`) Limit used files by geographic area.
start_time (datetime): (DEPRECATED: Use `filter_parameters`) Limit used files by starting time.
end_time (datetime): (DEPRECATED: Use `filter_parameters`) Limit used files by ending time.
"""
super(Scene, self).__init__()
# Set the PPP_CONFIG_DIR in the environment in case it's used elsewhere in pytroll
LOG.debug("Setting 'PPP_CONFIG_DIR' to '%s'", ppp_config_dir)
os.environ["PPP_CONFIG_DIR"] = self.ppp_config_dir = ppp_config_dir
if not filenames and (start_time or end_time or base_dir):
import warnings
warnings.warn(
"Deprecated: Use "
+ "'from satpy import find_files_and_readers' to find files"
)
from satpy import find_files_and_readers
filenames = find_files_and_readers(
start_time=start_time,
end_time=end_time,
base_dir=base_dir,
reader=reader,
sensor=sensor,
ppp_config_dir=self.ppp_config_dir,
reader_kwargs=reader_kwargs,
)
elif start_time or end_time or area:
import warnings
warnings.warn(
"Deprecated: Use "
+ "'filter_parameters' to filter loaded files by 'start_time', "
+ "'end_time', or 'area'."
)
fp = filter_parameters if filter_parameters else {}
fp.update(
{
"start_time": start_time,
"end_time": end_time,
"area": area,
}
)
filter_parameters = fp
if filter_parameters:
if reader_kwargs is None:
reader_kwargs = {}
reader_kwargs.setdefault("filter_parameters", {}).update(filter_parameters)
self.readers = self.create_reader_instances(
filenames=filenames, reader=reader, reader_kwargs=reader_kwargs
)
self.info.update(self._compute_metadata_from_readers())
self.datasets = DatasetDict()
self.cpl = CompositorLoader(self.ppp_config_dir)
comps, mods = self.cpl.load_compositors(self.info["sensor"])
self.wishlist = set()
self.dep_tree = DependencyTree(self.readers, comps, mods)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _get_sensor_names(self):
"""Join the sensors from all loaded readers."""
# if the user didn't tell us what sensors to work with, let's figure it
# out
if not self.attrs.get("sensor"):
# reader finder could return multiple readers
return set(
[
sensor
for reader_instance in self.readers.values()
for sensor in reader_instance.sensor_names
]
)
elif not isinstance(self.attrs["sensor"], (set, tuple, list)):
return set([self.attrs["sensor"]])
else:
return set(self.attrs["sensor"])
|
def _get_sensor_names(self):
"""Join the sensors from all loaded readers."""
# if the user didn't tell us what sensors to work with, let's figure it
# out
if not self.info.get("sensor"):
# reader finder could return multiple readers
return set(
[
sensor
for reader_instance in self.readers.values()
for sensor in reader_instance.sensor_names
]
)
elif not isinstance(self.info["sensor"], (set, tuple, list)):
return set([self.info["sensor"]])
else:
return set(self.info["sensor"])
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def start_time(self):
"""Return the start time of the file."""
return self.attrs["start_time"]
|
def start_time(self):
"""Return the start time of the file."""
return self.info["start_time"]
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def end_time(self):
"""Return the end time of the file."""
return self.attrs["end_time"]
|
def end_time(self):
"""Return the end time of the file."""
return self.info["end_time"]
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def available_composite_ids(self, available_datasets=None):
"""Get names of compositors that can be generated from the available
datasets.
:return: generator of available compositor's names
"""
if available_datasets is None:
available_datasets = self.available_dataset_ids(composites=False)
else:
if not all(isinstance(ds_id, DatasetID) for ds_id in available_datasets):
raise ValueError("'available_datasets' must all be DatasetID objects")
all_comps = self.all_composite_ids()
# recreate the dependency tree so it doesn't interfere with the user's
# wishlist
comps, mods = self.cpl.load_compositors(self.attrs["sensor"])
dep_tree = DependencyTree(self.readers, comps, mods)
unknowns = dep_tree.find_dependencies(set(available_datasets + all_comps))
available_comps = set(x.name for x in dep_tree.trunk())
# get rid of modified composites that are in the trunk
return sorted(available_comps & set(all_comps))
|
def available_composite_ids(self, available_datasets=None):
"""Get names of compositors that can be generated from the available
datasets.
:return: generator of available compositor's names
"""
if available_datasets is None:
available_datasets = self.available_dataset_ids(composites=False)
else:
if not all(isinstance(ds_id, DatasetID) for ds_id in available_datasets):
raise ValueError("'available_datasets' must all be DatasetID objects")
all_comps = self.all_composite_ids()
# recreate the dependency tree so it doesn't interfere with the user's
# wishlist
comps, mods = self.cpl.load_compositors(self.info["sensor"])
dep_tree = DependencyTree(self.readers, comps, mods)
unknowns = dep_tree.find_dependencies(set(available_datasets + all_comps))
available_comps = set(x.name for x in dep_tree.trunk())
# get rid of modified composites that are in the trunk
return sorted(available_comps & set(all_comps))
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def all_composite_ids(self, sensor_names=None):
"""Get all composite IDs that are configured.
:return: generator of configured composite names
"""
if sensor_names is None:
sensor_names = self.attrs["sensor"]
compositors = []
# Note if we get compositors from the dep tree then it will include
# modified composites which we don't want
for sensor_name in sensor_names:
compositors.extend(self.cpl.compositors.get(sensor_name, {}).keys())
return sorted(set(compositors))
|
def all_composite_ids(self, sensor_names=None):
"""Get all composite IDs that are configured.
:return: generator of configured composite names
"""
if sensor_names is None:
sensor_names = self.info["sensor"]
compositors = []
# Note if we get compositors from the dep tree then it will include
# modified composites which we don't want
for sensor_name in sensor_names:
compositors.extend(self.cpl.compositors.get(sensor_name, {}).keys())
return sorted(set(compositors))
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def iter_by_area(self):
"""Generate datasets grouped by Area.
:return: generator of (area_obj, list of dataset objects)
"""
datasets_by_area = {}
for ds in self:
a = ds.attrs.get("area")
a_str = str(a) if a is not None else None
datasets_by_area.setdefault(a_str, (a, []))
datasets_by_area[a_str][1].append(DatasetID.from_dict(ds.attrs))
for area_name, (area_obj, ds_list) in datasets_by_area.items():
yield area_obj, ds_list
|
def iter_by_area(self):
"""Generate datasets grouped by Area.
:return: generator of (area_obj, list of dataset objects)
"""
datasets_by_area = {}
for ds in self:
a = ds.info.get("area")
a_str = str(a) if a is not None else None
datasets_by_area.setdefault(a_str, (a, []))
datasets_by_area[a_str][1].append(ds.id)
for area_name, (area_obj, ds_list) in datasets_by_area.items():
yield area_obj, ds_list
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def __setitem__(self, key, value):
"""Add the item to the scene."""
self.datasets[key] = value
ds_id = self.datasets.get_key(key)
self.wishlist.add(ds_id)
self.dep_tree.add_leaf(ds_id)
|
def __setitem__(self, key, value):
"""Add the item to the scene."""
if not isinstance(value, Dataset):
raise ValueError("Only 'Dataset' objects can be assigned")
self.datasets[key] = value
ds_id = self.datasets.get_key(key)
self.wishlist.add(ds_id)
self.dep_tree.add_leaf(ds_id)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _generate_composite(self, comp_node, keepables):
"""Collect all composite prereqs and create the specified composite.
Args:
comp_node (Node): Composite Node to generate a Dataset for
keepables (set): `set` to update if any datasets are needed
when generation is continued later. This can
happen if generation is delayed to incompatible
areas which would require resampling first.
"""
if comp_node.name in self.datasets:
# already loaded
return
compositor, prereqs, optional_prereqs = comp_node.data
try:
prereq_datasets = self._get_prereq_datasets(
comp_node.name,
prereqs,
keepables,
)
except KeyError:
return
optional_datasets = self._get_prereq_datasets(
comp_node.name, optional_prereqs, keepables, skip=True
)
try:
composite = compositor(
prereq_datasets, optional_datasets=optional_datasets, **self.attrs
)
cid = DatasetID.from_dict(composite.attrs)
self.datasets[cid] = composite
# update the node with the computed DatasetID
if comp_node.name in self.wishlist:
self.wishlist.remove(comp_node.name)
self.wishlist.add(cid)
comp_node.name = cid
except IncompatibleAreas:
LOG.warning(
"Delaying generation of %s because of incompatible areas",
str(compositor.id),
)
preservable_datasets = set(self.datasets.keys())
prereq_ids = set(p.name for p in prereqs)
opt_prereq_ids = set(p.name for p in optional_prereqs)
keepables |= preservable_datasets & (prereq_ids | opt_prereq_ids)
# even though it wasn't generated keep a list of what
# might be needed in other compositors
keepables.add(comp_node.name)
return
|
def _generate_composite(self, comp_node, keepables):
"""Collect all composite prereqs and create the specified composite.
Args:
comp_node (Node): Composite Node to generate a Dataset for
keepables (set): `set` to update if any datasets are needed
when generation is continued later. This can
happen if generation is delayed to incompatible
areas which would require resampling first.
"""
if comp_node.name in self.datasets:
# already loaded
return
compositor, prereqs, optional_prereqs = comp_node.data
try:
prereq_datasets = self._get_prereq_datasets(
comp_node.name,
prereqs,
keepables,
)
except KeyError:
return
optional_datasets = self._get_prereq_datasets(
comp_node.name, optional_prereqs, keepables, skip=True
)
try:
composite = compositor(
prereq_datasets, optional_datasets=optional_datasets, **self.info
)
self.datasets[composite.id] = composite
if comp_node.name in self.wishlist:
self.wishlist.remove(comp_node.name)
self.wishlist.add(composite.id)
# update the node with the computed DatasetID
comp_node.name = composite.id
except IncompatibleAreas:
LOG.warning(
"Delaying generation of %s because of incompatible areas",
str(compositor.id),
)
preservable_datasets = set(self.datasets.keys())
prereq_ids = set(p.name for p in prereqs)
opt_prereq_ids = set(p.name for p in optional_prereqs)
keepables |= preservable_datasets & (prereq_ids | opt_prereq_ids)
# even though it wasn't generated keep a list of what
# might be needed in other compositors
keepables.add(comp_node.name)
return
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def resample(
self, destination, datasets=None, compute=True, unload=True, **resample_kwargs
):
"""Resample the datasets and return a new scene."""
to_resample = [
dataset
for (dsid, dataset) in self.datasets.items()
if (not datasets) or dsid in datasets
]
new_scn = self._resampled_scene(to_resample, destination, **resample_kwargs)
new_scn.attrs = self.attrs.copy()
new_scn.dep_tree = self.dep_tree.copy()
# MUST set this after assigning the resampled datasets otherwise
# composite prereqs that were resampled will be considered "wishlisted"
if datasets is None:
new_scn.wishlist = self.wishlist
else:
new_scn.wishlist = set([DatasetID.from_dict(ds.attrs) for ds in new_scn])
# recompute anything from the wishlist that needs it (combining
# multiple resolutions, etc.)
keepables = None
if compute:
nodes = [
self.dep_tree[i]
for i in new_scn.wishlist
if i in self.dep_tree and not self.dep_tree[i].is_leaf
]
keepables = new_scn.compute(nodes=nodes)
if new_scn.missing_datasets:
# copy the set of missing datasets because they won't be valid
# after they are removed in the next line
missing = new_scn.missing_datasets.copy()
new_scn._remove_failed_datasets(keepables)
missing_str = ", ".join(str(x) for x in missing)
LOG.warning("The following datasets were not created: {}".format(missing_str))
if unload:
new_scn.unload(keepables)
return new_scn
|
def resample(
self, destination, datasets=None, compute=True, unload=True, **resample_kwargs
):
"""Resample the datasets and return a new scene."""
new_scn = Scene()
new_scn.info = self.info.copy()
# new_scn.cpl = self.cpl
new_scn.dep_tree = self.dep_tree.copy()
for ds_id, projectable in self.datasets.items():
LOG.debug("Resampling %s", ds_id)
if datasets and ds_id not in datasets:
continue
new_scn[ds_id] = projectable.resample(destination, **resample_kwargs)
# MUST set this after assigning the resampled datasets otherwise
# composite prereqs that were resampled will be considered "wishlisted"
if datasets is None:
new_scn.wishlist = self.wishlist
else:
new_scn.wishlist = set([ds.id for ds in new_scn])
# recompute anything from the wishlist that needs it (combining multiple
# resolutions, etc.)
keepables = None
if compute:
nodes = [
self.dep_tree[i] for i in new_scn.wishlist if not self.dep_tree[i].is_leaf
]
keepables = new_scn.compute(nodes=nodes)
if new_scn.missing_datasets:
# copy the set of missing datasets because they won't be valid
# after they are removed in the next line
missing = new_scn.missing_datasets.copy()
new_scn._remove_failed_datasets(keepables)
missing_str = ", ".join(str(x) for x in missing)
LOG.warning("The following datasets were not created: {}".format(missing_str))
if unload:
new_scn.unload(keepables)
return new_scn
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def show(self, dataset_id, overlay=None):
"""Show the *dataset* on screen as an image."""
from satpy.writers import get_enhanced_image
img = get_enhanced_image(self[dataset_id].squeeze(), overlay=overlay)
img.show()
return img
|
def show(self, dataset_id, overlay=None):
"""Show the *dataset* on screen as an image."""
from satpy.writers import get_enhanced_image
get_enhanced_image(self[dataset_id], overlay=overlay).show()
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def load_writer_config(self, config_files, **kwargs):
"""Load the writer config for *config_files*."""
conf = {}
for conf_fn in config_files:
with open(conf_fn) as fd:
conf = recursive_dict_update(conf, yaml.load(fd))
writer_class = conf["writer"]["writer"]
writer = writer_class(
ppp_config_dir=self.ppp_config_dir, config_files=config_files, **kwargs
)
return writer
|
def load_writer_config(self, config_files, **kwargs):
conf = {}
for conf_fn in config_files:
with open(conf_fn) as fd:
conf = recursive_dict_update(conf, yaml.load(fd))
writer_class = conf["writer"]["writer"]
writer = writer_class(
ppp_config_dir=self.ppp_config_dir, config_files=config_files, **kwargs
)
return writer
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, **kwargs):
"""Save the *dataset_id* to file using *writer* (default: geotiff)."""
if writer is None:
if filename is None:
writer = self.get_writer("geotiff", **kwargs)
else:
writer = self.get_writer_by_ext(os.path.splitext(filename)[1], **kwargs)
else:
writer = self.get_writer(writer, **kwargs)
writer.save_dataset(self[dataset_id], filename=filename, overlay=overlay, **kwargs)
|
def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, **kwargs):
"""Save the *dataset_id* to file using *writer* (geotiff by default)."""
if writer is None:
if filename is None:
writer = self.get_writer("geotiff", **kwargs)
else:
writer = self.get_writer_by_ext(os.path.splitext(filename)[1], **kwargs)
else:
writer = self.get_writer(writer, **kwargs)
writer.save_dataset(self[dataset_id], filename=filename, overlay=overlay, **kwargs)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_writer(self, writer="geotiff", **kwargs):
"""Get the writer instance."""
config_fn = writer + ".yaml" if "." not in writer else writer
config_files = config_search_paths(
os.path.join("writers", config_fn), self.ppp_config_dir
)
kwargs.setdefault("config_files", config_files)
return self.load_writer_config(**kwargs)
|
def get_writer(self, writer="geotiff", **kwargs):
config_fn = writer + ".yaml" if "." not in writer else writer
config_files = config_search_paths(
os.path.join("writers", config_fn), self.ppp_config_dir
)
kwargs.setdefault("config_files", config_files)
return self.load_writer_config(**kwargs)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_writer_by_ext(self, extension, **kwargs):
"""Find the writer matching the *extension*."""
mapping = {".tiff": "geotiff", ".tif": "geotiff", ".nc": "cf"}
return self.get_writer(mapping.get(extension.lower(), "simple_image"), **kwargs)
|
def get_writer_by_ext(self, extension, **kwargs):
mapping = {".tiff": "geotiff", ".tif": "geotiff", ".nc": "cf"}
return self.get_writer(mapping.get(extension.lower(), "simple_image"), **kwargs)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def lonlat2xyz(lon, lat):
"""Convert lon lat to cartesian."""
lat = xu.deg2rad(lat)
lon = xu.deg2rad(lon)
x = xu.cos(lat) * xu.cos(lon)
y = xu.cos(lat) * xu.sin(lon)
z = xu.sin(lat)
return x, y, z
|
def lonlat2xyz(lon, lat):
"""Convert lon lat to cartesian."""
lat = np.deg2rad(lat)
lon = np.deg2rad(lon)
x = np.cos(lat) * np.cos(lon)
y = np.cos(lat) * np.sin(lon)
z = np.sin(lat)
return x, y, z
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def xyz2lonlat(x, y, z):
"""Convert cartesian to lon lat."""
lon = xu.rad2deg(xu.arctan2(y, x))
lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))
return lon, lat
|
def xyz2lonlat(x, y, z):
"""Convert cartesian to lon lat."""
lon = np.rad2deg(np.arctan2(y, x))
lat = np.rad2deg(np.arctan2(z, np.sqrt(x**2 + y**2)))
return lon, lat
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def angle2xyz(azi, zen):
"""Convert azimuth and zenith to cartesian."""
azi = xu.deg2rad(azi)
zen = xu.deg2rad(zen)
x = xu.sin(zen) * xu.sin(azi)
y = xu.sin(zen) * xu.cos(azi)
z = xu.cos(zen)
return x, y, z
|
def angle2xyz(azi, zen):
"""Convert azimuth and zenith to cartesian."""
azi = np.deg2rad(azi)
zen = np.deg2rad(zen)
x = np.sin(zen) * np.sin(azi)
y = np.sin(zen) * np.cos(azi)
z = np.cos(zen)
return x, y, z
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def xyz2angle(x, y, z):
"""Convert cartesian to azimuth and zenith."""
azi = xu.rad2deg(xu.arctan2(x, y))
zen = 90 - xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))
return azi, zen
|
def xyz2angle(x, y, z):
"""Convert cartesian to azimuth and zenith."""
azi = np.rad2deg(np.arctan2(x, y))
zen = 90 - np.rad2deg(np.arctan2(z, np.sqrt(x**2 + y**2)))
return azi, zen
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _determine_mode(dataset):
if "mode" in dataset.attrs:
return dataset.attrs["mode"]
if dataset.ndim == 2:
return "L"
elif dataset.shape[0] == 2:
return "LA"
elif dataset.shape[0] == 3:
return "RGB"
elif dataset.shape[0] == 4:
return "RGBA"
else:
raise RuntimeError("Can't determine 'mode' of dataset: %s" % str(dataset))
|
def _determine_mode(dataset):
if "mode" in dataset.info:
return dataset.info["mode"]
if dataset.ndim == 2:
return "L"
elif dataset.shape[0] == 2:
return "LA"
elif dataset.shape[0] == 3:
return "RGB"
elif dataset.shape[0] == 4:
return "RGBA"
else:
raise RuntimeError("Can't determine 'mode' of dataset: %s" % (dataset.id,))
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def add_overlay(
orig,
area,
coast_dir,
color=(0, 0, 0),
width=0.5,
resolution=None,
level_coast=1,
level_borders=1,
):
"""Add coastline and political borders to image, using *color* (tuple
of integers between 0 and 255).
Warning: Loses the masks !
*resolution* is chosen automatically if None (default), otherwise it should be one of:
+-----+-------------------------+---------+
| 'f' | Full resolution | 0.04 km |
| 'h' | High resolution | 0.2 km |
| 'i' | Intermediate resolution | 1.0 km |
| 'l' | Low resolution | 5.0 km |
| 'c' | Crude resolution | 25 km |
+-----+-------------------------+---------+
"""
if orig.mode.startswith("L"):
orig.channels = [
orig.channels[0].copy(),
orig.channels[0].copy(),
orig.channels[0],
] + orig.channels[1:]
orig.mode = "RGB" + orig.mode[1:]
img = orig.pil_image()
if area is None:
raise ValueError("Area of image is None, can't add overlay.")
from pycoast import ContourWriterAGG
from satpy.resample import get_area_def
if isinstance(area, str):
area = get_area_def(area)
LOG.info("Add coastlines and political borders to image.")
if resolution is None:
x_resolution = (area.area_extent[2] - area.area_extent[0]) / area.x_size
y_resolution = (area.area_extent[3] - area.area_extent[1]) / area.y_size
res = min(x_resolution, y_resolution)
if res > 25000:
resolution = "c"
elif res > 5000:
resolution = "l"
elif res > 1000:
resolution = "i"
elif res > 200:
resolution = "h"
else:
resolution = "f"
LOG.debug("Automagically choose resolution " + resolution)
if img.mode.endswith("A"):
img = img.convert("RGBA")
else:
img = img.convert("RGB")
cw_ = ContourWriterAGG(coast_dir)
cw_.add_coastlines(
img, area, outline=color, resolution=resolution, width=width, level=level_coast
)
cw_.add_borders(
img,
area,
outline=color,
resolution=resolution,
width=width,
level=level_borders,
)
arr = np.array(img)
if orig.mode == "L":
orig.channels[0] = np.ma.array(arr[:, :, 0] / 255.0)
elif orig.mode == "LA":
orig.channels[0] = np.ma.array(arr[:, :, 0] / 255.0)
orig.channels[1] = np.ma.array(arr[:, :, -1] / 255.0)
else:
for idx in range(len(orig.channels)):
orig.channels[idx] = np.ma.array(arr[:, :, idx] / 255.0)
|
def add_overlay(
orig,
area,
coast_dir,
color=(0, 0, 0),
width=0.5,
resolution=None,
level_coast=1,
level_borders=1,
):
"""Add coastline and political borders to image, using *color* (tuple
of integers between 0 and 255).
Warning: Loses the masks !
*resolution* is chosen automatically if None (default), otherwise it should be one of:
+-----+-------------------------+---------+
| 'f' | Full resolution | 0.04 km |
| 'h' | High resolution | 0.2 km |
| 'i' | Intermediate resolution | 1.0 km |
| 'l' | Low resolution | 5.0 km |
| 'c' | Crude resolution | 25 km |
+-----+-------------------------+---------+
"""
img = orig.pil_image()
if area is None:
raise ValueError("Area of image is None, can't add overlay.")
from pycoast import ContourWriterAGG
from satpy.resample import get_area_def
if isinstance(area, str):
area = get_area_def(area)
LOG.info("Add coastlines and political borders to image.")
if resolution is None:
x_resolution = (area.area_extent[2] - area.area_extent[0]) / area.x_size
y_resolution = (area.area_extent[3] - area.area_extent[1]) / area.y_size
res = min(x_resolution, y_resolution)
if res > 25000:
resolution = "c"
elif res > 5000:
resolution = "l"
elif res > 1000:
resolution = "i"
elif res > 200:
resolution = "h"
else:
resolution = "f"
LOG.debug("Automagically choose resolution " + resolution)
if img.mode.endswith("A"):
img = img.convert("RGBA")
else:
img = img.convert("RGB")
cw_ = ContourWriterAGG(coast_dir)
cw_.add_coastlines(
img, area, outline=color, resolution=resolution, width=width, level=level_coast
)
cw_.add_borders(
img,
area,
outline=color,
resolution=resolution,
width=width,
level=level_borders,
)
arr = np.array(img)
if orig.mode == "L":
orig.channels[0] = np.ma.array(arr[:, :, 0] / 255.0)
elif orig.mode == "LA":
orig.channels[0] = np.ma.array(arr[:, :, 0] / 255.0)
orig.channels[1] = np.ma.array(arr[:, :, -1] / 255.0)
else:
for idx in range(len(orig.channels)):
orig.channels[idx] = np.ma.array(arr[:, :, idx] / 255.0)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def get_enhanced_image(
dataset,
enhancer=None,
fill_value=None,
ppp_config_dir=None,
enhancement_config_file=None,
overlay=None,
decorate=None,
):
mode = _determine_mode(dataset)
if ppp_config_dir is None:
ppp_config_dir = get_environ_config_dir()
if enhancer is None:
enhancer = Enhancer(ppp_config_dir, enhancement_config_file)
if enhancer.enhancement_tree is None:
raise RuntimeError(
"No enhancement configuration files found or specified, cannot"
" automatically enhance dataset"
)
if dataset.attrs.get("sensor", None):
enhancer.add_sensor_enhancements(dataset.attrs["sensor"])
# Create an image for enhancement
img = to_image(dataset, mode=mode, fill_value=fill_value)
enhancer.apply(img, **dataset.attrs)
img.info.update(dataset.attrs)
if overlay is not None:
add_overlay(img, dataset.attrs["area"], **overlay)
if decorate is not None:
add_decorate(img, **decorate)
return img
|
def get_enhanced_image(
dataset,
enhancer=None,
fill_value=None,
ppp_config_dir=None,
enhancement_config_file=None,
overlay=None,
decorate=None,
):
mode = _determine_mode(dataset)
if ppp_config_dir is None:
ppp_config_dir = get_environ_config_dir()
if enhancer is None:
enhancer = Enhancer(ppp_config_dir, enhancement_config_file)
if enhancer.enhancement_tree is None:
raise RuntimeError(
"No enhancement configuration files found or specified, cannot"
" automatically enhance dataset"
)
if dataset.info.get("sensor", None):
enhancer.add_sensor_enhancements(dataset.info["sensor"])
# Create an image for enhancement
img = to_image(dataset, mode=mode, fill_value=fill_value)
enhancer.apply(img, **dataset.info)
img.info.update(dataset.info)
if overlay is not None:
add_overlay(img, dataset.info["area"], **overlay)
if decorate is not None:
add_decorate(img, **decorate)
return img
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def show(dataset, **kwargs):
"""Display the dataset as an image."""
img = get_enhanced_image(dataset.squeeze(), **kwargs)
img.show()
return img
|
def show(dataset, **kwargs):
"""Display the dataset as an image."""
if not dataset.is_loaded():
raise ValueError("Dataset not loaded, cannot display.")
img = get_enhanced_image(dataset, **kwargs)
img.show()
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def to_image(dataset, copy=False, **kwargs):
# Only add keywords if they are present
for key in ["mode", "fill_value", "palette"]:
if key in dataset.attrs:
kwargs.setdefault(key, dataset.attrs[key])
dataset = dataset.squeeze()
if "bands" in dataset.dims:
return Image(
[
np.ma.masked_invalid(dataset.sel(bands=band).values)
for band in dataset["bands"]
],
copy=copy,
**kwargs,
)
elif dataset.ndim < 2:
raise ValueError("Need at least a 2D array to make an image.")
else:
return Image([np.ma.masked_invalid(dataset.values)], copy=copy, **kwargs)
|
def to_image(dataset, copy=True, **kwargs):
# Only add keywords if they are present
for key in ["mode", "fill_value", "palette"]:
if key in dataset.info:
kwargs.setdefault(key, dataset.info[key])
if dataset.ndim == 2:
return Image([dataset], copy=copy, **kwargs)
elif dataset.ndim == 3:
return Image([band for band in dataset], copy=copy, **kwargs)
else:
raise ValueError(
"Don't know how to convert array with ndim %d to image" % dataset.ndim
)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def save_dataset(
self, dataset, filename=None, fill_value=None, overlay=None, decorate=None, **kwargs
):
"""Saves the *dataset* to a given *filename*."""
fill_value = fill_value if fill_value is not None else self.fill_value
img = get_enhanced_image(
dataset.squeeze(), self.enhancer, fill_value, overlay=overlay, decorate=decorate
)
self.save_image(img, filename=filename, **kwargs)
|
def save_dataset(
self, dataset, filename=None, fill_value=None, overlay=None, decorate=None, **kwargs
):
"""Saves the *dataset* to a given *filename*."""
fill_value = fill_value if fill_value is not None else self.fill_value
img = get_enhanced_image(
dataset, self.enhancer, fill_value, overlay=overlay, decorate=decorate
)
self.save_image(img, filename=filename, **kwargs)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def omerc2cf(proj_dict):
"""Return the cf grid mapping for the omerc projection."""
if "no_rot" in proj_dict:
no_rotation = " "
else:
no_rotation = None
args = dict(
azimuth_of_central_line=proj_dict.get("alpha"),
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lonc"),
grid_mapping_name="oblique_mercator",
# longitude_of_projection_origin=0.,
no_rotation=no_rotation,
# reference_ellipsoid_name=proj_dict.get('ellps'),
semi_major_axis=6378137.0,
semi_minor_axis=6356752.3142,
false_easting=0.0,
false_northing=0.0,
)
return args
|
def omerc2cf(proj_dict):
"""Return the cf grid mapping for the omerc projection."""
grid_mapping_name = "oblique_mercator"
if "no_rot" in proj_dict:
no_rotation = " "
else:
no_rotation = None
args = dict(
azimuth_of_central_line=proj_dict.get("alpha"),
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lonc"),
# longitude_of_projection_origin=0.,
no_rotation=no_rotation,
# reference_ellipsoid_name=proj_dict.get('ellps'),
semi_major_axis=6378137.0,
semi_minor_axis=6356752.3142,
false_easting=0.0,
false_northing=0.0,
crtype="grid_mapping",
coords=["projection_x_coordinate", "projection_y_coordinate"],
)
return cf.CoordinateReference(grid_mapping_name, **args)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def geos2cf(proj_dict):
"""Return the cf grid mapping for the geos projection."""
args = dict(
perspective_point_height=proj_dict.get("h"),
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lon_0"),
grid_mapping_name="geostationary",
semi_major_axis=proj_dict.get("a"),
semi_minor_axis=proj_dict.get("b"),
sweep_axis=proj_dict.get("sweep"),
)
return args
|
def geos2cf(proj_dict):
"""Return the cf grid mapping for the geos projection."""
grid_mapping_name = "geostationary"
args = dict(
perspective_point_height=proj_dict.get("h"),
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lon_0"),
semi_major_axis=proj_dict.get("a"),
semi_minor_axis=proj_dict.get("b"),
sweep_axis=proj_dict.get("sweep"),
crtype="grid_mapping",
coords=["projection_x_coordinate", "projection_y_coordinate"],
)
return cf.CoordinateReference(grid_mapping_name, **args)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def laea2cf(proj_dict):
"""Return the cf grid mapping for the laea projection."""
args = dict(
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lon_0"),
grid_mapping_name="lambert_azimuthal_equal_area",
)
return args
|
def laea2cf(proj_dict):
"""Return the cf grid mapping for the laea projection."""
grid_mapping_name = "lambert_azimuthal_equal_area"
args = dict(
latitude_of_projection_origin=proj_dict.get("lat_0"),
longitude_of_projection_origin=proj_dict.get("lon_0"),
crtype="grid_mapping",
coords=["projection_x_coordinate", "projection_y_coordinate"],
)
return cf.CoordinateReference(grid_mapping_name, **args)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def create_grid_mapping(area):
"""Create the grid mapping instance for `area`."""
try:
grid_mapping = mappings[area.proj_dict["proj"]](area.proj_dict)
grid_mapping["name"] = area.proj_dict["proj"]
except KeyError:
raise NotImplementedError
return grid_mapping
|
def create_grid_mapping(area):
"""Create the grid mapping instance for `area`."""
try:
grid_mapping = mappings[area.proj_dict["proj"]](area.proj_dict)
except KeyError:
raise NotImplementedError
return grid_mapping
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def save_datasets(self, datasets, filename, **kwargs):
"""Save all datasets to one or more files."""
LOG.info("Saving datasets to NetCDF4/CF.")
ds_collection = {}
for ds in datasets:
ds_collection.update(get_extra_ds(ds))
datas = {}
for ds in ds_collection.values():
try:
new_datasets = area2cf(ds)
except KeyError:
new_datasets = [ds]
for new_ds in new_datasets:
datas[new_ds.attrs["name"]] = self.da2cf(new_ds, kwargs.get("epoch", EPOCH))
dataset = xr.Dataset(datas)
dataset.attrs["history"] = "Created by pytroll/satpy on " + str(datetime.utcnow())
dataset.attrs["conventions"] = "CF-1.7"
dataset.to_netcdf(filename, engine="h5netcdf")
|
def save_datasets(self, datasets, filename, **kwargs):
"""Save all datasets to one or more files."""
LOG.info("Saving datasets to NetCDF4/CF.")
fields = []
shapes = {}
for dataset in datasets:
if dataset.shape in shapes:
domain = shapes[dataset.shape]
else:
lines, pixels = dataset.shape
area = dataset.info.get("area")
add_time = False
try:
# Create a longitude auxiliary coordinate
lat = cf.AuxiliaryCoordinate(data=cf.Data(area.lats, "degrees_north"))
lat.standard_name = "latitude"
# Create a latitude auxiliary coordinate
lon = cf.AuxiliaryCoordinate(data=cf.Data(area.lons, "degrees_east"))
lon.standard_name = "longitude"
aux = [lat, lon]
add_time = True
except AttributeError:
LOG.info("No longitude and latitude data to save.")
aux = None
try:
grid_mapping = create_grid_mapping(area)
units = area.proj_dict.get("units", "m")
line_coord = cf.DimensionCoordinate(
data=cf.Data(area.proj_y_coords, units)
)
line_coord.standard_name = "projection_y_coordinate"
pixel_coord = cf.DimensionCoordinate(
data=cf.Data(area.proj_x_coords, units)
)
pixel_coord.standard_name = "projection_x_coordinate"
add_time = True
except (AttributeError, NotImplementedError):
LOG.info("No grid mapping to save.")
grid_mapping = None
line_coord = cf.DimensionCoordinate(data=cf.Data(np.arange(lines), "1"))
line_coord.standard_name = "line"
pixel_coord = cf.DimensionCoordinate(
data=cf.Data(np.arange(pixels), "1")
)
pixel_coord.standard_name = "pixel"
start_time = cf.dt(dataset.info["start_time"])
end_time = cf.dt(dataset.info["end_time"])
middle_time = cf.dt(
(dataset.info["end_time"] - dataset.info["start_time"]) / 2
+ dataset.info["start_time"]
)
# import ipdb
# ipdb.set_trace()
if add_time:
info = dataset.info
dataset = dataset[np.newaxis, :, :]
dataset.info = info
bounds = cf.CoordinateBounds(
data=cf.Data(
[start_time, end_time], cf.Units("days since 1970-1-1")
)
)
time_coord = cf.DimensionCoordinate(
properties=dict(standard_name="time"),
data=cf.Data(middle_time, cf.Units("days since 1970-1-1")),
bounds=bounds,
)
coords = [time_coord, line_coord, pixel_coord]
else:
coords = [line_coord, pixel_coord]
domain = cf.Domain(dim=coords, aux=aux, ref=grid_mapping)
shapes[dataset.shape] = domain
data = cf.Data(dataset, dataset.info.get("units", "m"))
# import ipdb
# ipdb.set_trace()
wanted_keys = ["standard_name", "long_name"]
properties = {
k: dataset.info[k] for k in set(wanted_keys) & set(dataset.info.keys())
}
new_field = cf.Field(properties=properties, data=data, domain=domain)
new_field._FillValue = dataset.fill_value
try:
new_field.valid_range = dataset.info["valid_range"]
except KeyError:
new_field.valid_range = new_field.min(), new_field.max()
new_field.Conventions = "CF-1.7"
fields.append(new_field)
fields[0].history = "Created by pytroll/satpy on " + str(datetime.utcnow())
flist = cf.FieldList(fields)
cf.write(flist, filename, fmt="NETCDF4", compress=6)
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def save_datasets(
self,
datasets,
sector_id=None,
source_name=None,
filename=None,
tile_count=(1, 1),
tile_size=None,
lettered_grid=False,
num_subtiles=None,
**kwargs,
):
if sector_id is None:
raise TypeError("Keyword 'sector_id' is required")
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for x in datasets:
area_id = _area_id(x.attrs["area"])
area, ds_list = area_datasets.setdefault(area_id, (x.attrs["area"], []))
ds_list.append(x)
output_filenames = []
dtype = AWIPS_DATA_DTYPE
fill_value = np.nan
for area_id, (area_def, ds_list) in area_datasets.items():
tile_gen = self._get_tile_generator(
area_def, lettered_grid, sector_id, num_subtiles, tile_size, tile_count
)
for dataset in ds_list:
pkwargs = {}
ds_info = dataset.attrs.copy()
LOG.info("Writing product %s to AWIPS SCMI NetCDF file", ds_info["name"])
if isinstance(dataset, np.ma.MaskedArray):
data = dataset
else:
mask = dataset.isnull()
data = np.ma.masked_array(dataset.values, mask=mask, copy=False)
pkwargs["awips_info"] = self._get_awips_info(
ds_info, source_name=source_name
)
pkwargs["attr_helper"] = AttributeHelper(ds_info)
LOG.debug("Scaling %s data to fit in netcdf file...", ds_info["name"])
bit_depth = ds_info.setdefault("bit_depth", 16)
valid_min = ds_info.get("valid_min")
if valid_min is None:
valid_min = np.nanmin(data)
valid_max = ds_info.get("valid_max")
if valid_max is None:
valid_max = np.nanmax(data)
pkwargs["valid_min"] = valid_min
pkwargs["valid_max"] = valid_max
pkwargs["bit_depth"] = bit_depth
LOG.debug(
"Using product valid min {} and valid max {}".format(
valid_min, valid_max
)
)
fills, factor, offset = self._calc_factor_offset(
data=data,
bitdepth=bit_depth,
min=valid_min,
max=valid_max,
dtype=dtype,
flag_meanings="flag_meanings" in ds_info,
)
pkwargs["fills"] = fills
pkwargs["factor"] = factor
pkwargs["offset"] = offset
if "flag_meanings" in ds_info:
pkwargs["data"] = data.astype(dtype)
else:
pkwargs["data"] = data
for (trow, tcol, tile_id, tmp_x, tmp_y), tmp_tile in tile_gen(
data, fill_value=fill_value
):
try:
fn = self.create_tile_output(
dataset,
sector_id,
trow,
tcol,
tile_id,
tmp_x,
tmp_y,
tmp_tile,
tile_gen.tile_count,
tile_gen.image_shape,
tile_gen.mx,
tile_gen.bx,
tile_gen.my,
tile_gen.by,
filename,
**pkwargs,
)
if fn is None:
if lettered_grid:
LOG.warning("Data did not fit in to any lettered tile")
raise RuntimeError("No SCMI tiles were created")
output_filenames.append(fn)
except (RuntimeError, KeyError, AttributeError):
LOG.error("Could not create output for '%s'", ds_info["name"])
LOG.debug("Writer exception: ", exc_info=True)
raise
return output_filenames[-1] if output_filenames else None
|
def save_datasets(
self,
datasets,
sector_id=None,
source_name=None,
filename=None,
tile_count=(1, 1),
tile_size=None,
lettered_grid=False,
num_subtiles=None,
**kwargs,
):
if sector_id is None:
raise TypeError("Keyword 'sector_id' is required")
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for x in datasets:
area_id = _area_id(x.info["area"])
area, ds_list = area_datasets.setdefault(area_id, (x.info["area"], []))
ds_list.append(x)
output_filenames = []
dtype = AWIPS_DATA_DTYPE
fill_value = np.nan
for area_id, (area_def, ds_list) in area_datasets.items():
tile_gen = self._get_tile_generator(
area_def, lettered_grid, sector_id, num_subtiles, tile_size, tile_count
)
for dataset in ds_list:
pkwargs = {}
ds_info = dataset.info.copy()
LOG.info("Writing product %s to AWIPS SCMI NetCDF file", ds_info["name"])
if isinstance(dataset, np.ma.MaskedArray):
data = dataset
else:
data = np.ma.masked_array(data, mask=np.isnan(data), copy=False)
pkwargs["awips_info"] = self._get_awips_info(
ds_info, source_name=source_name
)
pkwargs["attr_helper"] = AttributeHelper(ds_info)
LOG.debug("Scaling %s data to fit in netcdf file...", ds_info["name"])
bit_depth = ds_info.setdefault("bit_depth", 16)
valid_min = ds_info.get("valid_min")
if valid_min is None:
valid_min = np.nanmin(data)
valid_max = ds_info.get("valid_max")
if valid_max is None:
valid_max = np.nanmax(data)
pkwargs["valid_min"] = valid_min
pkwargs["valid_max"] = valid_max
pkwargs["bit_depth"] = bit_depth
LOG.debug(
"Using product valid min {} and valid max {}".format(
valid_min, valid_max
)
)
fills, factor, offset = self._calc_factor_offset(
data=data,
bitdepth=bit_depth,
min=valid_min,
max=valid_max,
dtype=dtype,
flag_meanings="flag_meanings" in ds_info,
)
pkwargs["fills"] = fills
pkwargs["factor"] = factor
pkwargs["offset"] = offset
if "flag_meanings" in ds_info:
pkwargs["data"] = data.astype(dtype)
else:
pkwargs["data"] = data
for (trow, tcol, tile_id, tmp_x, tmp_y), tmp_tile in tile_gen(
data, fill_value=fill_value
):
try:
fn = self.create_tile_output(
dataset,
sector_id,
trow,
tcol,
tile_id,
tmp_x,
tmp_y,
tmp_tile,
tile_gen.tile_count,
tile_gen.image_shape,
tile_gen.mx,
tile_gen.bx,
tile_gen.my,
tile_gen.by,
filename,
**pkwargs,
)
if fn is None:
if lettered_grid:
LOG.warning("Data did not fit in to any lettered tile")
raise RuntimeError("No SCMI tiles were created")
output_filenames.append(fn)
except (RuntimeError, KeyError, AttributeError):
LOG.error("Could not create output for '%s'", ds_info["name"])
LOG.debug("Writer exception: ", exc_info=True)
raise
return output_filenames[-1] if output_filenames else None
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def create_tile_output(
self,
dataset,
sector_id,
trow,
tcol,
tile_id,
tmp_x,
tmp_y,
tmp_tile,
tile_count,
image_shape,
mx,
bx,
my,
by,
filename,
awips_info,
attr_helper,
fills,
factor,
offset,
valid_min,
valid_max,
bit_depth,
**kwargs,
):
# Create the netcdf file
ds_info = dataset.attrs
area_def = ds_info["area"]
created_files = []
try:
if filename is None:
# format the filename
of_kwargs = ds_info.copy()
of_kwargs["start_time"] += timedelta(
minutes=int(os.environ.get("DEBUG_TIME_SHIFT", 0))
)
output_filename = self.get_filename(
area_id=area_def.area_id,
rows=area_def.y_size,
columns=area_def.x_size,
source_name=awips_info["source_name"],
sector_id=sector_id,
tile_id=tile_id,
**of_kwargs,
)
else:
output_filename = filename
if os.path.isfile(output_filename):
if not self.overwrite_existing:
LOG.error("AWIPS file already exists: %s", output_filename)
raise RuntimeError("AWIPS file already exists: %s" % (output_filename,))
else:
LOG.warning(
"AWIPS file already exists, will overwrite: %s", output_filename
)
created_files.append(output_filename)
LOG.info("Writing tile '%s' to '%s'", tile_id, output_filename)
nc = NetCDFWriter(output_filename, helper=attr_helper, compress=self.compress)
LOG.debug("Creating dimensions...")
nc.create_dimensions(tmp_tile.shape[0], tmp_tile.shape[1])
LOG.debug("Creating variables...")
nc.create_variables(bit_depth, fills[0], factor, offset)
LOG.debug("Creating global attributes...")
nc.set_global_attrs(
awips_info["physical_element"],
awips_info["awips_id"],
sector_id,
awips_info["creating_entity"],
tile_count,
image_shape,
trow,
tcol,
tmp_tile.shape[0],
tmp_tile.shape[1],
)
LOG.debug("Creating projection attributes...")
nc.set_projection_attrs(area_def.area_id, area_def.proj_dict)
LOG.debug("Writing image data...")
np.clip(tmp_tile, valid_min, valid_max, out=tmp_tile)
nc.set_image_data(tmp_tile, fills[0])
LOG.debug("Writing X/Y navigation data...")
nc.set_fgf(tmp_x, mx, bx, tmp_y, my, by, units="meters")
nc.close()
if self.fix_awips:
self._fix_awips_file(output_filename)
except (KeyError, AttributeError, RuntimeError):
last_fn = created_files[-1] if created_files else "N/A"
LOG.error("Error while filling in NC file with data: %s", last_fn)
for fn in created_files:
if not self.keep_intermediate and os.path.isfile(fn):
os.remove(fn)
raise
return created_files[-1] if created_files else None
|
def create_tile_output(
self,
dataset,
sector_id,
trow,
tcol,
tile_id,
tmp_x,
tmp_y,
tmp_tile,
tile_count,
image_shape,
mx,
bx,
my,
by,
filename,
awips_info,
attr_helper,
fills,
factor,
offset,
valid_min,
valid_max,
bit_depth,
**kwargs,
):
# Create the netcdf file
ds_info = dataset.info
area_def = ds_info["area"]
created_files = []
try:
if filename is None:
# format the filename
of_kwargs = ds_info.copy()
of_kwargs["start_time"] += timedelta(
minutes=int(os.environ.get("DEBUG_TIME_SHIFT", 0))
)
output_filename = self.get_filename(
area_id=area_def.area_id,
rows=area_def.y_size,
columns=area_def.x_size,
source_name=awips_info["source_name"],
sector_id=sector_id,
tile_id=tile_id,
**of_kwargs,
)
else:
output_filename = filename
if os.path.isfile(output_filename):
if not self.overwrite_existing:
LOG.error("AWIPS file already exists: %s", output_filename)
raise RuntimeError("AWIPS file already exists: %s" % (output_filename,))
else:
LOG.warning(
"AWIPS file already exists, will overwrite: %s", output_filename
)
created_files.append(output_filename)
LOG.info("Writing tile '%s' to '%s'", tile_id, output_filename)
nc = NetCDFWriter(output_filename, helper=attr_helper, compress=self.compress)
LOG.debug("Creating dimensions...")
nc.create_dimensions(tmp_tile.shape[0], tmp_tile.shape[1])
LOG.debug("Creating variables...")
nc.create_variables(bit_depth, fills[0], factor, offset)
LOG.debug("Creating global attributes...")
nc.set_global_attrs(
awips_info["physical_element"],
awips_info["awips_id"],
sector_id,
awips_info["creating_entity"],
tile_count,
image_shape,
trow,
tcol,
tmp_tile.shape[0],
tmp_tile.shape[1],
)
LOG.debug("Creating projection attributes...")
nc.set_projection_attrs(area_def.area_id, area_def.proj_dict)
LOG.debug("Writing image data...")
np.clip(tmp_tile, valid_min, valid_max, out=tmp_tile)
nc.set_image_data(tmp_tile, fills[0])
LOG.debug("Writing X/Y navigation data...")
nc.set_fgf(tmp_x, mx, bx, tmp_y, my, by, units="meters")
nc.close()
if self.fix_awips:
self._fix_awips_file(output_filename)
except (KeyError, AttributeError, RuntimeError):
last_fn = created_files[-1] if created_files else "N/A"
LOG.error("Error while filling in NC file with data: %s", last_fn)
for fn in created_files:
if not self.keep_intermediate and os.path.isfile(fn):
os.remove(fn)
raise
return created_files[-1] if created_files else None
|
https://github.com/pytroll/satpy/issues/123
|
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')
/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632 datasets = self.datasets.values()
633 writer = self.get_writer(writer, **kwargs)
--> 634 writer.save_datasets(datasets, **kwargs)
635
636 def get_writer(self, writer="geotiff", **kwargs):
/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176 coords = [line_coord, pixel_coord]
177
--> 178 domain = cf.Domain(dim=coords,
179 aux=aux,
180 ref=grid_mapping)
AttributeError: 'module' object has no attribute 'Domain'
|
AttributeError
|
def _get_calibration_params(self):
"""Get the calibration parameters from the metadata."""
params = {}
idx_table = []
val_table = []
for elt in self.mda["image_data_function"].split(b"\r\n"):
try:
key, val = elt.split(b":=")
try:
idx_table.append(int(key))
val_table.append(float(val))
except ValueError:
params[key] = val
except ValueError:
pass
params["indices"] = np.array(idx_table)
params["values"] = np.array(val_table, dtype=np.float32)
return params
|
def _get_calibration_params(self):
"""Get the calibration parameters from the metadata."""
params = {}
idx_table = []
val_table = []
for elt in self.mda["image_data_function"].split("\r\n"):
try:
key, val = elt.split(":=")
try:
idx_table.append(int(key))
val_table.append(float(val))
except ValueError:
params[key] = val
except ValueError:
pass
params["indices"] = np.array(idx_table)
params["values"] = np.array(val_table, dtype=np.float32)
return params
|
https://github.com/pytroll/satpy/issues/165
|
Traceback (most recent call last):
File "test_hrit_goes.py", line 19, in <module>
scn.load([composite])
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 566, in load
self.read(**kwargs)
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 507, in read
return self.read_datasets(nodes, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 377, in read_datasets
new_datasets = reader_instance.load(ds_ids, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 850, in load
ds = self._load_dataset_with_area(dsid, coords)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 794, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 648, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 619, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 425, in get_dataset
self.calibrate(out, key.calibration)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 460, in calibrate
self._calibrate(data)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 473, in _calibrate
data.mask[:] = data.data == 0
File "/home/a001673/.local/lib/python2.7/site-packages/xarray/core/common.py", line 176, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataArray' object has no attribute 'mask'
|
AttributeError
|
def _calibrate(self, data):
"""Calibrate *data*."""
idx = self.mda["calibration_parameters"]["indices"]
val = self.mda["calibration_parameters"]["values"]
ddata = data.data.map_blocks(
lambda block: np.interp(block, idx, val), dtype=val.dtype
)
res = xr.DataArray(ddata, dims=data.dims, attrs=data.attrs, coords=data.coords)
res = res.clip(min=0)
units = {"percent": "%"}
unit = self.mda["calibration_parameters"][b"_UNIT"]
res.attrs["units"] = units.get(unit, unit)
return res
|
def _calibrate(self, data):
"""Calibrate *data*."""
idx = self.mda["calibration_parameters"]["indices"]
val = self.mda["calibration_parameters"]["values"]
ddata = data.data.map_blocks(
lambda block: np.interp(block, idx, val), dtype=val.dtype
)
res = xr.DataArray(ddata, dims=data.dims, attrs=data.attrs, coords=data.coords)
res = res.clip(min=0)
units = {"percent": "%"}
unit = self.mda["calibration_parameters"]["_UNIT"]
res.attrs["units"] = units.get(unit, unit)
return res
|
https://github.com/pytroll/satpy/issues/165
|
Traceback (most recent call last):
File "test_hrit_goes.py", line 19, in <module>
scn.load([composite])
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 566, in load
self.read(**kwargs)
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 507, in read
return self.read_datasets(nodes, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/scene.py", line 377, in read_datasets
new_datasets = reader_instance.load(ds_ids, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 850, in load
ds = self._load_dataset_with_area(dsid, coords)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 794, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 648, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 619, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 425, in get_dataset
self.calibrate(out, key.calibration)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 460, in calibrate
self._calibrate(data)
File "/home/a001673/usr/src/satpy/satpy/readers/hrit_goes.py", line 473, in _calibrate
data.mask[:] = data.data == 0
File "/home/a001673/.local/lib/python2.7/site-packages/xarray/core/common.py", line 176, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataArray' object has no attribute 'mask'
|
AttributeError
|
def copy(self, node_cache=None):
if node_cache and self.name in node_cache:
return node_cache[self.name]
s = Node(self.name, self.data)
for c in self.children:
c = c.copy(node_cache=node_cache)
s.add_child(c)
return s
|
def copy(self):
s = Node(self.name, self.data)
for c in self.children:
c = c.copy()
s.add_child(c)
return s
|
https://github.com/pytroll/satpy/issues/208
|
TypeError Traceback (most recent call last)
/home/a000680/laptop/Pytroll/demo/modis/satpy_issue_5march2018.py in <module>()
59
60 scn.load(['solar_azimuth_angle', 'solar_zenith_angle',
---> 61 'satellite_zenith_angle', 'satellite_azimuth_angle'], resolution=1000)
/home/a000680/usr/src/satpy/satpy/scene.pyc in load(self, wishlist, calibration, resolution, polarization, compute, unload, **kwargs)
639 raise KeyError("Unknown datasets: {}".format(unknown_str))
640
--> 641 self.read(**kwargs)
642 keepables = None
643 if compute:
/home/a000680/usr/src/satpy/satpy/scene.pyc in read(self, nodes, **kwargs)
580 required_nodes = self.wishlist - set(self.datasets.keys())
581 nodes = self.dep_tree.leaves(nodes=required_nodes)
--> 582 return self.read_datasets(nodes, **kwargs)
583
584 def compute(self, nodes=None):
/home/a000680/usr/src/satpy/satpy/scene.pyc in read_datasets(self, dataset_nodes, **kwargs)
443 if ds_id in self.datasets and self.datasets[ds_id].is_loaded():
444 continue
--> 445 reader_name = node.data['reader_name']
446 reader_datasets.setdefault(reader_name, set()).add(ds_id)
447
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def copy(self):
"""Copy the this node tree
Note all references to readers are removed. This is meant to avoid
tree copies accessing readers that would return incompatible (Area)
data. Theoretically it should be possible for tree copies to request
compositor or modifier information as long as they don't depend on
any datasets not already existing in the dependency tree.
"""
new_tree = DependencyTree({}, self.compositors, self.modifiers)
for c in self.children:
c = c.copy(node_cache=new_tree._all_nodes)
new_tree.add_child(new_tree, c)
return new_tree
|
def copy(self):
"""Copy the this node tree
Note all references to readers are removed. This is meant to avoid
tree copies accessing readers that would return incompatible (Area)
data. Theoretically it should be possible for tree copies to request
compositor or modifier information as long as they don't depend on
any datasets not already existing in the dependency tree.
"""
new_tree = DependencyTree({}, self.compositors, self.modifiers)
for c in self.children:
c = c.copy()
new_tree.add_child(new_tree, c)
new_tree._all_nodes = new_tree.flatten(d=self._all_nodes)
return new_tree
|
https://github.com/pytroll/satpy/issues/208
|
TypeError Traceback (most recent call last)
/home/a000680/laptop/Pytroll/demo/modis/satpy_issue_5march2018.py in <module>()
59
60 scn.load(['solar_azimuth_angle', 'solar_zenith_angle',
---> 61 'satellite_zenith_angle', 'satellite_azimuth_angle'], resolution=1000)
/home/a000680/usr/src/satpy/satpy/scene.pyc in load(self, wishlist, calibration, resolution, polarization, compute, unload, **kwargs)
639 raise KeyError("Unknown datasets: {}".format(unknown_str))
640
--> 641 self.read(**kwargs)
642 keepables = None
643 if compute:
/home/a000680/usr/src/satpy/satpy/scene.pyc in read(self, nodes, **kwargs)
580 required_nodes = self.wishlist - set(self.datasets.keys())
581 nodes = self.dep_tree.leaves(nodes=required_nodes)
--> 582 return self.read_datasets(nodes, **kwargs)
583
584 def compute(self, nodes=None):
/home/a000680/usr/src/satpy/satpy/scene.pyc in read_datasets(self, dataset_nodes, **kwargs)
443 if ds_id in self.datasets and self.datasets[ds_id].is_loaded():
444 continue
--> 445 reader_name = node.data['reader_name']
446 reader_datasets.setdefault(reader_name, set()).add(ds_id)
447
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def read(self, nodes=None, **kwargs):
"""Load datasets from the necessary reader.
Args:
nodes (iterable): DependencyTree Node objects
**kwargs: Keyword arguments to pass to the reader's `load` method.
Returns:
DatasetDict of loaded datasets
"""
if nodes is None:
required_nodes = self.wishlist - set(self.datasets.keys())
nodes = self.dep_tree.leaves(nodes=required_nodes)
return self._read_datasets(nodes, **kwargs)
|
def read(self, nodes=None, **kwargs):
"""Load datasets from the necessary reader.
Args:
nodes (iterable): DependencyTree Node objects
**kwargs: Keyword arguments to pass to the reader's `load` method.
Returns:
DatasetDict of loaded datasets
"""
if nodes is None:
required_nodes = self.wishlist - set(self.datasets.keys())
nodes = self.dep_tree.leaves(nodes=required_nodes)
return self.read_datasets(nodes, **kwargs)
|
https://github.com/pytroll/satpy/issues/208
|
TypeError Traceback (most recent call last)
/home/a000680/laptop/Pytroll/demo/modis/satpy_issue_5march2018.py in <module>()
59
60 scn.load(['solar_azimuth_angle', 'solar_zenith_angle',
---> 61 'satellite_zenith_angle', 'satellite_azimuth_angle'], resolution=1000)
/home/a000680/usr/src/satpy/satpy/scene.pyc in load(self, wishlist, calibration, resolution, polarization, compute, unload, **kwargs)
639 raise KeyError("Unknown datasets: {}".format(unknown_str))
640
--> 641 self.read(**kwargs)
642 keepables = None
643 if compute:
/home/a000680/usr/src/satpy/satpy/scene.pyc in read(self, nodes, **kwargs)
580 required_nodes = self.wishlist - set(self.datasets.keys())
581 nodes = self.dep_tree.leaves(nodes=required_nodes)
--> 582 return self.read_datasets(nodes, **kwargs)
583
584 def compute(self, nodes=None):
/home/a000680/usr/src/satpy/satpy/scene.pyc in read_datasets(self, dataset_nodes, **kwargs)
443 if ds_id in self.datasets and self.datasets[ds_id].is_loaded():
444 continue
--> 445 reader_name = node.data['reader_name']
446 reader_datasets.setdefault(reader_name, set()).add(ds_id)
447
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def compute(self, nodes=None):
"""Compute all the composites contained in `requirements`."""
if nodes is None:
required_nodes = self.wishlist - set(self.datasets.keys())
nodes = set(self.dep_tree.trunk(nodes=required_nodes)) - set(
self.datasets.keys()
)
return self._read_composites(nodes)
|
def compute(self, nodes=None):
"""Compute all the composites contained in `requirements`."""
if nodes is None:
required_nodes = self.wishlist - set(self.datasets.keys())
nodes = set(self.dep_tree.trunk(nodes=required_nodes)) - set(
self.datasets.keys()
)
return self.read_composites(nodes)
|
https://github.com/pytroll/satpy/issues/208
|
TypeError Traceback (most recent call last)
/home/a000680/laptop/Pytroll/demo/modis/satpy_issue_5march2018.py in <module>()
59
60 scn.load(['solar_azimuth_angle', 'solar_zenith_angle',
---> 61 'satellite_zenith_angle', 'satellite_azimuth_angle'], resolution=1000)
/home/a000680/usr/src/satpy/satpy/scene.pyc in load(self, wishlist, calibration, resolution, polarization, compute, unload, **kwargs)
639 raise KeyError("Unknown datasets: {}".format(unknown_str))
640
--> 641 self.read(**kwargs)
642 keepables = None
643 if compute:
/home/a000680/usr/src/satpy/satpy/scene.pyc in read(self, nodes, **kwargs)
580 required_nodes = self.wishlist - set(self.datasets.keys())
581 nodes = self.dep_tree.leaves(nodes=required_nodes)
--> 582 return self.read_datasets(nodes, **kwargs)
583
584 def compute(self, nodes=None):
/home/a000680/usr/src/satpy/satpy/scene.pyc in read_datasets(self, dataset_nodes, **kwargs)
443 if ds_id in self.datasets and self.datasets[ds_id].is_loaded():
444 continue
--> 445 reader_name = node.data['reader_name']
446 reader_datasets.setdefault(reader_name, set()).add(ds_id)
447
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def resample(
self, destination=None, datasets=None, compute=True, unload=True, **resample_kwargs
):
"""Resample the datasets and return a new scene."""
to_resample = [
dataset
for (dsid, dataset) in self.datasets.items()
if (not datasets) or dsid in datasets
]
if destination is None:
destination = self.max_area(to_resample)
new_scn = self._resampled_scene(to_resample, destination, **resample_kwargs)
new_scn.attrs = self.attrs.copy()
new_scn.dep_tree = self.dep_tree.copy()
# MUST set this after assigning the resampled datasets otherwise
# composite prereqs that were resampled will be considered "wishlisted"
if datasets is None:
new_scn.wishlist = self.wishlist.copy()
else:
new_scn.wishlist = set([DatasetID.from_dict(ds.attrs) for ds in new_scn])
# recompute anything from the wishlist that needs it (combining
# multiple resolutions, etc.)
keepables = None
if compute:
nodes = [
self.dep_tree[i]
for i in new_scn.wishlist
if i in self.dep_tree and not self.dep_tree[i].is_leaf
]
keepables = new_scn.compute(nodes=nodes)
if new_scn.missing_datasets:
# copy the set of missing datasets because they won't be valid
# after they are removed in the next line
missing = new_scn.missing_datasets.copy()
new_scn._remove_failed_datasets(keepables)
missing_str = ", ".join(str(x) for x in missing)
LOG.warning("The following datasets were not created: {}".format(missing_str))
if unload:
new_scn.unload(keepables)
return new_scn
|
def resample(
self, destination=None, datasets=None, compute=True, unload=True, **resample_kwargs
):
"""Resample the datasets and return a new scene."""
to_resample = [
dataset
for (dsid, dataset) in self.datasets.items()
if (not datasets) or dsid in datasets
]
if destination is None:
destination = self.max_area(to_resample)
new_scn = self._resampled_scene(to_resample, destination, **resample_kwargs)
new_scn.attrs = self.attrs.copy()
new_scn.dep_tree = self.dep_tree.copy()
# MUST set this after assigning the resampled datasets otherwise
# composite prereqs that were resampled will be considered "wishlisted"
if datasets is None:
new_scn.wishlist = self.wishlist
else:
new_scn.wishlist = set([DatasetID.from_dict(ds.attrs) for ds in new_scn])
# recompute anything from the wishlist that needs it (combining
# multiple resolutions, etc.)
keepables = None
if compute:
nodes = [
self.dep_tree[i]
for i in new_scn.wishlist
if i in self.dep_tree and not self.dep_tree[i].is_leaf
]
keepables = new_scn.compute(nodes=nodes)
if new_scn.missing_datasets:
# copy the set of missing datasets because they won't be valid
# after they are removed in the next line
missing = new_scn.missing_datasets.copy()
new_scn._remove_failed_datasets(keepables)
missing_str = ", ".join(str(x) for x in missing)
LOG.warning("The following datasets were not created: {}".format(missing_str))
if unload:
new_scn.unload(keepables)
return new_scn
|
https://github.com/pytroll/satpy/issues/208
|
TypeError Traceback (most recent call last)
/home/a000680/laptop/Pytroll/demo/modis/satpy_issue_5march2018.py in <module>()
59
60 scn.load(['solar_azimuth_angle', 'solar_zenith_angle',
---> 61 'satellite_zenith_angle', 'satellite_azimuth_angle'], resolution=1000)
/home/a000680/usr/src/satpy/satpy/scene.pyc in load(self, wishlist, calibration, resolution, polarization, compute, unload, **kwargs)
639 raise KeyError("Unknown datasets: {}".format(unknown_str))
640
--> 641 self.read(**kwargs)
642 keepables = None
643 if compute:
/home/a000680/usr/src/satpy/satpy/scene.pyc in read(self, nodes, **kwargs)
580 required_nodes = self.wishlist - set(self.datasets.keys())
581 nodes = self.dep_tree.leaves(nodes=required_nodes)
--> 582 return self.read_datasets(nodes, **kwargs)
583
584 def compute(self, nodes=None):
/home/a000680/usr/src/satpy/satpy/scene.pyc in read_datasets(self, dataset_nodes, **kwargs)
443 if ds_id in self.datasets and self.datasets[ds_id].is_loaded():
444 continue
--> 445 reader_name = node.data['reader_name']
446 reader_datasets.setdefault(reader_name, set()).add(ds_id)
447
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def read_sigmf(data_file, meta_file=None, buffer=None, num_samples=None, offset=0):
"""
Read and unpack binary file, with SigMF spec, to GPU memory.
Parameters
----------
data_file : str
File contain sigmf data.
meta_file : str, optional
File contain sigmf meta.
buffer : ndarray, optional
Pinned memory buffer to use when copying data from GPU.
num_samples : int, optional
Number of samples to be loaded to GPU. If set to 0,
read in all samples.
offset : int, optional
May be specified as a non-negative integer offset.
It is the number of samples before loading 'num_samples'.
'offset' must be a multiple of ALLOCATIONGRANULARITY which
is equal to PAGESIZE on Unix systems.
Returns
-------
out : ndarray
An 1-dimensional array containing unpacked binary data.
"""
if meta_file is None:
meta_ext = ".sigmf-meta"
pat = re.compile(r"(.+)(\.)(.+)")
split_string = pat.split(data_file)
meta_file = split_string[1] + meta_ext
with open(meta_file, "r") as f:
header = json.loads(f.read())
dataset_type = _extract_values(header, "core:datatype")
data_type = dataset_type[0].split("_")
if len(data_type) == 1:
endianness = "N"
elif len(data_type) == 2:
if data_type[1] == "le":
endianness = "L"
elif data_type[1] == "be":
endianness = "B"
else:
raise NotImplementedError
else:
raise NotImplementedError
# Complex
if data_type[0][0] == "c":
if data_type[0][1:] == "f64":
data_type = cp.complex128
elif data_type[0][1:] == "f32":
data_type = cp.complex64
elif data_type[0][1:] == "i32":
data_type = cp.int32
elif data_type[0][1:] == "u32":
data_type = cp.uint32
elif data_type[0][1:] == "i16":
data_type = cp.int16
elif data_type[0][1:] == "u16":
data_type = cp.uint16
elif data_type[0][1:] == "i8":
data_type = cp.int8
elif data_type[0][1:] == "u8":
data_type = cp.uint8
else:
raise NotImplementedError
# Real
elif data_type[0][0] == "r":
if data_type[0][1:] == "f64":
data_type = cp.float64
elif data_type[0][1:] == "f32":
data_type = cp.float32
elif data_type[0][1:] == "i32":
data_type = cp.int32
elif data_type[0][1:] == "u32":
data_type = cp.uint32
elif data_type[0][1:] == "i16":
data_type = cp.int16
elif data_type[0][1:] == "u16":
data_type = cp.uint16
elif data_type[0][1:] == "i8":
data_type = cp.int8
elif data_type[0][1:] == "u8":
data_type = cp.uint8
else:
raise NotImplementedError
else:
raise NotImplementedError
binary = read_bin(data_file, buffer, data_type, num_samples, offset)
out = unpack_bin(binary, data_type, endianness)
return out
|
def read_sigmf(data_file, meta_file=None, buffer=None, num_samples=None, offset=0):
"""
Read and unpack binary file, with SigMF spec, to GPU memory.
Parameters
----------
data_file : str
File contain sigmf data.
meta_file : str, optional
File contain sigmf meta.
buffer : ndarray, optional
Pinned memory buffer to use when copying data from GPU.
num_samples : int, optional
Number of samples to be loaded to GPU. If set to 0,
read in all samples.
offset : int, optional
May be specified as a non-negative integer offset.
It is the number of samples before loading 'num_samples'.
'offset' must be a multiple of ALLOCATIONGRANULARITY which
is equal to PAGESIZE on Unix systems.
Returns
-------
out : ndarray
An 1-dimensional array containing unpacked binary data.
"""
if meta_file is None:
meta_ext = ".sigmf-meta"
split_string = data_file.split(".")
meta_file = split_string[0] + meta_ext
with open(meta_file, "r") as f:
header = json.loads(f.read())
dataset_type = _extract_values(header, "core:datatype")
data_type = dataset_type[0].split("_")
if len(data_type) == 1:
endianness = "N"
elif len(data_type) == 2:
if data_type[1] == "le":
endianness = "L"
elif data_type[1] == "be":
endianness = "B"
else:
raise NotImplementedError
else:
raise NotImplementedError
# Complex
if data_type[0][0] == "c":
if data_type[0][1:] == "f64":
data_type = cp.complex128
elif data_type[0][1:] == "f32":
data_type = cp.complex64
elif data_type[0][1:] == "i32":
data_type = cp.int32
elif data_type[0][1:] == "u32":
data_type = cp.uint32
elif data_type[0][1:] == "i16":
data_type = cp.int16
elif data_type[0][1:] == "u16":
data_type = cp.uint16
elif data_type[0][1:] == "i8":
data_type = cp.int8
elif data_type[0][1:] == "u8":
data_type = cp.uint8
else:
raise NotImplementedError
# Real
elif data_type[0][0] == "r":
if data_type[0][1:] == "f64":
data_type = cp.float64
elif data_type[0][1:] == "f32":
data_type = cp.float32
elif data_type[0][1:] == "i32":
data_type = cp.int32
elif data_type[0][1:] == "u32":
data_type = cp.uint32
elif data_type[0][1:] == "i16":
data_type = cp.int16
elif data_type[0][1:] == "u16":
data_type = cp.uint16
elif data_type[0][1:] == "i8":
data_type = cp.int8
elif data_type[0][1:] == "u8":
data_type = cp.uint8
else:
raise NotImplementedError
else:
raise NotImplementedError
binary = read_bin(data_file, buffer, data_type, num_samples, offset)
out = unpack_bin(binary, data_type, endianness)
return out
|
https://github.com/rapidsai/cusignal/issues/279
|
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-46-cda23b1650a7> in <module>
1 data = cusignal.read_sigmf(
----> 2 data_file='../data/Demod_WiFi_cable_X310_3123D76_IQ#1_run1.sigmf-data'
3 )
4 data
/opt/conda/envs/rapids/lib/python3.7/site-packages/cusignal/io/reader.py in read_sigmf(data_file, meta_file, buffer, num_samples, offset)
160 meta_file = split_string[0] + meta_ext
161
--> 162 with open(meta_file, "r") as f:
163 header = json.loads(f.read())
164
FileNotFoundError: [Errno 2] No such file or directory: '.sigmf-meta'
|
FileNotFoundError
|
def clean_percentage(self):
if not self.range:
raise exceptions.ValidationError(
_("Percentage benefits require a product range")
)
if not self.value:
raise exceptions.ValidationError(
_("Percentage discount benefits require a value")
)
if self.value > 100:
raise exceptions.ValidationError(
_("Percentage discount cannot be greater than 100")
)
|
def clean_percentage(self):
if not self.range:
raise exceptions.ValidationError(
_("Percentage benefits require a product range")
)
if self.value > 100:
raise exceptions.ValidationError(
_("Percentage discount cannot be greater than 100")
)
|
https://github.com/django-oscar/django-oscar/issues/2167
|
Traceback (most recent call last):
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 30, in inner
return func(*args, **kwds)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/a1/projects/djangooscar/src/oscar/apps/dashboard/offers/views.py", line 93, in dispatch
**kwargs)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/views/generic/edit.py", line 221, in post
if form.is_valid():
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/forms/forms.py", line 161, in is_valid
return self.is_bound and not self.errors
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/forms/forms.py", line 153, in errors
self.full_clean()
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/forms/forms.py", line 364, in full_clean
self._post_clean()
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/forms/models.py", line 396, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "/Users/a1/projects/djangooscar/env3/lib/python3.5/site-packages/django/db/models/base.py", line 1129, in full_clean
self.clean()
File "/Users/a1/projects/djangooscar/src/oscar/apps/offer/abstract_models.py", line 497, in clean
getattr(self, method_name)()
File "/Users/a1/projects/djangooscar/src/oscar/apps/offer/abstract_models.py", line 515, in clean_percentage
if self.value > 100:
TypeError: unorderable types: NoneType() > int()
|
TypeError
|
def get(self, request, *args, **kwargs):
try:
self.search_handler = self.get_search_handler(
self.request.GET, request.get_full_path(), []
)
except InvalidPage:
# Redirect to page one.
messages.error(request, _("The given page number was invalid."))
return redirect("catalogue:index")
return super(CatalogueView, self).get(request, *args, **kwargs)
|
def get(self, request, *args, **kwargs):
self.search_handler = self.get_search_handler(
self.request.GET, request.get_full_path(), []
)
return super(CatalogueView, self).get(request, *args, **kwargs)
|
https://github.com/django-oscar/django-oscar/issues/1490
|
Traceback (most recent call last):
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/views.py", line 123, in get
self.request.GET, request.get_full_path(), [])
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/views.py", line 127, in get_search_handler
return get_product_search_handler_class()(*args, **kwargs)
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/search_handlers.py", line 38, in __init__
super(ProductSearchHandler, self).__init__(request_data, full_path)
File "/var/www/oscar/builds/latest/oscar/apps/search/search_handlers.py", line 54, in __init__
self.results, request_data)
File "/var/www/oscar/builds/latest/oscar/apps/search/search_handlers.py", line 119, in paginate_queryset
'message': str(e)
ValueError: Invalid page (2): That page contains no results
<WSGIRequest
path:/en-gb/catalogue/,
GET:<QueryDict: {u'selected_facets': [u'price_exact:[60 TO *]'], u'page': [u'2']}>,
POST:<QueryDict: {}>,
COOKIES:{},
META:{'CONTENT_LENGTH': '',
'CONTENT_TYPE': '',
u'CSRF_COOKIE': u'LhkCNs5r9tuy3OMshbqaiyzbQXg31CHf',
'DOCUMENT_ROOT': '/etc/nginx/html',
'HTTP_ACCEPT': '*/*',
'HTTP_ACCEPT_ENCODING': 'gzip, x-gzip',
'HTTP_CONNECTION': 'close',
'HTTP_HOST': 'latest.oscarcommerce.com',
'HTTP_USER_AGENT': 'Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)',
'HTTP_X_FORWARDED_FOR': '68.180.225.33',
'HTTP_X_REAL_IP': '68.180.225.33',
'PATH_INFO': u'/en-gb/catalogue/',
'QUERY_STRING': 'selected_facets=price_exact%3A%5B60+TO+%2A%5D&page=2',
'REMOTE_ADDR': '68.180.225.33',
'REMOTE_PORT': '',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/en-gb/catalogue/?selected_facets=price_exact%3A%5B60+TO+%2A%5D&page=2',
u'SCRIPT_NAME': u'',
'SERVER_NAME': 'sandbox.oscar.tangentlabs.co.uk',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.0',
'uwsgi.node': 'tangent-oscar-demo.tangentlabs.co.uk',
'uwsgi.version': '1.9.21.1',
'wsgi.errors': <open file 'wsgi_errors', mode 'w' at 0x14436f0>,
'wsgi.file_wrapper': <built-in function uwsgi_sendfile>,
'wsgi.input': <uwsgi._Input object at 0x36e8fd8>,
|
ValueError
|
def get(self, request, *args, **kwargs):
# Fetch the category; return 404 or redirect as needed
self.category = self.get_category()
potential_redirect = self.redirect_if_necessary(request.path, self.category)
if potential_redirect is not None:
return potential_redirect
try:
self.search_handler = self.get_search_handler(
request.GET, request.get_full_path(), self.get_categories()
)
except InvalidPage:
messages.error(request, _("The given page number was invalid."))
return redirect(self.category.get_absolute_url())
return super(ProductCategoryView, self).get(request, *args, **kwargs)
|
def get(self, request, *args, **kwargs):
# Fetch the category; return 404 or redirect as needed
self.category = self.get_category()
redirect = self.redirect_if_necessary(request.path, self.category)
if redirect is not None:
return redirect
self.search_handler = self.get_search_handler(
request.GET, request.get_full_path(), self.get_categories()
)
return super(ProductCategoryView, self).get(request, *args, **kwargs)
|
https://github.com/django-oscar/django-oscar/issues/1490
|
Traceback (most recent call last):
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/var/www/oscar/virtualenvs/latest/local/lib/python2.7/site-packages/Django-1.6.6-py2.7.egg/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/views.py", line 123, in get
self.request.GET, request.get_full_path(), [])
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/views.py", line 127, in get_search_handler
return get_product_search_handler_class()(*args, **kwargs)
File "/var/www/oscar/builds/latest/oscar/apps/catalogue/search_handlers.py", line 38, in __init__
super(ProductSearchHandler, self).__init__(request_data, full_path)
File "/var/www/oscar/builds/latest/oscar/apps/search/search_handlers.py", line 54, in __init__
self.results, request_data)
File "/var/www/oscar/builds/latest/oscar/apps/search/search_handlers.py", line 119, in paginate_queryset
'message': str(e)
ValueError: Invalid page (2): That page contains no results
<WSGIRequest
path:/en-gb/catalogue/,
GET:<QueryDict: {u'selected_facets': [u'price_exact:[60 TO *]'], u'page': [u'2']}>,
POST:<QueryDict: {}>,
COOKIES:{},
META:{'CONTENT_LENGTH': '',
'CONTENT_TYPE': '',
u'CSRF_COOKIE': u'LhkCNs5r9tuy3OMshbqaiyzbQXg31CHf',
'DOCUMENT_ROOT': '/etc/nginx/html',
'HTTP_ACCEPT': '*/*',
'HTTP_ACCEPT_ENCODING': 'gzip, x-gzip',
'HTTP_CONNECTION': 'close',
'HTTP_HOST': 'latest.oscarcommerce.com',
'HTTP_USER_AGENT': 'Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)',
'HTTP_X_FORWARDED_FOR': '68.180.225.33',
'HTTP_X_REAL_IP': '68.180.225.33',
'PATH_INFO': u'/en-gb/catalogue/',
'QUERY_STRING': 'selected_facets=price_exact%3A%5B60+TO+%2A%5D&page=2',
'REMOTE_ADDR': '68.180.225.33',
'REMOTE_PORT': '',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/en-gb/catalogue/?selected_facets=price_exact%3A%5B60+TO+%2A%5D&page=2',
u'SCRIPT_NAME': u'',
'SERVER_NAME': 'sandbox.oscar.tangentlabs.co.uk',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.0',
'uwsgi.node': 'tangent-oscar-demo.tangentlabs.co.uk',
'uwsgi.version': '1.9.21.1',
'wsgi.errors': <open file 'wsgi_errors', mode 'w' at 0x14436f0>,
'wsgi.file_wrapper': <built-in function uwsgi_sendfile>,
'wsgi.input': <uwsgi._Input object at 0x36e8fd8>,
|
ValueError
|
def lookup(self, slug, table="monster"):
"""Looks up a monster, technique, item, or npc based on name or id.
:param slug: The slug of the monster, technique, item, or npc. A short English identifier.
:param table: Which index to do the search in. Can be: "monster",
"item", "npc", or "technique".
:type slug: String
:type table: String
:rtype: Dict
:returns: A dictionary from the resulting lookup.
"""
if slug in self.database[table]:
return self.database[table][slug]
for id, item in self.database[table].items():
# TODO: localize *everything*
# the slug lookup will fail for monsters and npc's
# eventually, we may want to localize monster names or npc
# in that case, all DB objects will have a slug
# for now, we silently fail and lookup by name instead
try:
if item["slug"] == slug:
return item
except KeyError:
if item["name"] == slug:
return item
|
def lookup(self, name, table="monster"):
"""Looks up a monster, technique, item, or npc based on name or id.
:param name: The name of the monster, technique, item, or npc.
:param table: Which index to do the search in. Can be: "monster",
"item", "npc", or "technique".
:type name: String
:type table: String
:rtype: Dict
:returns: A dictionary from the resulting lookup.
"""
if name in self.database[table]:
return self.database[table][name]
for id, item in self.database[table].items():
if item["name"] == name:
return item
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def start_battle(self, game, action):
"""Start a battle and switch to the combat module. The parameters must contain an NPC id
in the NPC database.
:param game: The main game object that contains all the game's variables.
:param action: The action (tuple) retrieved from the database that contains the action's
parameters
:type game: core.control.Control
:type action: Tuple
:rtype: None
:returns: None
Valid Parameters: npc_id
**Examples:**
>>> action.__dict__
{
"type": "start_battle",
"parameters": [
"1"
]
}
"""
# Don't start a battle if we don't even have monsters in our party yet.
if not self.check_battle_legal(game.player1):
return False
# Stop movement and keypress on the server.
if game.isclient or game.ishost:
game.client.update_player(game.player1.facing, event_type="CLIENT_START_BATTLE")
# Start combat
npc_id = int(action.parameters[0])
# Create an NPC object that will be used as our opponent
npc = player.Npc()
# Look up the NPC's details from our NPC database
npcs = db.JSONDatabase()
npcs.load("npc")
npc_details = npcs.database["npc"][npc_id]
# Set the NPC object with the details fetched from the database.
npc.name = npc_details["name"]
# Set the NPC object's AI model.
npc.ai = ai.AI()
# Look up the NPC's monster party
npc_party = npc_details["monsters"]
# Look up the monster's details
monsters = db.JSONDatabase()
monsters.load("monster")
# Look up each monster in the NPC's party
for npc_monster_details in npc_party:
results = monsters.database["monster"][npc_monster_details["monster_id"]]
# Create a monster object for each monster the NPC has in their party.
current_monster = monster.Monster()
current_monster.load_from_db(npc_monster_details["monster_id"])
current_monster.name = npc_monster_details["name"]
current_monster.monster_id = npc_monster_details["monster_id"]
current_monster.level = npc_monster_details["level"]
current_monster.hp = npc_monster_details["hp"]
current_monster.current_hp = npc_monster_details["hp"]
current_monster.attack = npc_monster_details["attack"]
current_monster.defense = npc_monster_details["defense"]
current_monster.speed = npc_monster_details["speed"]
current_monster.special_attack = npc_monster_details["special_attack"]
current_monster.special_defense = npc_monster_details["special_defense"]
current_monster.experience_give_modifier = npc_monster_details["exp_give_mod"]
current_monster.experience_required_modifier = npc_monster_details[
"exp_req_mod"
]
current_monster.type1 = results["types"][0]
current_monster.set_level(current_monster.level)
if len(results["types"]) > 1:
current_monster.type2 = results["types"][1]
current_monster.load_sprite_from_db()
pound = technique.Technique("technique_pound")
current_monster.learn(pound)
# Add our monster to the NPC's party
npc.monsters.append(current_monster)
# Add our players and setup combat
game.push_state("CombatState", players=(game.player1, npc), combat_type="trainer")
# Flash the screen before combat
# game.push_state("FlashTransition")
# Start some music!
logger.info("Playing battle music!")
filename = "147066_pokemon.ogg"
mixer.music.load(prepare.BASEDIR + "resources/music/" + filename)
mixer.music.play(-1)
|
def start_battle(self, game, action):
"""Start a battle and switch to the combat module. The parameters must contain an NPC id
in the NPC database.
:param game: The main game object that contains all the game's variables.
:param action: The action (tuple) retrieved from the database that contains the action's
parameters
:type game: core.control.Control
:type action: Tuple
:rtype: None
:returns: None
Valid Parameters: npc_id
**Examples:**
>>> action.__dict__
{
"type": "start_battle",
"parameters": [
"1"
]
}
"""
# Don't start a battle if we don't even have monsters in our party yet.
if not self.check_battle_legal(game.player1):
return False
# Stop movement and keypress on the server.
if game.isclient or game.ishost:
game.client.update_player(game.player1.facing, event_type="CLIENT_START_BATTLE")
# Start combat
npc_id = int(action.parameters[0])
# Create an NPC object that will be used as our opponent
npc = player.Npc()
# Look up the NPC's details from our NPC database
npcs = db.JSONDatabase()
npcs.load("npc")
npc_details = npcs.database["npc"][npc_id]
# Set the NPC object with the details fetched from the database.
npc.name = npc_details["name"]
# Set the NPC object's AI model.
npc.ai = ai.AI()
# Look up the NPC's monster party
npc_party = npc_details["monsters"]
# Look up the monster's details
monsters = db.JSONDatabase()
monsters.load("monster")
# Look up each monster in the NPC's party
for npc_monster_details in npc_party:
results = monsters.database["monster"][npc_monster_details["monster_id"]]
# Create a monster object for each monster the NPC has in their party.
current_monster = monster.Monster()
current_monster.load_from_db(npc_monster_details["monster_id"])
current_monster.name = npc_monster_details["name"]
current_monster.monster_id = npc_monster_details["monster_id"]
current_monster.level = npc_monster_details["level"]
current_monster.hp = npc_monster_details["hp"]
current_monster.current_hp = npc_monster_details["hp"]
current_monster.attack = npc_monster_details["attack"]
current_monster.defense = npc_monster_details["defense"]
current_monster.speed = npc_monster_details["speed"]
current_monster.special_attack = npc_monster_details["special_attack"]
current_monster.special_defense = npc_monster_details["special_defense"]
current_monster.experience_give_modifier = npc_monster_details["exp_give_mod"]
current_monster.experience_required_modifier = npc_monster_details[
"exp_req_mod"
]
current_monster.type1 = results["types"][0]
current_monster.set_level(current_monster.level)
if len(results["types"]) > 1:
current_monster.type2 = results["types"][1]
current_monster.load_sprite_from_db()
pound = technique.Technique("Pound")
current_monster.learn(pound)
# Add our monster to the NPC's party
npc.monsters.append(current_monster)
# Add our players and setup combat
game.push_state("CombatState", players=(game.player1, npc), combat_type="trainer")
# Flash the screen before combat
# game.push_state("FlashTransition")
# Start some music!
logger.info("Playing battle music!")
filename = "147066_pokemon.ogg"
mixer.music.load(prepare.BASEDIR + "resources/music/" + filename)
mixer.music.play(-1)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def __init__(self, slug=None, id=None):
self.id = 0
self.name = "Blank"
self.description = "None"
self.effect = []
self.type = None
self.power = 0
self.sprite = "" # The path to the sprite to load.
self.surface = None # The pygame.Surface object of the item.
self.surface_size_original = (
0,
0,
) # The original size of the image before scaling.
# If a slug of the item was provided, autoload it from the item database.
if slug or id:
self.load(slug, id)
|
def __init__(self, name=None, id=None):
self.id = 0
self.name = "Blank"
self.description = "None"
self.effect = []
self.type = None
self.power = 0
self.sprite = "" # The path to the sprite to load.
self.surface = None # The pygame.Surface object of the item.
self.surface_size_original = (
0,
0,
) # The original size of the image before scaling.
# If a name of the item was provided, autoload it from the item database.
if name or id:
self.load(name, id)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def load(self, slug, id):
"""Loads and sets this items's attributes from the item.db database. The item is looked up
in the database by name or id.
:param slug: The item slug to look up in the monster.item database.
:param id: The id of the item to look up in the item.db database.
:type slug: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>> potion_item = Item()
>>> potion_item.load("item_potion", None) # Load an item by name.
>>> potion_item.load(None, 1) # Load an item by id.
>>> pprint.pprint(potion_item.__dict__)
{'description': u'Heals a monster by 50 HP.',
'effect': [u'heal'],
'id': 1,
'name': u'Potion',
'power': 50,
'type': u'Consumable'}
"""
if slug:
results = items.lookup(slug, table="item")
elif id:
results = items.lookup_by_id(id, table="item")
else:
# TODO: some kind of useful message here
raise RuntimeError
self.slug = results["slug"] # short English identifier
self.name = trans(results["name_trans"]) # will be locale string
self.description = trans(results["description_trans"]) # will be locale string
self.id = results["id"]
self.type = results["type"]
self.power = results["power"]
self.sprite = results["sprite"]
self.usable_in = results["usable_in"]
self.surface = tools.load_and_scale(self.sprite)
self.surface_size_original = self.surface.get_size()
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
self.effect = results["effects"]
|
def load(self, name, id):
"""Loads and sets this items's attributes from the item.db database. The item is looked up
in the database by name or id.
:param name: The name of the item to look up in the monster.item database.
:param id: The id of the item to look up in the item.db database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>> potion_item = Item()
>>> potion_item.load("Potion", None) # Load an item by name.
>>> potion_item.load(None, 1) # Load an item by id.
>>> pprint.pprint(potion_item.__dict__)
{'description': u'Heals a monster by 50 HP.',
'effect': [u'heal'],
'id': 1,
'name': u'Potion',
'power': 50,
'type': u'Consumable'}
"""
if name:
results = items.lookup(name, table="item")
elif id:
results = items.lookup_by_id(id, table="item")
self.name = results["name"]
self.name_trans = trans(results["name_trans"])
self.description = results["description"]
self.description_trans = trans(results["description_trans"])
self.id = results["id"]
self.type = results["type"]
self.power = results["power"]
self.sprite = results["sprite"]
self.usable_in = results["usable_in"]
self.surface = tools.load_and_scale(self.sprite)
self.surface_size_original = self.surface.get_size()
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
self.effect = results["effects"]
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def heal(self, user, target):
"""This effect heals the target based on the item's power attribute.
:param user: The monster or object that is using this item.
:param target: The monster or object that we are using this item on.
:type user: Varies
:type target: Varies
:rtype: bool
:returns: Success
**Examples:**
>>> potion_item = Item("item_potion")
>>> potion_item.heal(bulbatux, game)
"""
if target.current_hp == target.hp:
return False
# Heal the target monster by "self.power" number of hitpoints.
target.current_hp += self.power
# If we've exceeded the monster's maximum HP, set their health to 100% of their HP.
if target.current_hp > target.hp:
target.current_hp = target.hp
return True
|
def heal(self, user, target):
"""This effect heals the target based on the item's power attribute.
:param user: The monster or object that is using this item.
:param target: The monster or object that we are using this item on.
:type user: Varies
:type target: Varies
:rtype: bool
:returns: Success
**Examples:**
>>> potion_item = Item("Potion")
>>> potion_item.heal(bulbatux, game)
"""
if target.current_hp == target.hp:
return False
# Heal the target monster by "self.power" number of hitpoints.
target.current_hp += self.power
# If we've exceeded the monster's maximum HP, set their health to 100% of their HP.
if target.current_hp > target.hp:
target.current_hp = target.hp
return True
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def __init__(self, slug=None, id=None):
self.name = "Pound"
self.tech_id = 0
self.category = "attack"
self.type1 = "Normal"
self.type2 = None
self._combat_counter = 0 # number of turns that this technique has been active
self.power = 1
self.effect = []
# If a slug of the technique was provided, autoload it.
if slug or id:
self.load(slug, id)
|
def __init__(self, name=None, id=None):
self.name = "Pound"
self.tech_id = 0
self.category = "attack"
self.type1 = "Normal"
self.type2 = None
self._combat_counter = 0 # number of turns that this technique has been active
self.power = 1
self.effect = []
# If a name of the technique was provided, autoload it.
if name or id:
self.load(name, id)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def load(self, slug, id):
"""Loads and sets this technique's attributes from the technique
database. The technique is looked up in the database by name or id.
:param slug: The slug of the technique to look up in the monster
database.
:param id: The id of the technique to look up in the monster database.
:type slug: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>>
"""
if slug:
results = techniques.lookup(slug, table="technique")
elif id:
results = techniques.database["technique"][id]
else:
# TODO: some kind of useful message here
raise RuntimeError
self.slug = results["slug"]
self.name = trans(results["name_trans"])
self.tech_id = results["id"]
self.category = results["category"]
self.icon = results["icon"]
self._combat_counter = 0
self._life_counter = 0
self.type1 = results["types"][0]
if len(results["types"]) > 1:
self.type2 = results["types"][1]
else:
self.type2 = None
self.power = results["power"]
self.effect = results["effects"]
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
# Load the animation sprites that will be used for this technique
self.animation = results["animation"]
self.images = []
animation_dir = prepare.BASEDIR + "resources/animations/technique/"
directory = sorted(os.listdir(animation_dir))
for image in directory:
if self.animation and image.startswith(self.animation):
self.images.append("animations/technique/" + image)
# Load the sound effect for this technique
sfx_directory = "sounds/technique/"
self.sfx = sfx_directory + results["sfx"]
|
def load(self, name, id):
"""Loads and sets this technique's attributes from the technique
database. The technique is looked up in the database by name or id.
:param name: The name of the technique to look up in the monster
database.
:param id: The id of the technique to look up in the monster database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>>
"""
if name:
results = techniques.lookup(name, table="technique")
elif id:
results = techniques.database["technique"][id]
self.name = results["name"]
self.name_trans = trans(results["name_trans"])
self.tech_id = results["id"]
self.category = results["category"]
self.icon = results["icon"]
self._combat_counter = 0
self._life_counter = 0
self.type1 = results["types"][0]
if len(results["types"]) > 1:
self.type2 = results["types"][1]
else:
self.type2 = None
self.power = results["power"]
self.effect = results["effects"]
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
# Load the animation sprites that will be used for this technique
self.animation = results["animation"]
self.images = []
animation_dir = prepare.BASEDIR + "resources/animations/technique/"
directory = sorted(os.listdir(animation_dir))
for image in directory:
if self.animation and image.startswith(self.animation):
self.images.append("animations/technique/" + image)
# Load the sound effect for this technique
sfx_directory = "sounds/technique/"
self.sfx = sfx_directory + results["sfx"]
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def use(self, user, target):
"""Applies this technique's effects as defined in the "effect" column of the technique
database. This method will execute a function with the same name as the effect defined in
the database. If you want to add a new effect, simply create a new function under the
Technique class with the name of the effect you define in monster.db.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monter.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
:returns: If technique was successful or not
**Examples:**
>>> poison_tech = Technique("technique_poison_sting")
>>> bulbatux.learn(poison_tech)
>>>
>>> bulbatux.moves[0].use(user=bulbatux, target=tuxmander)
"""
# Loop through all the effects of this technique and execute the effect's function.
# TODO: more robust API
successful = False
for effect in self.effect:
if getattr(self, str(effect))(user, target):
successful = True
return successful
|
def use(self, user, target):
"""Applies this technique's effects as defined in the "effect" column of the technique
database. This method will execute a function with the same name as the effect defined in
the database. If you want to add a new effect, simply create a new function under the
Technique class with the name of the effect you define in monster.db.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monter.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
:returns: If technique was successful or not
**Examples:**
>>> poison_tech = Technique("Poison Sting")
>>> bulbatux.learn(poison_tech)
>>>
>>> bulbatux.moves[0].use(user=bulbatux, target=tuxmander)
"""
# Loop through all the effects of this technique and execute the effect's function.
# TODO: more robust API
successful = False
for effect in self.effect:
if getattr(self, str(effect))(user, target):
successful = True
return successful
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def poison(self, user, target):
"""This effect has a chance to apply the poison status effect to a target monster.
Currently there is a 1/10 chance of poison.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monster.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
"""
already_poisoned = any(t for t in target.status if t.slug == "status_poison")
if not already_poisoned and random.randrange(1, 2) == 1:
target.apply_status(Technique("status_poison"))
return True
return False
|
def poison(self, user, target):
"""This effect has a chance to apply the poison status effect to a target monster.
Currently there is a 1/10 chance of poison.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monster.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
"""
already_poisoned = any(t for t in target.status if t.name == "Poison")
if not already_poisoned and random.randrange(1, 2) == 1:
target.apply_status(Technique("Poison"))
return True
return False
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def faint(self, user, target):
"""Faint this monster. Typically, called by combat to faint self, not others.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monster.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
"""
already_fainted = any(t for t in target.status if t.name == "status_faint")
if already_fainted:
raise RuntimeError
else:
target.apply_status(Technique("status_faint"))
return True
|
def faint(self, user, target):
"""Faint this monster. Typically, called by combat to faint self, not others.
:param user: The core.components.monster.Monster object that used this technique.
:param target: The core.components.monster.Monster object that we are using this
technique on.
:type user: core.components.monster.Monster
:type target: core.components.monster.Monster
:rtype: bool
"""
already_fainted = any(t for t in target.status if t.name == "Faint")
if already_fainted:
raise RuntimeError
else:
target.apply_status(Technique("Faint"))
return True
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def main():
"""Add all available states to our scene manager (tools.Control)
and start the game using the pygame interface.
:rtype: None
:returns: None
"""
import pygame
from .control import PygameControl
prepare.init()
control = PygameControl(prepare.ORIGINAL_CAPTION)
control.auto_state_discovery()
# background state is used to prevent other states from
# being required to track dirty screen areas. for example,
# in the start state, there is a menu on a blank background,
# since menus do not clean up dirty areas, the blank,
# "Background state" will do that. The alternative is creating
# a system for states to clean up their dirty screen areas.
control.push_state("BackgroundState")
# basically the main menu
control.push_state("StartState")
# Show the splash screen if it is enabled in the game configuration
if prepare.CONFIG.splash == "1":
control.push_state("SplashState")
control.push_state("FadeInTransition")
# block of code useful for testing
if 0:
import random
from core.components.event.actions.player import Player
from core.components.technique import Technique
# TODO: fix this player/player1 issue
control.player1 = prepare.player1
add_monster = partial(adapter("add_monster"))
Player().add_monster(control, add_monster("Bigfin", 10))
Player().add_monster(control, add_monster("Dollfin", 10))
Player().add_monster(control, add_monster("Rockitten", 10))
Player().add_monster(control, add_monster("Nut", 10))
Player().add_monster(control, add_monster("Sumobug", 10))
add_item = partial(adapter("add_item"))
Player().add_item(control, add_item("Potion", 1))
Player().add_item(control, add_item("Super Potion", 1))
Player().add_item(control, add_item("Capture Device", 1))
for monster in control.player1.monsters:
monster.hp = 100
monster.current_hp = 1
# monster.current_hp = random.randint(1, 2)
monster.apply_status(Technique("status_poison"))
# control.push_state("MonsterMenuState")
from core.components.event.actions.combat import Combat
start_battle = partial(adapter("random_encounter"))
Combat().random_encounter(control, start_battle(1))
control.main()
pygame.quit()
|
def main():
"""Add all available states to our scene manager (tools.Control)
and start the game using the pygame interface.
:rtype: None
:returns: None
"""
import pygame
from .control import PygameControl
prepare.init()
control = PygameControl(prepare.ORIGINAL_CAPTION)
control.auto_state_discovery()
# background state is used to prevent other states from
# being required to track dirty screen areas. for example,
# in the start state, there is a menu on a blank background,
# since menus do not clean up dirty areas, the blank,
# "Background state" will do that. The alternative is creating
# a system for states to clean up their dirty screen areas.
control.push_state("BackgroundState")
# basically the main menu
control.push_state("StartState")
# Show the splash screen if it is enabled in the game configuration
if prepare.CONFIG.splash == "1":
control.push_state("SplashState")
control.push_state("FadeInTransition")
# block of code useful for testing
if 0:
import random
from core.components.event.actions.player import Player
from core.components.technique import Technique
# TODO: fix this player/player1 issue
control.player1 = prepare.player1
add_monster = partial(adapter("add_monster"))
Player().add_monster(control, add_monster("Bigfin", 10))
Player().add_monster(control, add_monster("Dollfin", 10))
Player().add_monster(control, add_monster("Rockitten", 10))
Player().add_monster(control, add_monster("Nut", 10))
Player().add_monster(control, add_monster("Sumobug", 10))
add_item = partial(adapter("add_item"))
Player().add_item(control, add_item("Potion", 1))
Player().add_item(control, add_item("Super Potion", 1))
Player().add_item(control, add_item("Capture Device", 1))
for monster in control.player1.monsters:
monster.hp = 100
monster.current_hp = 1
# monster.current_hp = random.randint(1, 2)
monster.apply_status(Technique("Poison"))
# control.push_state("MonsterMenuState")
from core.components.event.actions.combat import Combat
start_battle = partial(adapter("random_encounter"))
Combat().random_encounter(control, start_battle(1))
control.main()
pygame.quit()
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def check_status(monster, status_name):
return any(t for t in monster.status if t.slug == status_name)
|
def check_status(monster, status_name):
return any(t for t in monster.status if t.name == status_name)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def fainted(monster):
return check_status(monster, "status_faint")
|
def fainted(monster):
return check_status(monster, "Faint")
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def perform_action(self, user, technique, target=None):
"""Do something with the thing: animated
:param user:
:param technique: Not a dict: a Technique or Item
:param target:
:returns:
"""
technique.advance_round()
result = technique.use(user, target)
try:
tools.load_sound(technique.sfx).play()
except AttributeError:
pass
# action is performed, so now use sprites to animate it
# this value will be None if the target is off screen
target_sprite = self._monster_sprite_map.get(target, None)
# slightly delay the monster shake, so technique animation
# is synchronized with the damage shake motion
hit_delay = 0
if user:
message = trans("combat_used_x", {"user": user.name, "name": technique.name})
# TODO: a real check or some params to test if should tackle, etc
if technique in user.moves:
hit_delay += 0.5
user_sprite = self._monster_sprite_map[user]
self.animate_sprite_tackle(user_sprite)
if target_sprite:
self.task(
partial(self.animate_sprite_take_damage, target_sprite),
hit_delay + 0.2,
)
self.task(partial(self.blink, target_sprite), hit_delay + 0.6)
# Track damage
self._damage_map[target].add(user)
else: # assume this was an item used
if result:
message += "\n" + trans("item_success")
else:
message += "\n" + trans("item_failure")
self.alert(message)
self.suppress_phase_change()
else:
if result:
self.suppress_phase_change()
self.alert(
trans(
"combat_status_damage",
{"name": target.name, "status": technique.name},
)
)
if result and target_sprite and hasattr(technique, "images"):
tech_sprite = self.get_technique_animation(technique)
tech_sprite.rect.center = target_sprite.rect.center
self.task(tech_sprite.image.play, hit_delay)
self.task(partial(self.sprites.add, tech_sprite, layer=50), hit_delay)
self.task(tech_sprite.kill, 3)
|
def perform_action(self, user, technique, target=None):
"""Do something with the thing: animated
:param user:
:param technique: Not a dict: a Technique or Item
:param target:
:returns:
"""
technique.advance_round()
result = technique.use(user, target)
try:
tools.load_sound(technique.sfx).play()
except AttributeError:
pass
# action is performed, so now use sprites to animate it
# this value will be None if the target is off screen
target_sprite = self._monster_sprite_map.get(target, None)
# slightly delay the monster shake, so technique animation
# is synchronized with the damage shake motion
hit_delay = 0
if user:
message = trans(
"combat_used_x", {"user": user.name, "name": technique.name_trans}
)
# TODO: a real check or some params to test if should tackle, etc
if technique in user.moves:
hit_delay += 0.5
user_sprite = self._monster_sprite_map[user]
self.animate_sprite_tackle(user_sprite)
if target_sprite:
self.task(
partial(self.animate_sprite_take_damage, target_sprite),
hit_delay + 0.2,
)
self.task(partial(self.blink, target_sprite), hit_delay + 0.6)
# Track damage
self._damage_map[target].add(user)
else: # assume this was an item used
if result:
message += "\n" + trans("item_success")
else:
message += "\n" + trans("item_failure")
self.alert(message)
self.suppress_phase_change()
else:
if result:
self.suppress_phase_change()
self.alert(
trans(
"combat_status_damage",
{"name": target.name, "status": technique.name_trans},
)
)
if result and target_sprite and hasattr(technique, "images"):
tech_sprite = self.get_technique_animation(technique)
tech_sprite.rect.center = target_sprite.rect.center
self.task(tech_sprite.image.play, hit_delay)
self.task(partial(self.sprites.add, tech_sprite, layer=50), hit_delay)
self.task(tech_sprite.kill, 3)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def check_party_hp(self):
"""Apply status effects, then check HP, and party status
* Monsters will be removed from play here
:returns: None
"""
for player in self.monsters_in_play.keys():
for monster in self.monsters_in_play[player]:
self.animate_hp(monster)
if monster.current_hp <= 0 and not fainted(monster):
self.remove_monster_actions_from_queue(monster)
self.faint_monster(monster)
|
def check_party_hp(self):
"""Apply status effects, then check HP, and party status
* Monsters will be removed from play here
:returns: None
"""
for player in self.monsters_in_play.keys():
for monster in self.monsters_in_play[player]:
self.animate_hp(monster)
if monster.current_hp <= 0 and faint not in monster.status:
self.remove_monster_actions_from_queue(monster)
self.faint_monster(monster)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def open_swap_menu(self):
"""Open menus to swap monsters in party
:return: None
"""
def swap_it(menuitem):
monster = menuitem.game_object
trans = translator.translate
if monster in self.game.get_state_name("CombatState").active_monsters:
tools.open_dialog(
self.game, [trans("combat_isactive", {"name": monster.name})]
)
return
elif monster.current_hp < 1:
tools.open_dialog(
self.game, [trans("combat_fainted", {"name": monster.name})]
)
player = self.game.player1
target = player.monsters[0]
swap = Technique("technique_swap")
swap.other = monster
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(player, swap, target)
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
menu = self.game.push_state("MonsterMenuState")
menu.on_menu_selection = swap_it
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
menu.monster = self.monster
|
def open_swap_menu(self):
"""Open menus to swap monsters in party
:return: None
"""
def swap_it(menuitem):
monster = menuitem.game_object
trans = translator.translate
if monster in self.game.get_state_name("CombatState").active_monsters:
tools.open_dialog(
self.game, [trans("combat_isactive", {"name": monster.name})]
)
return
elif monster.current_hp < 1:
tools.open_dialog(
self.game, [trans("combat_fainted", {"name": monster.name})]
)
player = self.game.player1
target = player.monsters[0]
swap = Technique("Swap")
swap.other = monster
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(player, swap, target)
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
menu = self.game.push_state("MonsterMenuState")
menu.on_menu_selection = swap_it
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
menu.monster = self.monster
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def swap_it(menuitem):
monster = menuitem.game_object
trans = translator.translate
if monster in self.game.get_state_name("CombatState").active_monsters:
tools.open_dialog(self.game, [trans("combat_isactive", {"name": monster.name})])
return
elif monster.current_hp < 1:
tools.open_dialog(self.game, [trans("combat_fainted", {"name": monster.name})])
player = self.game.player1
target = player.monsters[0]
swap = Technique("technique_swap")
swap.other = monster
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(player, swap, target)
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
|
def swap_it(menuitem):
monster = menuitem.game_object
trans = translator.translate
if monster in self.game.get_state_name("CombatState").active_monsters:
tools.open_dialog(self.game, [trans("combat_isactive", {"name": monster.name})])
return
elif monster.current_hp < 1:
tools.open_dialog(self.game, [trans("combat_fainted", {"name": monster.name})])
player = self.game.player1
target = player.monsters[0]
swap = Technique("Swap")
swap.other = monster
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(player, swap, target)
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def open_technique_menu(self):
"""Open menus to choose a Technique to use
:return: None
"""
def choose_technique():
# open menu to choose technique
menu = self.game.push_state("Menu")
menu.shrink_to_items = True
# add techniques to the menu
for tech in self.monster.moves:
image = self.shadow_text(tech.name)
item = MenuItem(image, None, None, tech)
menu.add(item)
# position the new menu
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
# set next menu after after selection is made
menu.on_menu_selection = choose_target
def choose_target(menu_item):
# open menu to choose target of technique
technique = menu_item.game_object
state = self.game.push_state("CombatTargetMenuState")
state.on_menu_selection = partial(enqueue_technique, technique)
def enqueue_technique(technique, menu_item):
# enqueue the technique
target = menu_item.game_object
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(self.monster, technique, target)
# close all the open menus
self.game.pop_state() # close target chooser
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
choose_technique()
|
def open_technique_menu(self):
"""Open menus to choose a Technique to use
:return: None
"""
def choose_technique():
# open menu to choose technique
menu = self.game.push_state("Menu")
menu.shrink_to_items = True
# add techniques to the menu
for tech in self.monster.moves:
image = self.shadow_text(tech.name_trans)
item = MenuItem(image, None, None, tech)
menu.add(item)
# position the new menu
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
# set next menu after after selection is made
menu.on_menu_selection = choose_target
def choose_target(menu_item):
# open menu to choose target of technique
technique = menu_item.game_object
state = self.game.push_state("CombatTargetMenuState")
state.on_menu_selection = partial(enqueue_technique, technique)
def enqueue_technique(technique, menu_item):
# enqueue the technique
target = menu_item.game_object
combat_state = self.game.get_state_name("CombatState")
combat_state.enqueue_action(self.monster, technique, target)
# close all the open menus
self.game.pop_state() # close target chooser
self.game.pop_state() # close technique menu
self.game.pop_state() # close the monster action menu
choose_technique()
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def choose_technique():
# open menu to choose technique
menu = self.game.push_state("Menu")
menu.shrink_to_items = True
# add techniques to the menu
for tech in self.monster.moves:
image = self.shadow_text(tech.name)
item = MenuItem(image, None, None, tech)
menu.add(item)
# position the new menu
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
# set next menu after after selection is made
menu.on_menu_selection = choose_target
|
def choose_technique():
# open menu to choose technique
menu = self.game.push_state("Menu")
menu.shrink_to_items = True
# add techniques to the menu
for tech in self.monster.moves:
image = self.shadow_text(tech.name_trans)
item = MenuItem(image, None, None, tech)
menu.add(item)
# position the new menu
menu.anchor("bottom", self.rect.top)
menu.anchor("right", self.game.screen.get_rect().right)
# set next menu after after selection is made
menu.on_menu_selection = choose_target
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def on_menu_selection(self, menu_item):
"""Called when player has selected something from the inventory
Currently, opens a new menu depending on the state context
:param menu_item:
:return:
"""
item = menu_item.game_object
state = self.determine_state_called_from()
if state in item.usable_in:
self.open_confirm_use_menu(item)
else:
msg = trans("item_cannot_use_here", {"name": item.name})
tools.open_dialog(self.game, [msg])
|
def on_menu_selection(self, menu_item):
"""Called when player has selected something from the inventory
Currently, opens a new menu depending on the state context
:param menu_item:
:return:
"""
item = menu_item.game_object
state = self.determine_state_called_from()
if state in item.usable_in:
self.open_confirm_use_menu(item)
else:
msg = trans("item_cannot_use_here", {"name": item.name_trans})
tools.open_dialog(self.game, [msg])
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def initialize_items(self):
"""Get all player inventory items and add them to menu
:return:
"""
for name, properties in self.game.player1.inventory.items():
obj = properties["item"]
image = self.shadow_text(obj.name, bg=(128, 128, 128))
yield MenuItem(image, obj.name, obj.description, obj)
|
def initialize_items(self):
"""Get all player inventory items and add them to menu
:return:
"""
for name, properties in self.game.player1.inventory.items():
obj = properties["item"]
image = self.shadow_text(obj.name_trans, bg=(128, 128, 128))
yield MenuItem(image, obj.name_trans, obj.description_trans, obj)
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def load(self, name, id):
"""Loads and sets this items's attributes from the item.db database. The item is looked up
in the database by name or id.
:param name: The name of the item to look up in the monster.item database.
:param id: The id of the item to look up in the item.db database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>> potion_item = Item()
>>> potion_item.load("Potion", None) # Load an item by name.
>>> potion_item.load(None, 1) # Load an item by id.
>>> pprint.pprint(potion_item.__dict__)
{'description': u'Heals a monster by 50 HP.',
'effect': [u'heal'],
'id': 1,
'name': u'Potion',
'power': 50,
'type': u'Consumable'}
"""
if name:
results = items.lookup(name, table="item")
elif id:
results = items.lookup_by_id(id, table="item")
self.name = results["name"]
self.name_trans = trans(results["name_trans"])
self.description = results["description"]
self.description_trans = trans(results["description_trans"])
self.id = results["id"]
self.type = results["type"]
self.power = results["power"]
self.sprite = results["sprite"]
self.usable_in = results["usable_in"]
self.surface = tools.load_and_scale(self.sprite)
self.surface_size_original = self.surface.get_size()
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
self.effect = results["effects"]
|
def load(self, name, id):
"""Loads and sets this items's attributes from the item.db database. The item is looked up
in the database by name or id.
:param name: The name of the item to look up in the monster.item database.
:param id: The id of the item to look up in the item.db database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>> potion_item = Item()
>>> potion_item.load("Potion", None) # Load an item by name.
>>> potion_item.load(None, 1) # Load an item by id.
>>> pprint.pprint(potion_item.__dict__)
{'description': u'Heals a monster by 50 HP.',
'effect': [u'heal'],
'id': 1,
'name': u'Potion',
'power': 50,
'type': u'Consumable'}
"""
if name:
results = items.lookup(name, table="item")
elif id:
results = items.lookup_by_id(id, table="item")
# Try and get this item's translated name and description if it exists.
if translator.has_key(results["name_trans"]):
self.name = trans(results["name_trans"])
else:
self.name = results["name"]
if translator.has_key(results["description_trans"]):
self.description = trans(results["description_trans"])
else:
self.description = results["description"]
self.id = results["id"]
self.type = results["type"]
self.power = results["power"]
self.sprite = results["sprite"]
self.usable_in = results["usable_in"]
self.surface = tools.load_and_scale(self.sprite)
self.surface_size_original = self.surface.get_size()
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
self.effect = results["effects"]
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def calc_bounding_rect(self):
"""A rect object that contains all sprites of this group"""
rect = super(RelativeGroup, self).calc_bounding_rect()
# return self.calc_absolute_rect(rect)
return rect
|
def calc_bounding_rect(self):
"""A rect object that contains all sprites of this group"""
rect = super(RelativeGroup, self).calc_bounding_rect()
for sprite in self.sprites():
print(sprite, sprite.rect)
# return self.calc_absolute_rect(rect)
return rect
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
def load(self, name, id):
"""Loads and sets this technique's attributes from the technique
database. The technique is looked up in the database by name or id.
:param name: The name of the technique to look up in the monster
database.
:param id: The id of the technique to look up in the monster database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>>
"""
if name:
results = techniques.lookup(name, table="technique")
elif id:
results = techniques.database["technique"][id]
self.name = results["name"]
self.name_trans = trans(results["name_trans"])
self.tech_id = results["id"]
self.category = results["category"]
self.icon = results["icon"]
self._combat_counter = 0
self._life_counter = 0
self.type1 = results["types"][0]
if len(results["types"]) > 1:
self.type2 = results["types"][1]
else:
self.type2 = None
self.power = results["power"]
self.effect = results["effects"]
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
# Load the animation sprites that will be used for this technique
self.animation = results["animation"]
self.images = []
animation_dir = prepare.BASEDIR + "resources/animations/technique/"
directory = sorted(os.listdir(animation_dir))
for image in directory:
if self.animation and image.startswith(self.animation):
self.images.append("animations/technique/" + image)
# Load the sound effect for this technique
sfx_directory = "sounds/technique/"
self.sfx = sfx_directory + results["sfx"]
|
def load(self, name, id):
"""Loads and sets this technique's attributes from the technique
database. The technique is looked up in the database by name or id.
:param name: The name of the technique to look up in the monster
database.
:param id: The id of the technique to look up in the monster database.
:type name: String
:type id: Integer
:rtype: None
:returns: None
**Examples:**
>>>
"""
if name:
results = techniques.lookup(name, table="technique")
elif id:
results = techniques.database["technique"][id]
# Try and get this item's translated name if it exists.
if translator.has_key(results["name_trans"]):
self.name = trans(results["name_trans"])
else:
self.name = results["name"]
self.tech_id = results["id"]
self.category = results["category"]
self.icon = results["icon"]
self._combat_counter = 0
self._life_counter = 0
self.type1 = results["types"][0]
if len(results["types"]) > 1:
self.type2 = results["types"][1]
else:
self.type2 = None
self.power = results["power"]
self.effect = results["effects"]
# TODO: maybe break out into own function
from operator import itemgetter
self.target = map(
itemgetter(0),
filter(
itemgetter(1),
sorted(results["target"].items(), key=itemgetter(1), reverse=True),
),
)
# Load the animation sprites that will be used for this technique
self.animation = results["animation"]
self.images = []
animation_dir = prepare.BASEDIR + "resources/animations/technique/"
directory = sorted(os.listdir(animation_dir))
for image in directory:
if self.animation and image.startswith(self.animation):
self.images.append("animations/technique/" + image)
# Load the sound effect for this technique
sfx_directory = "sounds/technique/"
self.sfx = sfx_directory + results["sfx"]
|
https://github.com/Tuxemon/Tuxemon/issues/160
|
Traceback (most recent call last):
File "./tuxemon.py", line 60, in <module>
main()
File "/tmp/Tuxemon/tuxemon/core/main.py", line 109, in main
control.main()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 512, in main
self.main_loop()
File "/tmp/Tuxemon/tuxemon/core/control.py", line 573, in main_loop
self.update(time_delta)
File "/tmp/Tuxemon/tuxemon/core/control.py", line 203, in update
state.update(dt)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 156, in update
self.update_phase()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 328, in update_phase
self.handle_action_queue()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 338, in handle_action_queue
self.check_party_hp()
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 614, in check_party_hp
self.faint_monster(monster)
File "/tmp/Tuxemon/tuxemon/core/states/combat/combat.py", line 581, in faint_monster
awarded_exp = monster.total_experience/monster.level/len(self._damage_map[monster])
KeyError: <core.components.monster.Monster object at 0x7fb24236ddd0>
|
KeyError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.