Example #1
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     
     self.detector = "AIA"
     self.instrument = "AIA"
     self.observatory = "SDO"
     self.cmap = cm.get_cmap('sdoaia%d' % header.get('wavelnth'))
Example #2
0
    def __init__(self, data, header):
        BaseMap.__init__(self, header)
        
        # MDI sometimes has an "60" in seconds field
        datestr = header['date_obs']

        if datestr[17:19] == "60":
            datestr = datestr[:17] + "30" + datestr[19:]
            
        rsun = header.get('radius')
        
        # Solar radius in arc-seconds at 1 au
        # @TODO: use sunpy.sun instead
        radius_1au = 959.644
        
        # MDI images may have radius = 0.0
        if not rsun:
            dsun = constants.au
        else:
            scale = header.get("cdelt1")
            dsun = (radius_1au / (rsun * scale)) * constants.au
            
        # Determine measurement
        dpcobsr = header.get('dpc_obsr')
        meas = "magnetogram" if dpcobsr.find('Mag') != -1 else "continuum"
        
        self.date = parse_time(datestr)
        self.detector = "MDI"
        self.measurement = meas
        self.dsun = dsun
        self.name = "MDI %s" % meas
Example #3
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     self.detector = "SWAP"
     self.instrument = "SWAP"
     self.observatory = "PROBA2"
     self.name = "SWAP %s" % header.get('wavelnth')
     self.cmap = cm.get_cmap(name='sdoaia171')
Example #4
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     
     self.detector = "HMI"
     self.instrument = "HMI"
     self.measurement = header['content'].split(" ")[0].lower()
     self.observatory = "SDO"
     self.name = "HMI %s" % self.meas 
Example #5
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     
     datestr = "%sT%s" % (header.get('date_obs'), header.get('time_obs'))
     
     self.date = parse_time(datestr)
     self.measurement = "white-light"
     self.name = "LASCO %s" % header.get('detector')
Example #6
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     self.date = parse_time(header.get('date_obs'))
     self.detector = header.get('detector')
     self.instrument = "SECCHI"
     self.observatory = header.get('obsrvtry')
     self.measurement = "white-light"
     self.name = "SECCHI %s" % header.get('detector')
Example #7
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     self.date = parse_time(header.get('date_obs'))
     self.detector = "EUVI"
     self.instrument = "SECCHI"
     self.observatory = header.get('obsrvtry')
     self.name = "EUVI %s" % self.meas
     self.cmap = cm.get_cmap('sohoeit%d' % header.get('wavelnth'))
Example #8
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     
     self.date = parse_time(header.get('date_obs'))
     self.detector = header.get('telescop')
     self.instrument = header.get('telescop')
     self.measurement = [header.get('energy_l'), header.get('energy_h')]
     self.name = "RHESSI %d - %d keV" % (header.get('energy_l'), 
                                         header.get('energy_h'))
     self.cmap = cm.get_cmap('rhessi')
     self.exposure_time = (parse_time(header.get('date_end')) - 
                           parse_time(header.get('date_obs'))).seconds
Example #9
0
 def __init__(self, data, header):
     BaseMap.__init__(self, header)
     
     # Solar radius in arc-seconds at 1 au
     # @TODO: use sunpy.sun instead
     radius_1au = 959.644
     
     scale = header.get("cdelt1")
     
     self.date = parse_time(header.get('date_obs'))
     self.detector = "EIT"
     self.dsun = (radius_1au / (self.rsun_arcseconds * scale)) * constants.au
     self.name = "EIT %s" % header.get('wavelnth')
     self.cmap = cm.get_cmap('sohoeit%d' % header.get('wavelnth'))
Example #10
0
 def add_map(self, input_, zorder=None, alpha=1):
     """Adds a map to the CompositeMap
     
     Parameters
     ----------
     input_ : {sunpy.map, string}
         Map instance or filepath to map to be added
     zorder : int
         The index to use when determining where the map should lie along
         the z-axis; maps with higher z-orders appear above maps with lower
         z-orders.
     alpha : float
         Opacity at which the map should be displayed. An alpha value of 0
         results in a fully transparent image while an alpha value of 1
         results in a fully opaque image. Values between result in semi-
         transparent images.
     """
     if zorder is None:
         zorder = max([m.zorder for m in self._maps]) + 10
     
     m = BaseMap.read(input_)
     m.zorder = zorder
     m.alpha = alpha
     
     self._maps.append(m)
Example #11
0
def Map(filepath):
    """Creates a map from specified file.
    
    .. deprecated:: 0.1
        Use `make_map` instead.
    
    Parameters
    ----------
    filepath : string
        Filepath to a FITs or JPEG 2000 file
    
    Returns
    -------
    out : Map
        Creates a map instance using the specific file and return it
    """
    import warnings
    warnings.warn("sunpy.Map is deprecated: use sunpy.make_map instead.", DeprecationWarning)
    
    if isinstance(filepath, basestring):
        return BaseMap.read(filepath)
    else:
        raise InvalidMapInput("Invalid input for make_map. Please specify "
                              "one or more filepaths, Maps, directories, "
                              "or wildcard expressions.")
Example #12
0
    def __new__(cls, *args, **kwargs):
        """Creates a new Map instance"""
        
        maps = []
        data = []
        headers = []
    
        # convert input to maps
        for item in args:
            if isinstance(item, BaseMap):
                maps.append(item)
            else:
                maps.append(BaseMap.read(item))

        # sort data
        sortby = kwargs.get("sortby", "date")
        if hasattr(cls, '_sort_by_%s' % sortby):
            maps.sort(key=getattr(cls, '_sort_by_%s' % sortby)())

        # create data cube
        for map_ in maps:
            data.append(np.array(map_))
            headers.append(map_.header)

        obj = np.asarray(data).view(cls)
        obj._headers = headers

        return obj
Example #13
0
    def __new__(cls, input_, sortby="date"):
        """Creates a new Map instance"""
        
        # Directory of files
        if isinstance(input_, basestring):
            filepaths = []
            fits_arr = []
            data = []
            headers = []

            # directory
            if os.path.isdir(input_):
                for filename in os.listdir(input_):
                    filepaths.append(os.path.join(input_, filename))

            # glob string
            else:
                from glob import glob
                filepaths = glob(input_)
                
            # read in files
            for filepath in filepaths:
                fits = pyfits.open(filepath)
                
                # append normalized header tags for use during sorting
                found_header_match = False
                
                for subcls in BaseMap.__subclasses__(): #pylint: disable=E1101
                    if subcls.is_datasource_for(fits[0].header):
                        found_header_match = True
                        fits.norm_header = subcls.get_properties(fits[0].header)
                if not found_header_match:
                    raise UnrecognizedDataSouceError

                fits_arr.append(fits)

            # sort data
            if sortby and hasattr(cls, '_sort_by_%s' % sortby):
                fits_arr.sort(key=getattr(cls, '_sort_by_%s' % sortby)())

            # create data cube
            for fits in fits_arr:
                data.append(fits[0].data)
                headers.append(fits[0].header)

            obj = np.asarray(data).view(cls)
            obj._headers = headers

        # List of data or filepaths
        elif isinstance(input_, list):
            obj = np.asarray(input_).view(cls)

        # ndarray
        elif isinstance(input_, np.ndarray):
            obj = input_

        return obj
Example #14
0
 def __getitem__(self, key):
     """Overiding indexing operation"""
     if self.ndim is 3 and isinstance(key, int):
         data = np.ndarray.__getitem__(self, key)
         header = self._headers[key]
         for cls in BaseMap.__subclasses__():
             if cls.is_datasource_for(header):
                 return cls(data, header)
         raise UnrecognizedDataSouceError
     else:
         return np.ndarray.__getitem__(self, key)
Example #15
0
def Map(input_):
    """Map class factory
    
    Attempts to determine the type of data associated with input and returns
    an instance of either the generic BaseMap class or a subclass of BaseMap
    such as AIAMap, EUVIMap, etc.
    
    Parameters
    ----------
    input_ : filepath, data array
        The data source used to create the map object. This can be either a
        filepath to an image, a 2d list, or an ndarray.
        
    Returns
    -------
    out : BaseMap
        Returns a BaseMap or BaseMap subclass instance
        
    Notes
    -----
    PyFITS
        [1] Due to the way PyFITS works with images the header dictionary may
        differ depending on whether is accessed before or after the fits[0].data
        is requested. If the header is read before the data then the original
        header will be returned. If the header is read after the data has been
        accessed then the data will have been scaled and a modified header
        reflecting these changes will be returned: BITPIX may differ and
        BSCALE and B_ZERO may be dropped in the modified version.
        
        [2] The verify('fix') call attempts to handle violations of the FITS
        standard. For example, nan values will be converted to "nan" strings.
        Attempting to cast a pyfits header to a dictionary while it contains
        invalid header tags will result in an error so verifying it early on
        makes the header easier to work with later.
    References
    ----------
    | http://stackoverflow.com/questions/456672/class-factory-in-python
    | http://stsdas.stsci.edu/download/wikidocs/The_PyFITS_Handbook.pdf
    """
    if isinstance(input_, basestring):
        fits = pyfits.open(input_)
        fits.verify('silentfix')        
        data = fits[0].data
        header = fits[0].header

        for cls in BaseMap.__subclasses__():
            if cls.is_datasource_for(header):
                return cls(data, header)
        raise UnrecognizedDataSouceError

    else:
        return BaseMap(input_)
Example #16
0
 def get_properties(cls, header):
     """Parses EUVI image header"""
     properties = BaseMap.get_properties(header)
     
     properties.update({
         "date": parse_time(header.get('date_obs')),
         "detector": "EUVI",
         "instrument": "SECCHI",
         "observatory": header.get('obsrvtry'),
         "cmap": cm.get_cmap('sohoeit%d' % header.get('wavelnth')),
         "nickname": "EUVI-" + header.get('obsrvtry')[-1]
     })
     return properties
Example #17
0
 def get_properties(cls, header):
     """Parses SWAP image header"""
     properties = BaseMap.get_properties(header)
     
     properties.update({
         "detector": "SWAP",
         "instrument": "SWAP",
         "observatory": "PROBA2",
         "name": "SWAP %s" % header.get('wavelnth'),
         "nickname": "SWAP",
         "cmap": cm.get_cmap(name='sdoaia171')
     })
     return properties
Example #18
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     # Note: Trailing "Z" in date was dropped on 2010/12/07        
     properties = BaseMap.get_properties()
     properties.update({
         'date': util.anytim(header['date-obs'][0:22]),
         'det': "AIA",
         'inst': "AIA",
         'meas': header['wavelnth'],
         'obs': "SDO",
         'name': "AIA %s" % header['wavelnth'],
         'cmap': cm.get_cmap(name = 'sdoaia' + str(header['wavelnth']))
     })
     return properties
Example #19
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     properties = BaseMap.get_properties()
     properties.update({
         'date': util.anytim(header.get('date_obs')),
         'det': header.get('telescop'),
         'inst': header.get('telescop'),
         'meas': [header.get('energy_l'), header.get('energy_h')],
         'obs': header.get('telescop'),
         'name': "RHESSI " + str(header.get('energy_l')) + '-' + str(header.get('energy_h')) + ' keV',
         'cmap': cm.get_cmap(name = 'rhessi'),
         # 'norm': mpl.colors.Normalize(vmin=cls.min(), vmax=cls.max())
     })
     return properties
Example #20
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
     
     properties = BaseMap.get_properties()
     properties.update({
         "date": datetime.strptime(header['date_obs'], date_format),
         "det": "EIT",
         "inst": "EIT",
         "meas": header['wavelnth'],
         "obs": "SOHO",
         "name": "EIT %s" % header['wavelnth'],
         "r_sun": header['solar_r']
     })
     return properties
Example #21
0
    def get_properties(cls, header):
        """Returns the default and normalized values to use for the Map"""
        datestr = "%sT%s" % (header['date_obs'], header['time_obs'])

        properties = BaseMap.get_properties()
        properties.update({
            "date": util.anytim(datestr),
            "det": header.get('detector'),
            "inst": "LASCO",
            "meas": header.get('wavelnth'),
            "obs": "SOHO",
            "name": "LASCO %s" % header.get('detector'),
            "exptime": header.get("exptime"),
        })
        return properties
Example #22
0
    def get_properties(cls, header):
        """Returns the default and normalized values to use for the Map"""
        datestr = "%sT%s" % (header['date_obs'], header['time_obs'])

        properties = BaseMap.get_properties()
        properties.update({
            "date": datetime.strptime(datestr, "%Y/%m/%dT%H:%M:%S.%f"),
            "det": header['detector'],
            "inst": "LASCO",
            "meas": header['wavelnth'],
            "obs": "SOHO",
            "name": "LASCO %s" % header['detector'],
            "r_sun": None
        })
        return properties
Example #23
0
    def get_properties(cls, header):
        """Returns the default and normalized values to use for the Map"""
        properties = BaseMap.get_properties()
        date_format = "%Y-%m-%dT%H:%M:%S.%f"

        properties.update({
            "date": datetime.strptime(header['date_obs'], date_format),
            "det": header['detector'],
            "inst": "SECCHI",
            "meas": header['wavelnth'],
            "obs": header['obsrvtry'],
            "name": "SECCHI %s" % header['detector'],
            "r_sun": header['rsun']
        })
        return properties
Example #24
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     #date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
     
     properties = BaseMap.get_properties()
     properties.update({
         "date": util.anytim(header.get('date_obs')),
         "det": "EIT",
         "inst": "EIT",
         "meas": header.get('wavelnth'),
         "obs": "SOHO",
         "name": "EIT %s" % header.get('wavelnth'),
         "exptime": header.get('exptime'),
         'cmap': cm.get_cmap(name='sohoeit' + str(header.get('wavelnth'))),
     })
     return properties
Example #25
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     # Note: Trailing "Z" in date was dropped on 2010/12/07    
     meas = header['content'].split(" ")[0].lower()
     
     properties = BaseMap.get_properties()
     properties.update({
         "date": util.anytim(header.get('date-obs')),
         "det": "HMI",
         "inst": "HMI",
         "meas": meas,
         "obs": "SDO",
         "name": "HMI %s" % meas,
         "exptime": header.get('exptime')
     })
     return properties
Example #26
0
 def get_properties(cls, header):
     """Returns the default and normalized values to use for the Map"""
     properties = BaseMap.get_properties()
     properties.update({
         'date': util.anytim(header.get('date_obs')),
         'det': header.get('telescop'),
         'inst': header.get('telescop'),
         'meas': [header.get('energy_l'), header.get('energy_h')],
         'obs': header.get('telescop'),
         'name': "RHESSI " + str(header.get('energy_l')) + '-' + 
                 str(header.get('energy_h')) + ' keV',
         'cmap': cm.get_cmap(name = 'rhessi'),
         'exptime': (util.anytim(header.get('date_end')) - 
                     util.anytim(header.get('date_obs'))).seconds
     })
     return properties
Example #27
0
 def get_properties(cls, header):
     """Parses COR image header"""
     properties = BaseMap.get_properties(header)
     
     # @TODO: Deal with invalid values for exptime. E.g. STEREO-B COR2
     # on 2012/03/20 has -1 for some images.
     properties.update({
         "date": parse_time(header.get('date_obs')),
         "detector": header.get('detector'),
         "instrument": "SECCHI",
         "observatory": header.get('obsrvtry'),
         "measurement": "white-light",
         "name": "SECCHI %s" % header.get('detector'),
         "nickname": "%s-%s" % (header.get('detector'), 
                                header.get('obsrvtry')[-1])
     })
     return properties
Example #28
0
    def __init__(self, *args):
        self._maps = []
        
        # Default alpha and zorder values
        alphas = [1] * len(args)
        zorders = range(0, 10 * len(args), 10) 
        
        # Parse input Maps/filepaths        
        for i, item in enumerate(args):
            # Parse map
            if isinstance(item, BaseMap):
                m = item
            else:
                m = BaseMap.read(item)
            
            # Set z-order and alpha values for the map
            m.zorder = zorders[i]
            m.alpha = alphas[i]

            # Add map
            self._maps.append(m)
Example #29
0
    def get_properties(cls, header):
        """Returns the default and normalized values to use for the Map"""
        # MDI sometimes has an "60" in seconds field
        datestr = header['date_obs']

        if datestr[17:19] == "60":
            datestr = datestr[:17] + "30" + datestr[19:]
        
        # Determine measurement
        dpcobsr = header['dpc_obsr']
        meas = "magnetogram" if dpcobsr.find('Mag') != -1 else "continuum"
        
        properties = BaseMap.get_properties()        
        properties.update({
            "date": datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S.%fZ"),
            "det": "MDI",
            "inst": "MDI",
            "meas": meas,
            "obs": "SOHO",
            "name": "MDI %s" % meas,
            "r_sun": header['radius']
        })
        return properties
Example #30
0
def make_map(*args, **kwargs):
    """Processes one or more inputs and returns a Map, MapCube, or CompositeMap
    instance.
    
    Parameters
    ----------
    args : filepath(s), data array
        The data source used to create the map object. This can be either a
        filepath to an image, a 2d list, or an ndarray.
    type : {'composite' | 'cube'}
        Type of multimap to construct when passed more than one input. The
        default choice is a CompositeMap which is more lenient with respect
        to how similar the input data is.
        
    Returns
    -------
    out : Map, MapCube, CompositeMap
        Returns a  subclass instance
        
    Examples
    --------
    >>> import sunpy
    >>> sunpy.make_map("file.fts")
    >>> sunpy.make_map("file1.fts", "file2.fts",..)
    >>> sunpy.make_map(["file1.fts", "file2.fts",..])
    >>> sunpy.make_map("path/to/files/*.fts")
    >>> sunpy.make_map(Map)
    >>> sunpy.make_map(Map1, Map2,..)

    """
    # Single Map or wildcard string
    if len(args) == 1:
        # String
        if isinstance(args[0], basestring):
            # Wildcard string
            if args[0].find("*") != -1:
                import glob
                maps = glob.glob(args[0])
            # Directory (use all files)
            elif os.path.isdir(args[0]):
                maps = os.listdir(args[0])
                
            # Filepath
            else:
                return BaseMap.read(args[0])

        # Map/MapCube/CompositeMap
        elif (isinstance(args[0], BaseMap) or 
              isinstance(args[0], CompositeMap) or 
              isinstance(args[0], MapCube)):
            return args[0]
        
        # List of filepaths or Maps
        elif isinstance(args[0], list):
            maps = args[0]

        # Unrecognized input
        else:
            raise InvalidMapInput("Invalid input for make_map. Please specify "
                                  "one or more filepaths, Maps, directories, "
                                  "or wildcard expressions.")
    else:
        maps = args
        
    # Make sure we found some data
    if len(maps) is 0:
        raise NoMapsFound("Specified path contains no valid files.")
        
    mtype = kwargs.get("type", "composite")
        
    # MapCube
    if mtype == "cube":
        return MapCube(*maps)
    # CompositeMap (default)
    elif mtype == "composite":
        return CompositeMap(*maps)
    else:
        raise InvalidMapType("Invalid multi-map type specified. Please choose "
                             "between 'composite' or 'cube'.")