Пример #1
0
 def update(self, value):
     self.remove()
     if value is None:
         return
     # we update id_color here to make sure that the colors are only used
     # if necessary
     self.id_color.update(self.id_color.value)
     self._plot = []
     if self.plot.value is None:
         linestyles = repeat('-')
     else:
         linestyles = cycle(safe_list(self.plot.value))
     for vals, da, fit_type, c, ls in zip(cycle(value), self.iter_data,
                                          cycle(safe_list(self.fit.value)),
                                          self.id_color.colors, linestyles):
         if da.ndim > 1:
             da = da[0]
         try:
             x = psyps._get_index_vals(da.to_series().index)
         except AttributeError:  # old psy-simple version
             x = da.to_series().index
         if fit_type in ['robust', 'fit']:
             y = vals[0] + vals[1] * x
         else:
             y = fit_type(x, *vals)
         self._plot.extend(self.ax.plot(x, y, color=c, ls=ls))
Пример #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))
Пример #3
0
    def get_colormap(cls, names=[], N=10, *args, **kwargs):
        """Open a :class:`ColormapDialog` and get a colormap

        Parameters
        ----------
        %(ColormapModel.parameters)s

        Other Parameters
        ----------------
        ``*args, **kwargs``
            Anything else that is passed to the ColormapDialog

        Returns
        -------
        str or matplotlib.colors.Colormap
            Either the name of a standard colormap available via
            :func:`psy_simple.colors.get_cmap` or a colormap
        """
        names = safe_list(names)
        obj = cls(names, N, *args, **kwargs)
        vbox = obj.layout()
        buttons = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, parent=obj)
        buttons.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
        vbox.addWidget(buttons)
        buttons.accepted.connect(obj.accept)
        buttons.rejected.connect(obj.reject)

        obj.table.selectionModel().selectionChanged.connect(
            lambda indices: buttons.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(
                bool(indices)))
        accepted = obj.exec_()
        if accepted:
            return obj.table.chosen_colormap
Пример #4
0
    def set_method(self, i):
        value = next(islice(cycle(safe_list(self.value)), i, i + 1))
        if value is None:
            self.model = None
            self.method = None
        elif isinstance(value, type) and issubclass(value, GenericModel):
            self.model = value
            self.method = 'curve_fit'
        elif hasattr(value, 'fit'):
            self.model = value
            self.method = 'generic'
        elif callable(value):

            class Model(GenericModel):

                function = staticmethod(value)

            self.model = Model
            self.method = 'curve_fit'
        elif value.lower().startswith('poly'):
            self.model = partial(np.polyfit, deg=int(value[4:]), cov=True)
            self.method = 'poly'
        else:
            self.model = sm.RLM if value == 'robust' else sm.OLS
            self.method = 'statsmodels'
Пример #5
0
 def p0(self, i=None):
     if self.index_in_list is not None or i is None:
         i = 0
     val = next(islice(cycle(safe_list(self.value)), i, i + 1))
     if isinstance(val, six.string_types) and val == 'auto':
         return self._estimate_p0(i)
     return val
Пример #6
0
def show_colormaps(names=[], N=10, show=True, use_qt=None):
    """Function to show standard colormaps from pyplot

    Parameters
    ----------
    ``*args``: str or :class:`matplotlib.colors.Colormap`
        If a colormap, it returned unchanged.
        %(cmap_note)s
    N: int, optional
        Default: 11. The number of increments in the colormap.
    show: bool, optional
        Default: True. If True, show the created figure at the end with
        pyplot.show(block=False)
    use_qt: bool
        If True, use the
        :class:`psy_simple.widgets.color.ColormapDialog.show_colormaps`, if
        False use a matplotlib implementation based on [1]_. If None, use
        the Qt implementation if it is running in the psyplot GUI.

    Returns
    -------
    psy_simple.widgets.color.ColormapDialog or matplitlib.figure.Figure
        Depending on `use_qt`, either an instance of the
        :class:`psy_simple.widgets.color.ColormapDialog` or the
        :class:`matplotlib.figure.Figure`

    References
    ----------
    .. [1] http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
    """
    names = safe_list(names)
    if use_qt or (use_qt is None and psyplot.with_gui):
        from psy_simple.widgets.colors import ColormapDialog
        from psyplot_gui.main import mainwindow
        return ColormapDialog.show_colormap(names, N, show, parent=mainwindow)
    import matplotlib.pyplot as plt
    # This example comes from the Cookbook on www.scipy.org.  According to the
    # history, Andrew Straw did the conversion from an old page, but it is
    # unclear who the original author is.
    a = np.vstack((np.linspace(0, 1, 256).reshape(1, -1)))
    # Get a list of the colormaps in matplotlib.  Ignore the ones that end with
    # '_r' because these are simply reversed versions of ones that don't end
    # with '_r'
    cmaps = _get_cmaps(names)
    nargs = len(cmaps) + 1
    fig = plt.figure(figsize=(5, 10))
    fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99)
    for i, m in enumerate(cmaps):
        ax = plt.subplot(nargs, 1, i+1)
        plt.axis("off")
        plt.pcolormesh(a, cmap=get_cmap(m, N + 1))
        pos = list(ax.get_position().bounds)
        fig.text(pos[0] - 0.01, pos[1], m, fontsize=10,
                 horizontalalignment='right')
    fig.canvas.set_window_title("Figure %i: Predefined colormaps" % fig.number)
    if show:
        plt.show(block=False)
    return fig
Пример #7
0
    def open_external_files(self, fnames=[], project=None, engine=None,
                            plot_method=None, name=None, dims=None,
                            encoding=None, enable_post=False,
                            seaborn_style=None, concat_dim=get_default_value(
                                xr.open_mfdataset, 'concat_dim'), chname={}):
        """
        Open external files

        Parameters
        ----------
        %(make_plot.parameters.fnames|project|engine|plot_method|name|dims|encoding|enable_post|seaborn_style|concat_dim|chname)s
        """
        if seaborn_style is not None:
            import seaborn as sns
            sns.set_style(seaborn_style)
        if project is not None:
            fnames = [s.split(',') for s in fnames]
            if not isinstance(project, dict):
                project = psyd.safe_list(project)[0]
            single_files = (l[0] for l in fnames if len(l) == 1)
            alternative_paths = defaultdict(lambda: next(single_files, None))
            alternative_paths.update(list(l for l in fnames if len(l) == 2))
            p = psy.Project.load_project(
                project, alternative_paths=alternative_paths,
                engine=engine, main=not psy.gcp(), encoding=encoding,
                enable_post=enable_post, chname=chname)
            if isinstance(project, six.string_types):
                p.attrs.setdefault('project_file', project)
            return True
        else:
            self.new_plots(False)
            self.plot_creator.open_dataset(fnames, engine=engine,
                                           concat_dim=concat_dim)
            if name == 'all':
                ds = self.plot_creator.get_ds()
                name = sorted(set(ds.variables) - set(ds.coords))
            self.plot_creator.insert_array(
                list(filter(None, psy.safe_list(name))))
            if dims is not None:
                ds = self.plot_creator.get_ds()
                dims = {key: ', '.join(
                    map(str, val)) for key, val in six.iteritems(
                        dims)}
                for i, vname in enumerate(
                        self.plot_creator.array_table.vnames):
                    self.plot_creator.array_table.selectRow(i)
                    self.plot_creator.array_table.update_selected(
                        )
                self.plot_creator.array_table.selectAll()
                var = ds[vname[0]]
                self.plot_creator.array_table.update_selected(
                    dims=var.psy.decoder.correct_dims(var, dims.copy()))
            if plot_method:
                self.plot_creator.pm_combo.setCurrentIndex(
                    self.plot_creator.pm_combo.findText(plot_method))
            self.plot_creator.exec_()
            return True
Пример #8
0
 def create_variable(self, ds, vname, data, **kwargs):
     """Insert the data into a variable in an :class:`xr.Dataset`"""
     attrs = self.nc_meta[vname].copy()
     dims = safe_list(attrs.pop('dims', vname))
     if vname in ds:
         ds.variables[vname][kwargs] = data
     else:
         v = xr.Variable(dims, np.asarray(data), attrs=attrs)
         ds[vname] = v
     return vname
Пример #9
0
 def __init__(self, filename_or_obj):
     """
     Parameters
     ----------
     filename_or_obj: str
         The path to the GeoTIFF file or a gdal dataset"""
     if isinstance(psyd.safe_list(filename_or_obj)[0], six.string_types):
         self.ds = gdal.Open(filename_or_obj)
         self._filename = filename_or_obj
     else:
         self.ds = filename_or_obj
         fnames = self.ds.GetFileList()
         self._filename = fnames[0] if len(fnames) == 1 else fnames
Пример #10
0
    def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs):
        """Show a colormap dialog

        Parameters
        ----------
        %(show_colormaps.parameters.no_use_qt)s"""
        names = safe_list(names)
        obj = cls(names, N, *args, **kwargs)
        vbox = obj.layout()
        buttons = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Close, parent=obj)
        buttons.rejected.connect(obj.close)
        vbox.addWidget(buttons)
        if show:
            obj.show()
        return obj
Пример #11
0
 def update(self, value):
     value = safe_list(value)
     if np.ndim(value) == 1:
         value = [value]
     value = cycle(value)
     if isinstance(self.raw_data,
                   InteractiveList) and (self.index_in_list is None):
         self._range = [[] for _ in range(len(self.raw_data))]
         for i, da in enumerate(list(self.iter_raw_data)):
             self.index_in_list = i
             super(XFitRange, self).update(next(value))
         self.index_in_list = None
     elif not isinstance(self.raw_data, InteractiveList) and (
             self.index_in_list is not None):
         self._range = [[] for _ in range(self.index_in_list + 1)]
         super(XFitRange, self).update(next(value))
     else:
         super(XFitRange, self).update(next(value))
Пример #12
0
    def insert_from_combo(self):
        cb = self.coord_combo
        inserts = list(
            ind.row() - 1
            for ind in cb.view().selectionModel().selectedIndexes()
            if ind.row() > 0)
        if not inserts:
            return
        elif not self._single_selection:
            try:
                current = yaml.load(self.parent().get_text())
            except Exception:
                pass
            else:
                if current:
                    current = self.slice2list(current)
                    inserts = sorted(set(chain(inserts, safe_list(current))))
        else:
            inserts = inserts[0]

        self.parent().set_obj(inserts)
Пример #13
0
    def insert_from_combo(self):
        cb = self.coord_combo
        inserts = list(ind.row() - 1
                       for ind in cb.view().selectionModel().selectedIndexes()
                       if ind.row() > 0)
        if not inserts:
            return
        elif not self._single_selection:
            try:
                current = yaml.load(self.parent().get_text(),
                                    Loader=yaml.Loader)
            except Exception:
                pass
            else:
                if current:
                    current = self.slice2list(current)
                    inserts = sorted(set(chain(inserts, safe_list(current))))
        else:
            inserts = inserts[0]

        self.parent().set_obj(inserts)
Пример #14
0
def _get_cmaps(names):
    """Filter the given `names` for colormaps"""
    import matplotlib.pyplot as plt
    available_cmaps = list(
        chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
    names = safe_list(names)
    wrongs = []
    for arg in (arg for arg in names if (
            not isinstance(arg, Colormap) and arg not in available_cmaps)):
        if isinstance(arg, str):
            similarkeys = get_close_matches(arg, available_cmaps)
        if similarkeys != []:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
        else:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Run function without arguments to see all colormaps" % arg)
        names.remove(arg)
        wrongs.append(arg)
    if not names and not wrongs:
        names = sorted(m for m in available_cmaps if not m.endswith("_r"))
    return names