示例#1
0
 def test_format_coord(self):
     """Test the formatting of a coordinate"""
     stradi = Straditizer(
         osp.join(test_dir, 'test_figures', 'basic_diagram.png'))
     stradi.data_xlim = stradi.data_ylim = np.array([10, 30])
     stradi.init_reader()
     stradi.data_reader._get_column_starts()
     ax = stradi.ax
     x, y = 11.0, 11.0
     ref = (stradi._orig_format_coord(x, y) +
            "DataReader: x=%s y=%sColumn 0 x=%s" %
            (ax.format_xdata(1.), ax.format_ydata(1.), ax.format_xdata(1.)))
     self.assertEqual(ax.format_coord(x, y), ref)
示例#2
0
    def from_clipboard(self):
        """Open a straditizer from an Image in the clipboard

        This method uses the :func:`PIL.ImageGrab.grabclipboard` function to
        open a new straditizer from the clipboard."""
        from PIL import ImageGrab
        from straditize.straditizer import Straditizer
        image = ImageGrab.grabclipboard()
        if np.shape(image)[-1] == 3:
            image.putalpha(255)
        stradi = Straditizer(image)
        return self.finish_loading(stradi)
示例#3
0
 def reload_autosaved(self):
     """Reload the autosaved straditizer and close the old one"""
     from straditize.straditizer import Straditizer
     if not self.autosaved:
         return
     answer = QMessageBox.question(
         self, 'Reload autosave',
         'Shall I reload the last autosaved stage? This will close the '
         'current figures.')
     if answer == QMessageBox.Yes:
         self.close_straditizer()
         stradi = Straditizer.from_dataset(self.autosaved.pop(0))
         self.menu_actions.finish_loading(stradi)
示例#4
0
    def init_stradi(self,
                    datalim=True,
                    columns=True,
                    names=True,
                    digitize=True,
                    samples=True,
                    axes=False):
        path = self.filepath
        if not axes:
            path += '-no-axes'
        image = Image.open(path + '.png')
        stradi = Straditizer(image)
        if datalim:
            stradi.data_xlim = self.data_xlim
            stradi.data_ylim = self.data_ylim
            stradi.init_reader('area' if not self.use_bars else 'bars')
        else:
            return stradi

        stradi.yaxis_px = np.array([0, np.diff(self.data_ylim)[0]])
        stradi.yaxis_data = np.array(self.sp[0].psy.ax.get_ylim())[::-1]

        if columns:
            stradi.data_reader.column_starts = self.column_starts
        else:
            return stradi

        if names:
            stradi.colnames_reader.column_names = self.data.columns.tolist()

        self.set_xtranslation(stradi)

        if digitize:
            stradi.data_reader.digitize()
            stradi.data_reader._full_df.loc[:] = np.where(
                stradi.data_reader.full_df.values, self.full_df.values, 0)

        else:
            return stradi

        if samples:
            stradi.data_reader.sample_locs = self.transformed_data

        return stradi
示例#5
0
def start_app(fname=None,
              output=None,
              xlim=None,
              ylim=None,
              full=False,
              reader_type='area',
              **kwargs):
    """
    Start the psyplot GUI with the straditizer setup

    Parameters
    ----------
    fname: str
        Either the path to a picture to digitize or a previously saved
        straditizer project (ending with ``'.pkl'``)
    output: str
        The path to the csv file where to save the digitized diagram
    xlim: list of int of length 2
        The x-limits of the data part of the diagram
    ylim: list of int of length 2
        The y-limits of the data part of the diagram
    full: bool
        If True, the image is digitzed and x- and ylim are set to the entire
        share of the array
    reader_type: { 'area' | 'bars' | 'rounded bars' | 'stacked area' | 'line' }
        Specify the reader type
    %(psyplot_gui.start_app.parameters.no_fnames|output)s
    """
    import numpy as np

    def set_x_and_ylim(stradi):
        if not xlim and stradi.data_xlim is None:
            stradi.data_xlim = [0, np.shape(stradi.image)[1]]
        if not ylim and stradi.data_ylim is None:
            stradi.data_ylim = [0, np.shape(stradi.image)[0]]

    if not output:
        from psyplot_gui.compat.qtcompat import QApplication
        from psyplot_gui import start_app, send_files_to_psyplot
        exec_ = kwargs.pop('exec_', True)
        if exec_:
            app = QApplication(sys.argv)
        cwd = osp.abspath(kwargs.get('pwd') or os.getcwd())
        mainwindow = start_app(exec_=False, callback='', **kwargs)
        if mainwindow is None:
            send_files_to_psyplot('straditize', [fname], None, xlim, ylim,
                                  full, reader_type)
            return
        stradi_widget = mainwindow.plugins[
            'straditize.widgets:StraditizerWidgets:straditizer']
        stradi_widget.switch_to_straditizer_layout()
        if fname:
            stradi_widget.menu_actions.open_straditizer(osp.join(cwd, fname))
            if not fname.endswith('.pkl') and (xlim or ylim):
                set_x_and_ylim(stradi_widget.straditizer)
            stradi = stradi_widget.straditizer
        else:
            if exec_:
                sys.excepthook = mainwindow.excepthook
                sys.exit(app.exec_())
            return mainwindow
    else:
        if not fname:
            raise IOError(
                'A file must be provided if the `output` parameter is used!')
        from straditize.straditizer import Straditizer
        if fname.endswith('.pkl'):
            stradi = Straditizer.load(fname, plot=False)
        else:
            from PIL import Image
            with Image.open(fname) as _image:
                image = Image.fromarray(np.array(_image.convert('RGBA')),
                                        'RGBA')
            stradi = Straditizer(image)
            stradi.set_attr('image_file', fname)
            set_x_and_ylim(stradi)
    if xlim:
        stradi.data_xlim = xlim
    if ylim:
        stradi.data_ylim = ylim
    if xlim or ylim or full:
        set_x_and_ylim(stradi)
        if reader_type == 'stacked area':
            import straditize.widgets.stacked_area_reader
        stradi.init_reader(reader_type)
    if output:
        stradi.data_reader.digitize()
        stradi.data_reader.sample_locs, stradi.data_reader.rough_locs = \
            stradi.data_reader.find_samples()
        stradi.final_df.to_csv(output)
    elif exec_:
        stradi_widget.refresh()
        sys.excepthook = mainwindow.excepthook
        sys.exit(app.exec_())
    else:
        stradi_widget.refresh()
        return mainwindow
示例#6
0
    def open_straditizer(self, fname=None, *args, **kwargs):
        """Open a straditizer from an image or project file

        Parameters
        ----------
        fname: :class:`str`, :class:`PIL.Image.Image` or ``None``
            The path to the file to import. If None, a QFileDialog is opened
            and the user is asked for a file name. The action then depends on
            the ending of ``fname``:

            ``'.nc'`` or ``'.nc4'``
                we expect a netCDF file and open it with
                :func:`xarray.open_dataset` and load the straditizer with the
                :meth:`straditize.straditizer.Straditizer.from_dataset`
                constructor
            ``'.pkl'``
                We expect a pickle file and load the straditizer with
                :func:`pickle.load`
            any other ending
                We expect an image file and use the :func:`PIL.Image.open`
                function

            At the end, the loading is finished with the :meth:`finish_loading`
            method"""
        from straditize.straditizer import Straditizer
        if fname is None or (not isinstance(fname, six.string_types)
                             and np.ndim(fname) < 2):
            fname = QFileDialog.getOpenFileName(
                self.straditizer_widgets, 'Straditizer project',
                self._dirname_to_use or self._start_directory,
                'Projects and images '
                '(*.nc *.nc4 *.pkl *.jpeg *.jpg *.pdf *.png *.raw *.rgba *.tif'
                ' *.tiff);;'
                'NetCDF files (*.nc *.nc4);;'
                'Pickle files (*.pkl);;'
                'All images '
                '(*.jpeg *.jpg *.pdf *.png *.raw *.rgba *.tif *.tiff);;'
                'Joint Photographic Experts Group (*.jpeg *.jpg);;'
                'Portable Document Format (*.pdf);;'
                'Portable Network Graphics (*.png);;'
                'Raw RGBA bitmap (*.raw *.rbga);;'
                'Tagged Image File Format(*.tif *.tiff);;'
                'All files (*)')
            if with_qt5:  # the filter is passed as well
                fname = fname[0]
        if not np.ndim(fname) and not fname:
            return
        elif np.ndim(fname) >= 2:
            stradi = Straditizer(fname, *args, **kwargs)
        elif fname.endswith('.nc') or fname.endswith('.nc4'):
            import xarray as xr
            ds = xr.open_dataset(fname)
            stradi = Straditizer.from_dataset(ds.load(), *args, **kwargs)
            stradi.set_attr('project_file', fname)
            ds.close()
            stradi.set_attr('loaded', str(dt.datetime.now()))
        elif fname.endswith('.pkl'):
            stradi = Straditizer.load(fname, *args, **kwargs)
            stradi.set_attr('project_file', fname)
            stradi.set_attr('loaded', str(dt.datetime.now()))
        else:
            from PIL import Image
            with Image.open(fname) as _image:
                image = Image.fromarray(np.array(_image.convert('RGBA')),
                                        'RGBA')
            w, h = image.size
            im_size = w * h
            if im_size > 20e6:
                recom_frac = 17403188.0 / im_size
                answer = (
                    QMessageBox.Yes if self.straditizer_widgets.always_yes else
                    QMessageBox.question(
                        self.straditizer_widgets, "Large straditizer image",
                        "This is a rather large image with %1.0f pixels. "
                        "Shall I reduce it to %1.0f%% of it's size for a "
                        "better interactive experience?<br>"
                        "If not, you can rescale it via<br><br>"
                        "Transform source image &rarr; Rescale image" %
                        (im_size, 100. * recom_frac)))
                if answer == QMessageBox.Yes:
                    image = image.resize((int(round(w * recom_frac)),
                                          int(round(h * recom_frac))))

            stradi = Straditizer(image, *args, **kwargs)
            stradi.set_attr('image_file', fname)
        self.finish_loading(stradi)
        self._dirname_to_use = None
示例#7
0
 def test_guess_data_lims(self):
     stradi = Straditizer(
         osp.join(test_dir, 'test_figures', 'basic_diagram.png'))
     xlim, ylim = stradi.guess_data_lims()
     self.assertEqual(list(xlim), [10, 27])
     self.assertEqual(list(ylim), [10, 30])