Beispiel #1
0
    def test_update(self):

        try:
            OrderedDict().update([('a', 1), ('b', 2)], None)                        # too many args
            assert False
        except TypeError:
            pass
        else:
            assert False

        pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
        od = OrderedDict()
        od.update(dict(pairs))
        self.assertEqual(sorted(od.items()), pairs)                                 # dict input
        od = OrderedDict()
        od.update(**dict(pairs))
        self.assertEqual(sorted(od.items()), pairs)                                 # kwds input
        od = OrderedDict()
        od.update(pairs)
        self.assertEqual(list(od.items()), pairs)                                   # pairs input
        od = OrderedDict()
        od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)
        self.assertEqual(list(od.items()), pairs)                                   # mixed input

        # Make sure that direct calls to update do not clear previous contents
        # add that updates items are not moved to the end
        d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
        d.update([('e', 5), ('f', 6)], g=7, d=4)
        self.assertEqual(list(d.items()),
            [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
Beispiel #2
0
 def test_copying(self):
     # Check that ordered dicts are copyable, deepcopyable, picklable,
     # and have a repr/eval round-trip
     pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
     od = OrderedDict(pairs)
     update_test = OrderedDict()
     update_test.update(od)
     for i, dup in enumerate([
                 od.copy(),
                 copy.copy(od),
                 copy.deepcopy(od),
                 pickle.loads(pickle.dumps(od, 0)),
                 pickle.loads(pickle.dumps(od, 1)),
                 pickle.loads(pickle.dumps(od, 2)),
                 pickle.loads(pickle.dumps(od, -1)),
                 eval(repr(od)),
                 update_test,
                 OrderedDict(od),
                 ]):
         self.assertTrue(dup is not od)
         self.assertEquals(dup, od)
         self.assertEquals(list(dup.items()), list(od.items()))
         self.assertEquals(len(dup), len(od))
         self.assertEquals(type(dup), type(od))
Beispiel #3
0
class LightcurveFunc(object):
    '''Wrap function for the lightcurve analysis function registry

    This wrapper is to be used for fucntions that operate on individual
    lightcurves.

    Functions in the registry of analysis function for lightcurves need
    some metadata for make sure that they can be called correctly, when
    :class:`atlas.YSOVAR_atlas` autogenerated columns in the table.

    This class warps a function and provides some metadata.
    This metadata includes:

        - The number of bands the function requires as input.
        - Does the function require the uncertainty of the mags?
        - Does the function require the time of the observations?
        - What is the name of the function, so that it can be found?
        - Some short description of the function.
        - Default names for the columns that are autogenerated.

    Use the following command to read the full docstring of the function
    that is wrapped in this object::

        help(my_object.func)

    .. note::
        This class is usually not called directly.
        Use :func:`YSOVAR.registry.register`.

    '''

    ''' hold default keyword arguments for this function'''
    kwargs = {}    

    def __init__(self, func, n_bands, error, time, name = '',
                 default_colnames = [], default_colunits=[None], default_coldescriptions=None, other_cols = dict(), description = '', kwargs = {}):
        '''Wrap function for the lightcurve analysis function registry

        Parameters
        ----------
        func : function or callable object
            This function will be called.
        n_bands : int
            Number of spectral bands required by this function.
        error : bool
            If ``True`` the uncertainties in each lightcurve band will be passed
            to the function.
        time : bool
            If ``True`` the observations times will be passed as first argument.
        name : string
            Set the name used to identify the function in the registry.
            Default is the name of the function.
        description : string
            One line description of the function.
            Default is the first line of the docstring of the function.
        default_colnames : list of strings
            Prefix used for naming auto-generated data columns in a :class:`YSOVAR_atlas`.
            All generated columns are of type ``np.float``; this is just a
            convenience, since most column are float columns. It is equally
            possible to define each column with its datatype explicitly in
            ``other_col``.
            The length of the list should equal the number of values returned by the
            function. If neither this keyword nor ``other_col``is set,
            it defaults to the name of the function. However, if the function
            returns more than on output value then this keyword is required.
        default_colunits : list of strings or None's
            Default unit for auto-generated data columns. If not set, the unit
            will be ``None``.
        default_coldescriptions : list of strings or None
            Default column description for auto-generated columns. Note that
            this will often be different from ``description``, e.g. when a
            function call generates more than one output value.
            Nevertheless, if this keyword is not set, the first column will
            have ``description`` and all further columns not receive a 
            descriptive text.
        other_cols : Ordered dictionary
            This dictionary fullfills the same role as ``default_colname``, but
            if allows to specify ``{colname: dtype}`` pairs.
            If both ``default_colname`` and ``other_col`` are present, then
            the first values are assigned to the columns named in
            ``default_colname``.
        kwargs : dictionary
            This supplied keyword arguments that will be passed to ``func`` each
            time it is called, unless the keyword of the same name is passed
            when calling. Essentially, this provides a mechnism to
            easily freeze a keyword argument.
        '''
        self.func = func
        self.n_bands = n_bands
        self.error = error
        self.time = time
        if name == '':
            self.name = func.__name__
        else:
            self.name = name

        if '_' in name:
            raise ValueError('{0} contains an "_". This does not work for autogeneration of columns. Use name = name to speficy an alternative name.'.format(name))
    
        if default_colnames == [] and other_cols == OrderedDict():
            self.default_colnames = OrderedDict([[func.__name__, float]])
        else:
            self.default_colnames = OrderedDict(
                zip(default_colnames, [float]*len(default_colnames)))
            self.default_colnames.update(other_cols)        
            
        if description == '':
            # Find first non-empty line in description
            descr = func.__doc__.split('\n')
            # Just to safeguard for empty docstrings
            try:
                self.description = descr.pop(0).strip()
                while self.description == '':
                    self.description = descr.pop(0).strip()
            except IndexError:
                pass
        else:
            self.description = description

        self.default_colunits = default_colunits
        self.default_coldescriptions = [self.description] if (default_coldescriptions is None) else default_coldescriptions

        self.kwargs = kwargs
 
    def __call__(self, *args, **kwargs):
        pass_args = self.kwargs.copy()
        pass_args.update(kwargs)
        return self.func(*args, **pass_args)

    def __str__(self):
        return '{0:10s} - {1}'.format(self.name, self.description)