示例#1
0
    def __call__(self, *args, **kwargs):
        """ Method for running the factory. Takes arbitrary arguments and
        keyword arguments and passes them to a sequence of pre-registered types
        to determine which is the correct Map-type to build.

        Arguments args and kwargs are passed through to the validation
        function and to the constructor for the final type.  For Map types,
        validation function must take a data-header pair as an argument.

        Parameters
        ----------

        composite : boolean, optional
            Indicates if collection of maps should be returned as a CompositeMap

        cube : boolean, optional
            Indicates if collection of maps should be returned as a MapCube

        sequence : boolean, optional
            Indicates if collection of maps should be returned as a MapSequence

        silence_errors : boolean, optional
            If set, ignore data-header pairs which cause an exception.

        Notes
        -----
        Extra keyword arguments are passed through to `sunpy.io.read_file` such
        as `memmap` for FITS files.
        """

        # Hack to get around Python 2.x not backporting PEP 3102.
        composite = kwargs.pop('composite', False)

        # MapCube Deprecation
        cube = kwargs.pop('cube', False)
        if cube:
            warnings.warn('MapCube is now deprecated and renamed MapSequence. ' +
                          'Please use the syntax Map(sequence=True) instead of Map(cube=True).',
                          SunpyDeprecationWarning, stacklevel=2)

        sequence = kwargs.pop('sequence', False)
        silence_errors = kwargs.pop('silence_errors', False)

        data_header_pairs, already_maps = self._parse_args(*args, **kwargs)

        new_maps = list()

        # Loop over each registered type and check to see if WidgetType
        # matches the arguments.  If it does, use that type.
        for pair in data_header_pairs:
            data, header = pair
            meta = MetaDict(header)

            try:
                new_map = self._check_registered_widgets(data, meta, **kwargs)
            except (NoMatchError, MultipleMatchError, ValidationFunctionError):
                if not silence_errors:
                    raise
            except:
                raise

            new_maps.append(new_map)

        new_maps += already_maps

        # If the list is meant to be a cube, instantiate a map cube
        if cube:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", category=SunpyDeprecationWarning)
                amapcube = MapCube(new_maps, **kwargs)
            return amapcube

        # If the list is meant to be a sequence, instantiate a map sequence
        if sequence:
            return MapSequence(new_maps, **kwargs)

        # If the list is meant to be a composite map, instantiate one
        if composite:
            return CompositeMap(new_maps, **kwargs)

        if len(new_maps) == 1:
            return new_maps[0]

        return new_maps
示例#2
0
    def __call__(self, *args, **kwargs):
        """ Method for running the factory. Takes arbitrary arguments and
        keyword arguments and passes them to a sequence of pre-registered types
        to determine which is the correct Map-type to build.

        Arguments args and kwargs are passed through to the validation
        function and to the constructor for the final type.  For Map types,
        validation function must take a data-header pair as an argument.

        Parameters
        ----------

        composite : boolean, optional
            Indicates if collection of maps should be returned as a CompositeMap

        cube : boolean, optional
            Indicates if collection of maps should be returned as a MapCube

        silence_errors : boolean, optional
            If set, ignore data-header pairs which cause an exception.

        """

        # Hack to get around Python 2.x not backporting PEP 3102.
        composite = kwargs.pop('composite', False)
        cube = kwargs.pop('cube', False)
        silence_errors = kwargs.pop('silence_errors', False)

        data_header_pairs, already_maps = self._parse_args(*args, **kwargs)

        new_maps = list()

        # Loop over each registered type and check to see if WidgetType
        # matches the arguments.  If it does, use that type.
        for pair in data_header_pairs:
            data, header = pair
            meta = MapMeta(header)

            try:
                new_map = self._check_registered_widgets(data, meta, **kwargs)
            except (NoMatchError, MultipleMatchError, ValidationFunctionError):
                if not silence_errors:
                    raise
            except:
                raise

            new_maps.append(new_map)

        new_maps += already_maps

        # If the list is meant to be a cube, instantiate a map cube
        if cube:
            return MapCube(new_maps, **kwargs)

        # If the list is meant to be a composite mape, instantiate one
        if composite:
            return CompositeMap(new_maps, **kwargs)

        if len(new_maps) == 1:
            return new_maps[0]

        return new_maps
示例#3
0
    def __call__(self,
                 *args,
                 composite=False,
                 sequence=False,
                 silence_errors=False,
                 **kwargs):
        """ Method for running the factory. Takes arbitrary arguments and
        keyword arguments and passes them to a sequence of pre-registered types
        to determine which is the correct Map-type to build.

        Arguments args and kwargs are passed through to the validation
        function and to the constructor for the final type. For Map types,
        validation function must take a data-header pair as an argument.

        Parameters
        ----------
        composite : `bool`, optional
            Indicates if collection of maps should be returned as a `~sunpy.map.CompositeMap`.
            Default is `False`.
        sequence : `bool`, optional
            Indicates if collection of maps should be returned as a `sunpy.map.MapSequence`.
            Default is `False`.
        silence_errors : `bool`, optional
            If set, ignore data-header pairs which cause an exception.
            Default is ``False``.

        Notes
        -----
        Extra keyword arguments are passed through to `sunpy.io.read_file` such
        as `memmap` for FITS files.
        """
        data_header_pairs = self._parse_args(*args,
                                             silence_errors=silence_errors,
                                             **kwargs)
        new_maps = list()

        # Loop over each registered type and check to see if WidgetType
        # matches the arguments.  If it does, use that type.
        for pair in data_header_pairs:
            if isinstance(pair, GenericMap):
                new_maps.append(pair)
                continue
            data, header = pair
            meta = MetaDict(header)

            try:
                new_map = self._check_registered_widgets(data, meta, **kwargs)
                new_maps.append(new_map)
            except (NoMatchError, MultipleMatchError, ValidationFunctionError,
                    MapMetaValidationError) as e:
                if not silence_errors:
                    raise
                warnings.warn(
                    f"One of the data, header pairs failed to validate with: {e}",
                    SunpyUserWarning)

        if not len(new_maps):
            raise RuntimeError('No maps loaded')

        # If the list is meant to be a sequence, instantiate a map sequence
        if sequence:
            return MapSequence(new_maps, **kwargs)

        # If the list is meant to be a composite map, instantiate one
        if composite:
            return CompositeMap(new_maps, **kwargs)

        if len(new_maps) == 1:
            return new_maps[0]

        return new_maps
示例#4
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,..)
    >>> sunpy.make_map([[0, 1],[2, 3]], {'telescop': 'sunpy',..})

    """
    if len(args) is 0:
        raise TypeError("Invalid input.")

    # First check to see if data/header were passed in    
    if isinstance(args[0], list) or isinstance(args[0], np.ndarray):
        data = None

        # n-dimensional list
        if isinstance(args[0][0], list) or isinstance(args[0], np.ndarray):
            data = args[0]
        else:
            try:
                float(args[0][0])
            except (ValueError, TypeError):
                pass
            else:
                # 1-dimensional data
                data = args[0]

        # if either of the above cases hold, then create a new Map
        if data is not None:
            if len(args) > 1:
                return Map(args[0], args[1])
            else:
                return Map(args[0], {})


    # If not, check for one or more maps or filepaths
    if len(args) == 1:
        # String
        if isinstance(args[0], basestring):
            filepath = os.path.expanduser(args[0])

            # Wildcard string
            if filepath.find("*") != -1:
                import glob
                maps = glob.glob(filepath)
            # Directory (use all files)
            elif os.path.isdir(filepath):
                maps = [os.path.join(filepath, x) for x in os.listdir(filepath)]

            # Filepath
            else:
                return Map.read(filepath)

        # Map/MapCube/CompositeMap
        elif (isinstance(args[0], Map) or 
              isinstance(args[0], CompositeMap) or 
              isinstance(args[0], MapCube)):
            return args[0]

        # List of filepaths or Maps
        elif isinstance(args[0], list):
            # list of maps or filepaths
            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'.")