Ejemplo n.º 1
0
    def __init__(self, filename=None):
        if filename is None:
            filename = self.builtin_mat

        if _is_url(filename):
            self.filename = download_file(filename, cache=True)
        else:
            self.filename = filename

        mat = spio.loadmat(self.filename, matlab_compatible=True)

        # Pull out the information we need.
        # FIXME: No mapInfoDV nor commented stuff below in SourceForge version
        key = 'mapInfoDV'
        # key = 'map'
        self.n_dim = mat[key]['nDim'][0][0][0][0]
        self.Ymap = mat[key]['Ymap'][0][0][0][0]
        self.YmapMapping = self.Ymap['mapping']
        self.YmapMean = self.YmapMapping['mean'][0][0][0]
        self.YmapM = self.YmapMapping['M'][0][0]
        self.YmapMapped = self.Ymap['mapped']
        self.knn = mat[key]['knn'][0][0][0][0]
        self.knnGood = mat[key]['knnGood'][0][0][:, 0]
        self.mappedPeriods = mat[key]['periods'][0][0][0]
        self.mappedMes = mat[key]['mes'][0][0][0]
        self.nPsample = mat[key]['nPsample'][0][0][0][
            0]  # number to sample  # noqa: E501
        self.nPercentil = mat[key]['npercentilTM'][0][0][0][0]
        self.dymeans = mat[key]['dymean'][0][0][0]
        self.ntrfr = 2.0
        self.npts = 80.0
Ejemplo n.º 2
0
Archivo: core.py Proyecto: rtanmay/sbpy
    def from_builtin(cls, name):
        """Vega spectrum from a built-in `sbpy` source.

        Parameters
        ----------
        name : string
          The name of a Vega spectrum parameter set in
          `sbpy.spectroscopy.vega.sources`.

        """

        from astropy.utils.data import _is_url

        try:
            parameters = getattr(sources, name).copy()

            if not _is_url(parameters['filename']):
                # find in the module's location
                parameters['filename'] = get_pkg_data_filename(
                    os.path.join('data', parameters['filename']))

            vega = Vega.from_file(**parameters)
        except AttributeError:
            msg = 'Unknown Vega spectrum "{}".  Valid spectra:\n{}'.format(
                name, sources.available)
            raise ValueError(msg)

        return vega
Ejemplo n.º 3
0
    def from_builtin(cls, name):
        """Spectrum from a built-in `sbpy` source.

        Parameters
        ----------
        name : string
            The name of the spectrum.  See `show_builtin()` for
            available sources.

        """

        from astropy.utils.data import _is_url

        try:
            parameters = getattr(cls._sources, name).copy()
        except AttributeError:
            msg = 'Unknown spectrum "{}".  Valid spectra:\n'.format(
                name) + cls.show_builtin(print=False)
            raise UndefinedSourceError(msg)

        if not _is_url(parameters['filename']):
            # find in the module's location
            parameters['filename'] = get_pkg_data_filename(
                os.path.join('data', parameters['filename']))

        return cls.from_file(**parameters)
Ejemplo n.º 4
0
    def from_builtin(cls, name):
        """Solar spectrum from a built-in `sbpy` source.

        Parameters
        ----------
        name : string
          The name of a solar spectrum parameter set in
          `sbpy.spectroscopy.sun.sources`.

        """

        from astropy.utils.data import _is_url

        try:
            parameters = getattr(sources, name).copy()

            if not _is_url(parameters['filename']):
                # find in the module's location
                path = os.path.dirname(__file__)
                parameters['filename'] = os.sep.join(
                    (path, 'data', parameters['filename']))

            return Sun.from_file(**parameters)
        except AttributeError:
            msg = 'Unknown solar spectrum "{}".  Valid spectra:\n{}'.format(
                name, sources.available)
            raise ValueError(msg)
Ejemplo n.º 5
0
    def from_file(cls,
                  filename,
                  wave_unit=None,
                  flux_unit=None,
                  cache=True,
                  **kwargs):
        """Load the source spectrum from a file.

        NaNs are dropped.

        Parameters
        ----------
        filename : string
            The name of the file.  See
            `~synphot.SourceSpectrum.from_file` for details.

        wave_unit, flux_unit : str or `~astropy.units.Unit`, optional
            Wavelength and flux units in the file.

        cache : bool, optional
            If ``True``, cache the contents of URLs.

        **kwargs
            Passed to object initialization.

        """

        try:
            import synphot
        except ImportError:
            raise ImportError('synphot required for {}.'.format(cls.__name__))

        from astropy.utils.data import download_file, _is_url

        if filename.lower().endswith(('.fits', '.fit', '.fz')):
            read_spec = synphot.specio.read_fits_spec
        else:
            read_spec = synphot.specio.read_ascii_spec

        # URL cache because synphot.SourceSpectrum.from_file does not
        if _is_url(filename):
            fn = download_file(filename, cache=True)
        else:
            fn = filename

        spec = read_spec(fn, wave_unit=wave_unit, flux_unit=flux_unit)
        i = np.isfinite(spec[1] * spec[2])
        source = synphot.SourceSpectrum(synphot.Empirical1D,
                                        points=spec[1][i],
                                        lookup_table=spec[2][i],
                                        meta={'header': spec[0]})

        return cls(source, **kwargs)
Ejemplo n.º 6
0
    def from_file(cls, filename, wave_unit=None, flux_unit=None,
                  cache=True, **kwargs):
        """Load the source spectrum from a file.

        Parameters
        ----------
        filename : string
          The name of the file.  See
          `~synphot.SourceSpectrum.from_file` for details.

        wave_unit, flux_unit : str or `~astropy.units.core.Unit`, optional
          Wavelength and flux units.

        cache : bool, optional
          If `True`, cache the contents of URLs.

        **kwargs
          Passed to `Sun` initialization.

        """

        from astropy.utils.data import download_file
        from astropy.utils.data import _is_url
        import synphot
        from synphot.specio import read_fits_spec, read_ascii_spec

        # URL cache because synphot.SourceSpectrum.from_file does not
        if _is_url(filename):
            if filename.lower().endswith(('.fits', '.fit')):
                read_spec = read_fits_spec
            else:
                read_spec = read_ascii_spec

            fn = download_file(filename, cache=True)
            spec = read_spec(fn, wave_unit=wave_unit, flux_unit=flux_unit)
            source = synphot.SourceSpectrum(
                synphot.Empirical1D, points=spec[1], lookup_table=spec[2],
                meta={'header': spec[0]})
        else:
            source = synphot.SourceSpectrum.from_file(
                filename, wave_unit=wave_unit, flux_unit=flux_unit)

        return cls(source, **kwargs)
Ejemplo n.º 7
0
    def __init__(self,
                 fileobj=None,
                 mode=None,
                 memmap=None,
                 overwrite=False,
                 cache=True):
        self.strict_memmap = bool(memmap)
        memmap = True if memmap is None else memmap

        self._file = None
        self.closed = False
        self.binary = True
        self.mode = mode
        self.memmap = memmap
        self.compression = None
        self.readonly = False
        self.writeonly = False

        # Should the object be closed on error: see
        # https://github.com/astropy/astropy/issues/6168
        self.close_on_error = False

        # Holds mmap instance for files that use mmap
        self._mmap = None

        if fileobj is None:
            self.simulateonly = True
            return
        else:
            self.simulateonly = False
            # If fileobj is of type pathlib.Path
            if isinstance(fileobj, pathlib.Path):
                fileobj = str(fileobj)

        if mode is not None and mode not in IO_FITS_MODES:
            raise ValueError(f"Mode '{mode}' not recognized")
        if isfile(fileobj):
            objmode = _normalize_fits_mode(fileobj_mode(fileobj))
            if mode is not None and mode != objmode:
                raise ValueError(
                    "Requested FITS mode '{}' not compatible with open file "
                    "handle mode '{}'".format(mode, objmode))
            mode = objmode
        if mode is None:
            mode = 'readonly'

        # Handle raw URLs
        if (isinstance(fileobj, (str, bytes))
                and mode not in ('ostream', 'append', 'update')
                and _is_url(fileobj)):
            self.name = download_file(fileobj, cache=cache)
        # Handle responses from URL requests that have already been opened
        elif isinstance(fileobj, http.client.HTTPResponse):
            if mode in ('ostream', 'append', 'update'):
                raise ValueError(f"Mode {mode} not supported for HTTPResponse")
            fileobj = io.BytesIO(fileobj.read())
        else:
            self.name = fileobj_name(fileobj)

        self.mode = mode

        # Underlying fileobj is a file-like object, but an actual file object
        self.file_like = False

        # Initialize the internal self._file object
        if isfile(fileobj):
            self._open_fileobj(fileobj, mode, overwrite)
        elif isinstance(fileobj, (str, bytes)):
            self._open_filename(fileobj, mode, overwrite)
        else:
            self._open_filelike(fileobj, mode, overwrite)

        self.fileobj_mode = fileobj_mode(self._file)

        if isinstance(fileobj, gzip.GzipFile):
            self.compression = 'gzip'
        elif isinstance(fileobj, zipfile.ZipFile):
            # Reading from zip files is supported but not writing (yet)
            self.compression = 'zip'
        elif _is_bz2file(fileobj):
            self.compression = 'bzip2'

        if (mode in ('readonly', 'copyonwrite', 'denywrite')
                or (self.compression and mode == 'update')):
            self.readonly = True
        elif (mode == 'ostream' or (self.compression and mode == 'append')):
            self.writeonly = True

        # For 'ab+' mode, the pointer is at the end after the open in
        # Linux, but is at the beginning in Solaris.
        if (mode == 'ostream' or self.compression
                or not hasattr(self._file, 'seek')):
            # For output stream start with a truncated file.
            # For compressed files we can't really guess at the size
            self.size = 0
        else:
            pos = self._file.tell()
            self._file.seek(0, 2)
            self.size = self._file.tell()
            self._file.seek(pos)

        if self.memmap:
            if not isfile(self._file):
                self.memmap = False
            elif not self.readonly and not self._mmap_available:
                # Test mmap.flush--see
                # https://github.com/astropy/astropy/issues/968
                self.memmap = False
Ejemplo n.º 8
0
    def __init__(self,
                 fileobj=None,
                 mode=None,
                 memmap=None,
                 overwrite=False,
                 cache=True):
        self.strict_memmap = bool(memmap)
        memmap = True if memmap is None else memmap

        if fileobj is None:
            self._file = None
            self.closed = False
            self.binary = True
            self.mode = mode
            self.memmap = memmap
            self.compression = None
            self.readonly = False
            self.writeonly = False
            self.simulateonly = True
            self.close_on_error = False
            return
        else:
            self.simulateonly = False
            # If fileobj is of type pathlib.Path
            if isinstance(fileobj, pathlib.Path):
                fileobj = str(fileobj)
            elif isinstance(fileobj, bytes):
                # Using bytes as filename is tricky, it's deprecated for Windows
                # in Python 3.5 (because it could lead to false-positives) but
                # was fixed and un-deprecated in Python 3.6.
                # However it requires that the bytes object is encoded with the
                # file system encoding.
                # Probably better to error out and ask for a str object instead.
                # TODO: This could be revised when Python 3.5 support is dropped
                # See also: https://github.com/astropy/astropy/issues/6789
                raise TypeError("names should be `str` not `bytes`.")

        # Holds mmap instance for files that use mmap
        self._mmap = None

        if mode is not None and mode not in IO_FITS_MODES:
            raise ValueError(f"Mode '{mode}' not recognized")
        if isfile(fileobj):
            objmode = _normalize_fits_mode(fileobj_mode(fileobj))
            if mode is not None and mode != objmode:
                raise ValueError(
                    "Requested FITS mode '{}' not compatible with open file "
                    "handle mode '{}'".format(mode, objmode))
            mode = objmode
        if mode is None:
            mode = 'readonly'

        # Handle raw URLs
        if (isinstance(fileobj, str)
                and mode not in ('ostream', 'append', 'update')
                and _is_url(fileobj)):
            self.name = download_file(fileobj, cache=cache)
        # Handle responses from URL requests that have already been opened
        elif isinstance(fileobj, http.client.HTTPResponse):
            if mode in ('ostream', 'append', 'update'):
                raise ValueError(f"Mode {mode} not supported for HTTPResponse")
            fileobj = io.BytesIO(fileobj.read())
        else:
            self.name = fileobj_name(fileobj)

        self.closed = False
        self.binary = True
        self.mode = mode
        self.memmap = memmap

        # Underlying fileobj is a file-like object, but an actual file object
        self.file_like = False

        # Should the object be closed on error: see
        # https://github.com/astropy/astropy/issues/6168
        self.close_on_error = False

        # More defaults to be adjusted below as necessary
        self.compression = None
        self.readonly = False
        self.writeonly = False

        # Initialize the internal self._file object
        if isfile(fileobj):
            self._open_fileobj(fileobj, mode, overwrite)
        elif isinstance(fileobj, str):
            self._open_filename(fileobj, mode, overwrite)
        else:
            self._open_filelike(fileobj, mode, overwrite)

        self.fileobj_mode = fileobj_mode(self._file)

        if isinstance(fileobj, gzip.GzipFile):
            self.compression = 'gzip'
        elif isinstance(fileobj, zipfile.ZipFile):
            # Reading from zip files is supported but not writing (yet)
            self.compression = 'zip'
        elif isinstance(fileobj, bz2.BZ2File):
            self.compression = 'bzip2'

        if (mode in ('readonly', 'copyonwrite', 'denywrite')
                or (self.compression and mode == 'update')):
            self.readonly = True
        elif (mode == 'ostream' or (self.compression and mode == 'append')):
            self.writeonly = True

        # For 'ab+' mode, the pointer is at the end after the open in
        # Linux, but is at the beginning in Solaris.
        if (mode == 'ostream' or self.compression
                or not hasattr(self._file, 'seek')):
            # For output stream start with a truncated file.
            # For compressed files we can't really guess at the size
            self.size = 0
        else:
            pos = self._file.tell()
            self._file.seek(0, 2)
            self.size = self._file.tell()
            self._file.seek(pos)

        if self.memmap:
            if not isfile(self._file):
                self.memmap = False
            elif not self.readonly and not self._mmap_available:
                # Test mmap.flush--see
                # https://github.com/astropy/astropy/issues/968
                self.memmap = False