Exemplo n.º 1
0
 def test_open_geotiff(self):
     """Test to open a GeoTiff file"""
     ds_ref = psyd.open_dataset(bt.get_file('test-t2m-u-v.nc'))
     ds_tiff = psyd.open_dataset(
         bt.get_file('test-t2m-1979-01-31T18-00-00.tif'), engine='gdal')
     self.assertListEqual(ds_tiff.Band1.values.tolist(),
                          ds_ref.isel(time=0, lev=0).t2m.values.tolist())
Exemplo n.º 2
0
 def test_idims(self):
     ds = psyd.open_dataset(os.path.join(bt.test_dir, 'test-t2m-u-v.nc'))
     arr = psyd.InteractiveArray(ds.t2m[1:, 3], base=ds)
     dims = arr.idims
     for dim in ['time', 'lev', 'lat', 'lon']:
         self.assertEqual(
             psyd.safe_list(ds[dim][dims[dim]]),
             psyd.safe_list(arr.coords[dim]),
             msg="Slice %s for dimension %s is wrong!" % (dims[dim], dim))
Exemplo n.º 3
0
 def test_open_mf_geotiff(self):
     """Test to open multiple GeoTiff files and extract the time from the
     file name"""
     ds_ref = psyd.open_dataset(bt.get_file('test-t2m-u-v.nc'))
     ds_tiff = psyd.open_mfdataset(bt.get_file('test-t2m-*.tif'),
                                   engine='gdal',
                                   t_format='test-t2m-%Y-%m-%dT%H-%M-%S')
     self.assertListEqual(
         ds_ref.isel(time=[0, 1], lev=0).t2m.values.tolist(),
         ds_tiff.Band1.values.tolist())
     self.assertListEqual(
         pd.to_datetime(ds_tiff.time.values).tolist(),
         pd.to_datetime(ds_ref.time[:2].values).tolist())
Exemplo n.º 4
0
 def _test_coord(self, func_name, name, uname=None, name2d=False,
                   circ_name=None):
     def check_ds(name):
         self.assertEqual(getattr(d, func_name)(ds.t2m).name, name)
         if name2d:
             self.assertEqual(getattr(d, func_name)(ds.t2m_2d).name, name)
         else:
             self.assertIsNone(getattr(d, func_name)(ds.t2m_2d))
     uname = uname or name
     circ_name = circ_name or name
     ds = psyd.open_dataset(os.path.join(bt.test_dir, 'test-t2m-u-v.nc'))
     d = psyd.CFDecoder(ds)
     check_ds(name)
     ds.close()
     ds = psyd.open_dataset(os.path.join(bt.test_dir, 'icon_test.nc'))
     d = psyd.CFDecoder(ds)
     check_ds(uname)
     ds.close()
     ds = psyd.open_dataset(
         os.path.join(bt.test_dir, 'circumpolar_test.nc'))
     d = psyd.CFDecoder(ds)
     check_ds(circ_name)
     ds.close()
Exemplo n.º 5
0
def create_screenshot(
    code: str,
    output: str,
    make_plot: bool = False,
    enable: bool = None,
    plotmethod: str = "mapplot",
    minwidth=None,
    generate=rebuild_screenshots,
) -> str:
    """Generate a screenshot of the GUI."""
    from PyQt5.QtWidgets import QApplication, QSizePolicy  # pylint: disable=no-name-in-module
    from psy_view.ds_widget import DatasetWidget
    from psyplot.data import open_dataset

    output = osp.join("_static", output)
    if on_rtd:
        return output

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    if not generate and osp.exists(output):
        return output

    ds_widget = DatasetWidget(open_dataset(osp.join(confdir, "demo.nc")))
    ds_widget.plotmethod = plotmethod

    if make_plot:
        ds_widget.variable_buttons["t2m"].click()

    if minwidth:
        ds_widget.setMinimumWidth(minwidth)

    options = {"ds_widget": ds_widget}
    exec("w = " + code, options)
    w = options['w']

    if enable is not None:
        w.setEnabled(enable)

    w.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)

    ds_widget.show()  # to make sure we can see everything

    w.grab().save(osp.join(confdir, output))
    ds_widget.close_sp()
    ds_widget.close()
    return output
Exemplo n.º 6
0
    def load_mask(self, data, value):
        if isinstance(value, str) and value in data.psy.base:
            mask = data.psy.base[value]
            if not set(mask.dims).intersection(data.dims):
                raise ValueError("No intersection between dimensions of mask "
                                 f"{value}: {mask.dims}, and the data: "
                                 f"{data.dims}")
        elif isinstance(value, str):
            try:
                mask = open_dataset(value)
            except Exception:
                raise ValueError(
                    f"{value} is not in the base dataset of "
                    f"{data.psy.arr_name} and could not be loaded with "
                    f"psy.open_dataset({repr(value)})")
            else:
                available_vars = [
                    v for v in mask
                    if set(mask[v].dims).intersection(data.dims)
                ]
                if not available_vars:
                    raise ValueError(f"No variable in {value} has an overlap "
                                     f"with the data dimensions {data.dims}")
                else:
                    mask = mask[available_vars[0]]
        else:
            mask = value
        base_var = next(data.psy.iter_base_variables)

        # aggregate mask over dimensions that are not in the base variable
        dims2agg = set(mask.dims).difference(set(base_var.dims))
        if dims2agg:
            mask = mask.any(list(dims2agg))

        # select idims of mask
        idims = {
            d: sl
            for d, sl in data.psy.idims.items()
            if d in mask.dims and d not in data.dims
        }
        if idims:
            mask = mask.isel(**idims)

        return mask
Exemplo n.º 7
0
 def test_get_enhanced_attrs_01_arr(self):
     """Test the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs` method
     """
     ds = psyd.open_dataset(bt.get_file('test-t2m-u-v.nc'))
     plotter = TestPlotter(ds.t2m)
     attrs = ds.t2m.attrs.copy()
     for key, val in ds.lon.attrs.items():
         attrs['x' + key] = val
     for key, val in ds.lat.attrs.items():
         attrs['y' + key] = val
     for key, val in ds.lev.attrs.items():
         attrs['z' + key] = val
     for key, val in ds.time.attrs.items():
         attrs['t' + key] = val
     attrs['xname'] = 'lon'
     attrs['yname'] = 'lat'
     attrs['zname'] = 'lev'
     attrs['tname'] = 'time'
     attrs['name'] = 't2m'
     self.assertEqual(dict(plotter.get_enhanced_attrs(plotter.plot_data)),
                      dict(attrs))
Exemplo n.º 8
0
 def test_get_enhanced_attrs_02_list(self):
     """Test the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs` method
     """
     ds = psyd.open_dataset(bt.get_file('test-t2m-u-v.nc'))
     plotter = TestPlotter(
         psyd.InteractiveList(
             ds.psy.create_list(name=['t2m', 'u'], x=0, t=0)))
     attrs = {}
     for key, val in ds.t2m.attrs.items():
         attrs['t2m' + key] = val
     for key, val in ds.u.attrs.items():
         attrs['u' + key] = val
     for key, val in ds.lon.attrs.items():
         attrs['x' + key] = val
     for key, val in ds.lat.attrs.items():
         attrs['y' + key] = val
         attrs['x' + key] = val  # overwrite the longitude information
     # the plot_data has priority over the base variable, therefore we
     # the plotter should replace the y information with the z information
     for key, val in ds.lev.attrs.items():
         attrs['z' + key] = val
         attrs['y' + key] = val  # overwrite the latitude information
     for key, val in ds.time.attrs.items():
         attrs['t' + key] = val
     for key in set(ds.t2m.attrs) & set(ds.u.attrs):
         if ds.t2m.attrs[key] == ds.u.attrs[key]:
             attrs[key] = ds.t2m.attrs[key]
     attrs['zname'] = attrs['yname'] = 'lev'
     attrs['xname'] = 'lat'
     attrs['tname'] = 'time'
     attrs['lon'] = attrs['x'] = ds.lon.values[0]
     attrs['time'] = attrs['t'] = pd.to_datetime(
         ds.time.values[0]).isoformat()
     self.maxDiff = None
     self.assertEqual(dict(plotter.get_enhanced_attrs(plotter.plot_data)),
                      dict(attrs))
Exemplo n.º 9
0
def test_ds(test_file):
    import psyplot.data as psyd
    with psyd.open_dataset(test_file) as ds:
        yield ds
Exemplo n.º 10
0
 def _grid_ds(grid):
     ds = psyd.open_dataset(osp.join(bt.test_dir, 'grids', grid + '.nc'))
     open_datasets.append(ds)
     return ds
Exemplo n.º 11
0
def test_ds():
    import psyplot.data as psyd
    test_file = osp.join(osp.dirname(__file__), '..', 'test-t2m-u-v.nc')
    with psyd.open_dataset(test_file) as ds:
        yield ds