Exemplo n.º 1
0
 def open_dataframe(self, fname=None, *args, **kwargs):
     """Opens a file dialog and the dataset that has been inserted"""
     if fname is None:
         fname = QFileDialog.getOpenFileName(
             self, 'Open dataset', os.getcwd(),
             'Comma separated files (*.csv);;'
             'Excel files (*.xls *.xlsx);;'
             'JSON files (*.json);;'
             'All files (*)'
             )
         if with_qt5:  # the filter is passed as well
             fname = fname[0]
     if isinstance(fname, pd.DataFrame):
         self.set_df(fname)
     elif not fname:
         return
     else:
         ext = osp.splitext(fname)[1]
         open_funcs = {
             '.xls': pd.read_excel, '.xlsx': pd.read_excel,
             '.json': pd.read_json,
             '.tab': partial(pd.read_csv, delimiter='\t'),
             '.dat': partial(pd.read_csv, delim_whitespace=True),
             }
         open_func = open_funcs.get(ext, pd.read_csv)
         try:
             df = open_func(fname)
         except Exception:
             self.error_msg.showTraceback(
                 '<b>Could not open DataFrame %s with %s</b>' % (
                     fname, open_func))
             return
         self.set_df(df)
Exemplo n.º 2
0
    def _save_image(self, image, fname=None):
        """Save an image to a file

        Parameters
        ----------
        image: PIL.Image.Image
            The image to save
        fname: str or None
            The path of the target filename where to save the `image`. If None,
            A QFileDialog is opened and we ask the user for a filename"""
        if fname is None or not isinstance(fname, six.string_types):
            fname = QFileDialog.getSaveFileName(
                self.straditizer_widgets, 'Straditizer file destination',
                self._start_directory, 'All images '
                '(*.png *.jpeg *.jpg *.pdf *.tif *.tiff);;'
                'Joint Photographic Experts Group (*.jpeg *.jpg);;'
                'Portable Document Format (*.pdf);;'
                'Portable Network Graphics (*.png);;'
                'Tagged Image File Format(*.tif *.tiff);;'
                'All files (*)')
            if with_qt5:  # the filter is passed as well
                fname = fname[0]
        if not fname:
            return
        ext = osp.splitext(fname)[1]
        if ext.lower() in ['.jpg', '.jpeg', '.pdf'] and image.mode == 'RGBA':
            image = rgba2rgb(image)
        image.save(fname)
Exemplo n.º 3
0
    def get_open_file_name(self):
        """Ask the user for a filename for saving the data frame"""
        def check_current():
            dirname = osp.dirname(current)
            if osp.exists(dirname) and osp.isdir(dirname):
                return dirname

        current = self.txt_fname.text().strip()
        start = None
        if current:
            start = check_current()
        if start is None:
            for attr in 'project_file', 'image_file':
                try:
                    current = self.stradi.get_attr(attr)
                except KeyError:
                    pass
                else:
                    start = check_current()
                    if start is not None:
                        break
        if start is None:
            start = os.getcwd()
        fname = QFileDialog.getSaveFileName(
            self, 'DataFrame file destination', start,
            'Excel files (*.xlsx *.xls);;'
            'csv files (*.csv);;'
            'All files (*)')
        if with_qt5:  # the filter is passed as well
            fname = fname[0]
        if not fname:
            return
        self.txt_fname.setText(fname)
Exemplo n.º 4
0
 def open_dataframe(self, fname=None, *args, **kwargs):
     """Opens a file dialog and the dataset that has been inserted"""
     if fname is None:
         fname = QFileDialog.getOpenFileName(
             self, 'Open dataset', os.getcwd(),
             'Comma separated files (*.csv);;'
             'Excel files (*.xls *.xlsx);;'
             'JSON files (*.json);;'
             'All files (*)'
             )
         if with_qt5:  # the filter is passed as well
             fname = fname[0]
     if isinstance(fname, pd.DataFrame):
         self.set_df(fname)
     elif not fname:
         return
     else:
         ext = osp.splitext(fname)[1]
         open_funcs = {
             '.xls': pd.read_excel, '.xlsx': pd.read_excel,
             '.json': pd.read_json,
             '.tab': partial(pd.read_csv, delimiter='\t'),
             '.dat': partial(pd.read_csv, delim_whitespace=True),
             }
         open_func = open_funcs.get(ext, pd.read_csv)
         try:
             df = open_func(fname)
         except Exception:
             self.error_msg.showTraceback(
                 '<b>Could not open DataFrame %s with %s</b>' % (
                     fname, open_func))
             return
         self.set_df(df)
Exemplo n.º 5
0
    def _open_image(self, fname=None):
        """Open an image file

        Parameters
        ----------
        fname: :class:`str`, :class:`PIL.Image.Image` or ``None``
            The path of the image file or the :class:`PIL.Image.Image`. If
            None, a QFileDialog is opened to request the file from the user.

        Returns
        -------
        PIL.Image.Image
            The image file or None if the operation has been cancelled by the
            user"""
        if fname is None or (not isinstance(fname, six.string_types)
                             and np.ndim(fname) < 2):
            fname = QFileDialog.getOpenFileName(
                self.straditizer_widgets, 'Stratigraphic diagram',
                self._dirname_to_use or self._start_directory, 'All images '
                '(*.jpeg *.jpg *.pdf *.png *.raw *.rgba *.tif *.tiff);;'
                'Joint Photographic Experts Group (*.jpeg *.jpg);;'
                'Portable Document Format (*.pdf);;'
                'Portable Network Graphics (*.png);;'
                '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:
            return fname
        else:
            from PIL import Image
            with Image.open(fname) as _image:
                return Image.fromarray(np.array(_image.convert('RGBA')))
Exemplo n.º 6
0
 def _save_preset(self, project, *args, **kwargs):
     fname, ok = QFileDialog.getSaveFileName(
         self, 'Save preset', os.path.join(get_configdir(), 'presets'),
         'YAML file (*.yml *.yaml);;'
         'All files (*)')
     if ok:
         project.save_preset(fname, *args, **kwargs)
Exemplo n.º 7
0
 def _load_preset(self, project, *args, **kwargs):
     fname, ok = QFileDialog.getOpenFileName(
         self, 'Load preset', os.path.join(get_configdir(), "presets"),
         'YAML files (*.yml *.yaml);;'
         'All files (*)')
     if ok:
         project.load_preset(fname, *args, **kwargs)
Exemplo n.º 8
0
 def _open_project(self, *args, **kwargs):
     fname = QFileDialog.getOpenFileName(
         self, 'Project destination', os.getcwd(),
         'Pickle files (*.pkl);;'
         'All files (*)'
         )
     p = psy.Project.load_project(fname, *args, **kwargs)
     p.attrs['project_file'] = fname
     self.update_project_action(p.num)
Exemplo n.º 9
0
 def _open_project(self, *args, **kwargs):
     fname = QFileDialog.getOpenFileName(
         self, 'Project file', os.getcwd(), 'Pickle files (*.pkl);;'
         'All files (*)')
     if with_qt5:  # the filter is passed as well
         fname = fname[0]
     if not fname:
         return
     p = psy.Project.load_project(fname, *args, **kwargs)
     p.attrs['project_file'] = fname
     self.update_project_action(p.num)
Exemplo n.º 10
0
 def _open_project(self, *args, **kwargs):
     fname = QFileDialog.getOpenFileName(
         self, 'Project file', os.getcwd(),
         'Pickle files (*.pkl);;'
         'All files (*)'
         )
     if with_qt5:  # the filter is passed as well
         fname = fname[0]
     if not fname:
         return
     p = psy.Project.load_project(fname, *args, **kwargs)
     p.attrs['project_file'] = fname
     self.update_project_action(p.num)
Exemplo n.º 11
0
 def _export_project(self, p, *args, **kwargs):
     fname = QFileDialog.getSaveFileName(
         self, 'Picture destination', os.getcwd(), 'PDF files (*.pdf);;'
         'Postscript file (*.ps);;'
         'PNG image (*.png);;'
         'JPG image (*.jpg *.jpeg);;'
         'TIFF image (*.tif *.tiff);;'
         'GIF image (*.gif);;'
         'All files (*)')
     if with_qt5:  # the filter is passed as well
         fname = fname[0]
     if not fname:
         return
     try:
         p.export(fname, *args, **kwargs)
     except Exception:
         self.error_msg.showTraceback(
             '<b>Could not export the figures!</b>')
Exemplo n.º 12
0
 def _export_project(self, p, *args, **kwargs):
     fname = QFileDialog.getSaveFileName(
         self, 'Picture destination', os.getcwd(),
         'PDF files (*.pdf);;'
         'Postscript file (*.ps);;'
         'PNG image (*.png);;'
         'JPG image (*.jpg *.jpeg);;'
         'TIFF image (*.tif *.tiff);;'
         'GIF image (*.gif);;'
         'All files (*)'
         )
     if not fname:
         return
     try:
         p.export(fname, *args, **kwargs)
     except:
         self.error_msg.showTraceback(
             '<b>Could not export the figures!</b>')
Exemplo n.º 13
0
 def _save_project(self, p, new_fname=False, *args, **kwargs):
     if new_fname or 'project_file' not in p.attrs:
         fname = QFileDialog.getSaveFileName(
             self, 'Project destination', os.getcwd(),
             'Pickle files (*.pkl);;'
             'All files (*)'
             )
         if not fname:
             return
     else:
         fname = p.attrs['project_file']
     try:
         p.save_project(fname, *args, **kwargs)
     except:
         self.error_msg.showTraceback('<b>Could not save the project!</b>')
     else:
         p.attrs['project_file'] = fname
         if p.is_main:
             self.update_project_action(p.num)
Exemplo n.º 14
0
 def _save_project(self, p, new_fname=False, *args, **kwargs):
     if new_fname or 'project_file' not in p.attrs:
         fname = QFileDialog.getSaveFileName(
             self, 'Project destination', os.getcwd(),
             'Pickle files (*.pkl);;'
             'All files (*)')
         if with_qt5:  # the filter is passed as well
             fname = fname[0]
         if not fname:
             return
     else:
         fname = p.attrs['project_file']
     try:
         p.save_project(fname, *args, **kwargs)
     except Exception:
         self.error_msg.showTraceback('<b>Could not save the project!</b>')
     else:
         p.attrs['project_file'] = fname
         if p.is_main:
             self.update_project_action(p.num)
Exemplo n.º 15
0
    def save_straditizer_as(self, fname=None):
        """Save the straditizer to a file

        Parameters
        ----------
        fname: str or ``None``
            If None, a QFileDialog is opened and the user has to provide a
            filename. The final action then depends on the ending of the
            chose file:

            ``'.pkl'``
                We save the straditizer with :meth:`pickle.dump`
            else
                We use the
                :meth:`straditize.straditizer.Straditizer.to_dataset` method
                and save the resulting dataset using the
                :meth:`xarray.Dataset.to_netcdf` method"""
        if fname is None or not isinstance(fname, six.string_types):
            fname = QFileDialog.getSaveFileName(
                self.straditizer_widgets, 'Straditizer file destination',
                self._start_directory,
                ('NetCDF files (*.nc *.nc4);;Pickle files (*.pkl);;'
                 'All files (*)'))
            if with_qt5:  # the filter is passed as well
                fname = fname[0]
        if not fname:
            return
        ending = os.path.splitext(fname)[1]
        self.straditizer.set_attr('saved', str(dt.datetime.now()))
        self.straditizer.set_attr('project_file', fname)
        if ending == '.pkl':
            self.straditizer.save(fname)
        else:
            ds = self.straditizer.to_dataset()
            # -- Compression with a level of 4. Requires netcdf4 engine
            comp = dict(zlib=True, complevel=4)
            encoding = {var: comp for var in ds.data_vars}

            ds.to_netcdf(fname, encoding=encoding, engine='netcdf4')
Exemplo n.º 16
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