Exemple #1
0
    def _read_file(fname, **kwargs):
        """
        Reading a file with `sunpy.io` for automatic source detection.

        Parameters
        ----------
        fname : `str`
            The file path to parse.

        Returns
        -------
        parsed : `bool`
            `True` if file has been read.
        pairs : `list` or `str`
            List of ``(data, header)`` pairs if ``parsed`` is `True`,  ``fname`` if ``parsed`` is `False`.
            `False` if the file is not supported or incorrect.
        """
        if 'source' not in kwargs.keys() or not kwargs['source']:
            try:
                pairs = read_file(fname, **kwargs)

                new_pairs = []
                for pair in pairs:
                    filedata, filemeta = pair
                    if isinstance(filemeta, FileHeader):
                        data = filedata
                        meta = MetaDict(filemeta)
                        new_pairs.append(HDPair(data, meta))
                return True, new_pairs
            except UnrecognizedFileTypeError:
                return False, fname
        else:
            return False, fname
Exemple #2
0
    def _read_file(self, fname, **kwargs):
        """
        Read in a file name and return the list of (data, meta) pairs in that file.
        """
        # File gets read here. This needs to be generic enough to seamlessly
        # call a fits file or a jpeg2k file, etc
        # NOTE: use os.fspath so that fname can be either a str or pathlib.Path
        # This can be removed once read_file supports pathlib.Path
        log.debug(f'Reading {fname}')
        try:
            pairs = read_file(os.fspath(fname), **kwargs)
        except Exception as e:
            msg = f"Failed to read {fname}."
            raise IOError(msg) from e

        new_pairs = []
        for pair in pairs:
            filedata, filemeta = pair
            assert isinstance(filemeta, FileHeader)
            # This tests that the data is more than 1D
            if len(np.shape(filedata)) > 1:
                data = filedata
                meta = MetaDict(filemeta)
                new_pairs.append((data, meta))

        if not new_pairs:
            raise NoMapsInFileError(
                f"Found no HDUs with >= 2D data in '{fname}'.")

        return new_pairs
Exemple #3
0
    def meta(self, dfile, fname):
        data, header = read_file(dfile[0])[0]
        # Add the missing meta information to the header
        header['CUNIT1'] = 'arcsec'
        header['CUNIT2'] = 'arcsec'

        ax = sunpy.map.Map(data, header)
        fig = plt.figure()
        ax.plot()

        instr = str(header['TELESCOP'] + "-" + header['INSTRUME'] + "-" +
                    header['DETECTOR'])
        date = str(header['DATE-OBS'])
        time = str(header['TIME-OBS'])
        filter = str(header['FILTER'])
        ylabel = str(header['CTYPE2'])
        xlabel = str(header['CTYPE1'])

        img_name = fname.split(".")[0] + ".png"
        plt.savefig(img_name)

        write(img_name, instr, date, time, xlabel, ylabel, "arcsec", "arcsec",
              filter)

        plt.close()
    def _read_file(fname, **kwargs):
        """
        Reading a file with `sunpy.io` for automatic source detection.

        Parameters
        ----------
        fname : `str`
            The file path to parse.

        Returns
        -------
        parsed : `bool`
            `True` if file has been read.
        pairs : `list` or `str`
            List of ``(data, header)`` pairs if ``parsed`` is `True`,  ``fname`` if ``parsed`` is `False`.
            `False` if the file is not supported or incorrect.
        """
        if 'source' not in kwargs.keys() or not kwargs['source']:
            try:
                pairs = read_file(fname, **kwargs)

                new_pairs = []
                for pair in pairs:
                    filedata, filemeta = pair
                    if isinstance(filemeta, FileHeader):
                        data = filedata
                        meta = MetaDict(filemeta)
                        new_pairs.append(HDPair(data, meta))
                return True, new_pairs
            except UnrecognizedFileTypeError:
                return False, fname
        else:
            return False, fname
Exemple #5
0
    def _read_file(self, fname, **kwargs):
        """ Read in a file name and return the list of (data, meta) pairs in
            that file. """

        # File gets read here.  This needs to be generic enough to seamlessly
        # call a fits file or a jpeg2k file, etc
        pairs = read_file(fname, **kwargs)

        new_pairs = []
        for pair in pairs:
            filedata, filemeta = pair
            assert isinstance(filemeta, FileHeader)
            # This tests that the data is more than 1D
            if len(np.shape(filedata)) > 1:
                data = filedata
                meta = MetaDict(filemeta)
                new_pairs.append((data, meta))
        return new_pairs
Exemple #6
0
    def _read_file(self, fname, **kwargs):
        """ Read in a file name and return the list of (data, meta) pairs in
            that file. """

        # File gets read here.  This needs to be generic enough to seamlessly
        #call a fits file or a jpeg2k file, etc
        pairs = read_file(fname, **kwargs)

        new_pairs = []
        for pair in pairs:
            filedata, filemeta = pair
            assert isinstance(filemeta, FileHeader)
            #This tests that the data is more than 1D
            if len(np.shape(filedata)) > 1:
                data = filedata
                meta = MapMeta(filemeta)
                new_pairs.append((data, meta))
        return new_pairs
Exemple #7
0
    def _read_file(self, fname, **kwargs):
        """ Read in a file name and return the list of (data, meta) pairs in
            that file. """

        # File gets read here.  This needs to be generic enough to seamlessly
        # call a fits file or a jpeg2k file, etc
        # NOTE: use os.fspath so that fname can be either a str or pathlib.Path
        # This can be removed once read_file supports pathlib.Path
        log.debug(f'Reading {fname}')
        pairs = read_file(os.fspath(fname), **kwargs)

        new_pairs = []
        for pair in pairs:
            filedata, filemeta = pair
            assert isinstance(filemeta, FileHeader)
            # This tests that the data is more than 1D
            if len(np.shape(filedata)) > 1:
                data = filedata
                meta = MetaDict(filemeta)
                new_pairs.append((data, meta))
        return new_pairs
Exemple #8
0
    def _read_file(fname, **kwargs):
        """
        Reading a file with `sunpy.io` for automatic source detection.

        Parameters
        ----------
        fname : `str`
            The file path to parse.

        Returns
        -------
        pairs : `list` or `str`
            List of ``(data, header)`` pairs or ``fname`` if the file is not supported or incorrect.
        """
        if 'source' not in kwargs.keys() or not kwargs['source']:
            try:
                if detect_filetype(fname) == 'cdf':
                    # Put import here to ensure there is no import dependency
                    # on cdflib for TimeSeries
                    from sunpy.io.cdf import read_cdf
                    return read_cdf(os.fspath(fname), **kwargs)
            except UnrecognizedFileTypeError:
                pass

            try:
                pairs = read_file(os.fspath(fname), **kwargs)

                new_pairs = []
                for pair in pairs:
                    filedata, filemeta = pair
                    if isinstance(filemeta, FileHeader):
                        data = filedata
                        meta = MetaDict(filemeta)
                        new_pairs.append(HDPair(data, meta))
                return [new_pairs]
            except UnrecognizedFileTypeError:
                return [fname]
        else:
            return [fname]
Exemple #9
0
    def _read_file(self, fname, **kwargs):
        """
        Test reading a file with sunpy.io for automatic source detection.

        Parameters
        ----------

        fname : filename

        kwargs

        Returns
        -------

        parsed :  bool
            True if file has been reading

        pairs : list or string
            List of (data, header) pairs if ``parsed`` is ``True`` or ``fname``
            if ``False``
        """
        if 'source' not in kwargs.keys() or not kwargs['source']:
            try:
                pairs = read_file(fname, **kwargs)

                new_pairs = []
                for pair in pairs:
                    filedata, filemeta = pair
                    if isinstance(filemeta, FileHeader):
                        data = filedata
                        meta = MetaDict(filemeta)
                        new_pairs.append(HDPair(data, meta))
                return True, new_pairs
            except UnrecognizedFileTypeError:
                return False, fname
        else:
            return False, fname
Exemple #10
0
    def _read_file(self, fname, **kwargs):
        """
        Test reading a file with sunpy.io for automatic source detection.

        Parameters
        ----------

        fname : filename

        kwargs

        Returns
        -------

        parsed :  bool
            True if file has been reading

        pairs : list or string
            List of (data, header) pairs if ``parsed`` is ``True`` or ``fname``
            if ``False``
        """
        if 'source' not in kwargs.keys() or not kwargs['source']:
            try:
                pairs = read_file(fname, **kwargs)

                new_pairs = []
                for pair in pairs:
                    filedata, filemeta = pair
                    if isinstance(filemeta, FileHeader):
                        data = filedata
                        meta = MetaDict(filemeta)
                        new_pairs.append(HDPair(data, meta))
                return True, new_pairs
            except UnrecognizedFileTypeError:
                return False, fname
        else:
            return False, fname
Exemple #11
0
result = Fido.search(timerange, instrument)

###############################################################################
# Let's inspect the result
print(result)

###############################################################################
# The following shows how to download the results. If we
# don't provide a path it will download the file into the sunpy data directory.
# The output provides the path of the downloaded files.
downloaded_files = Fido.fetch(result)
print(downloaded_files)

###############################################################################
# The downloaded file lacks the correct meta. We want to open the file and
# access both the data and the header information.
data, header = read_file(downloaded_files[0])[0]

# Add the missing meta information to the header
header['CUNIT1'] = 'arcsec'
header['CUNIT2'] = 'arcsec'

###############################################################################
# With this fix we can load it into a map and plot the results.
# Please note that there is no plot displayed below as this example is skipped
# due to timeouts that can occur when you try to download LASCO C3 data.
lascomap = sunpy.map.Map(data, header)
fig = plt.figure()
lascomap.plot()
plt.show()
result = Fido.search(timerange, instrument)

# ``result`` contains the return from the online search.
# In this case, we have found 4 files that correspond to our search parameters.
print(result)

###############################################################################
# The next step is to download the search results and `Fido.fetch` will be used.
# We will pass in the ``result`` and ``downloaded_files`` will contain
# a list of the location of each of the downloaded files.

downloaded_files = Fido.fetch(result)
print(downloaded_files)

###############################################################################
# Finally we can pass in the first file we downloaded into `sunpy.map.Map`
# to create a SunPy Map object which allows us to easily plot the image.
# However, there is a problem here. The downloaded file lacks the correct meta
# information needed to create a `sunpy.map.Map`.

# We want to open the file and access both the data and the header information.
data, header = read_file(downloaded_files[0])[0]

# Add the missing meta information to the header
header['CUNIT1'] = 'arcsec'
header['CUNIT2'] = 'arcsec'

# Now we can pass in the data and header directly into `sunpy.map.Map`
lascomap = sunpy.map.Map(data, header)
lascomap.peek()
# The three images we see here are a continuum image (like the intensitygram we plotted at the start) of the photosphere, a map of the photosphere's magnetic field, and a map of the solar surface velocity.
# We had to rotate these images to align them with AIA ones because the two instruments are orientated differently on the spacecraft.

## Solar Corona

# We can also use SunPy to look at pictures of the solar corona.
# The SOHO telescope has three detectors (C1,C2,C3) on its LASCO instrument which image the corona in different wavelengths and distances from the photosphere.
# Let's get an image from the LASCO C1 detector:

coronaSOHO = Fido.search(a.Time('2000/02/27 07:42', '2000/02/27 07:43'), a.Instrument('LASCO'), a.Detector('C3'))
# I is a good idea to print this search before attempting to download it
# This will help you check that you're not downloading tons of files or no files

coronaSOHOdata = Fido.fetch(coronaSOHO[0],path="./lascoData/")
data, header = read_file(coronaSOHOdata[0])[0]

header['CUNIT1'] = 'arcsec'
header['CUNIT2'] = 'arcsec'

coronamap = sunpy.map.Map(data, header)
fig = plt.figure(4)
axSOHO = plt.subplot(111, projection=coronamap)
axSOHO.set_title("LASCO C3")
lasco = coronamap.plot(annotate=False, norm=colors.LogNorm(), clip_interval=(25.0, 99.5)*u.percent)
# lasco.set_clim(0,8000)
axSOHO.set_axis_off()
plt.colorbar()
plt.show()

# The black line in some of the images you see from LASCO are from the arm that holds a disc which blocks out the light from the solar disk.