Returns a description dictionary for pytables table creation


Creates a pytables column instance.

        The type of column depends on the type of `column[0]`.
        Note that data in `column` must be homogeneous!


Returns the longest string size for a string entry across data.


Loads into dictionary


Loads data that was originally a dictionary when stored

        :param leaf:

            PyTables table containing the dictionary data

        :param full_name:

            Full name of the parameter or result whose data is to be loaded

        :return:

            Data to be loaded


Reads shared data and constructs the appropraite class.

        :param shared_node:

            hdf5 node storing the pandas DataFrame

        :param full_name:

            Full name of the parameter or result whose data is to be loaded

        :return:

            Data to load


Reads a non-nested PyTables table column by column and created a new ObjectTable for
        the loaded data.

        :param table_or_group:

            PyTables table to read from or a group containing subtables.

        :param full_name:

            Full name of the parameter or result whose data is to be loaded

        :return:

            Data to be loaded


Reads data from an array or carray

        :param array:

            PyTables array or carray to read from

        :param full_name:

            Full name of the parameter or result whose data is to be loaded

        :return:

            Data to load


Helper function that creates a novel trajectory and loads it from disk.

    For the parameters see :func:`~pypet.trajectory.Trajectory.f_load`.

    ``new_name`` and ``add_time`` are only used in case ``as_new`` is ``True``.
    Accordingly, they determine the new name of trajectory.


Creates a run set name based on ``idx``


Sets properties like ``v_fast_access``.

        For example: ``traj.f_set_properties(v_fast_access=True, v_auto_load=False)``


Adds classes or paths to classes to the trajectory to create custom parameters.

        :param dynamic_imports:

            If you've written custom parameter that needs to be loaded dynamically during runtime,
            this needs to be specified here as a list of classes or strings naming classes
            and there module paths. For example:
            `dynamic_imports = ['pypet.parameter.PickleParameter',MyCustomParameter]`

            If you only have a single class to import, you do not need the list brackets:
            `dynamic_imports = 'pypet.parameter.PickleParameter'`


Makes the trajectory iterate over all runs.

        :param start: Start index of run

        :param stop: Stop index, leave ``None`` for length of trajectory

        :param step: Stepsize

        :param yields:

            What should be yielded: ``'name'`` of run, ``idx`` of run
            or ``'self'`` to simply return the trajectory container.

            You can also pick ``'copy'`` to get **shallow** copies (ie the tree is copied but
            no leave nodes except explored ones.) of your trajectory,
            might lead to some of overhead.

        Note that after a full iteration, the trajectory is set back to normal.

        Thus, the following code snippet

        ::

            for run_name in traj.f_iter_runs():

                 # Do some stuff here...

        is equivalent to

        ::

            for run_name in traj.f_get_run_names(sort=True):
                traj.f_set_crun(run_name)

                # Do some stuff here...

            traj.f_set_crun(None)

        :return:

            Iterator over runs. The iterator itself will return the run names but modify
            the trajectory in each iteration and set it back do normal in the end.


Searches for all occurrences of `name` in each run.

        Generates an ordered dictionary with the run names or indices as keys and
        found items as values.

        Example:

        >>> traj.f_get_from_runs(self, 'deep.universal_answer', use_indices=True, fast_access=True)
        OrderedDict([(0, 42), (1, 42), (2, 'fortytwo), (3, 43)])

        :param name:

            String description of the item(s) to find.
            Cannot be full names but the part of the names that are below
            a `run_XXXXXXXXX` group.

        :param include_default_run:

            If results found under ``run_ALL`` should be accounted for every run or simply be
            ignored.

        :param use_indices:

            If `True` the keys of the resulting dictionary are the run indices
            (e.g. 0,1,2,3), otherwise the keys are run names (e.g. `run_00000000`,
            `run_000000001`)

        :param fast_access:

            Whether to return parameter or result instances or the values handled by these.

        :param with_links:

            If links should be considered

        :param shortcuts:

            If shortcuts are allowed and the trajectory can *hop* over nodes in the
            path.

        :param max_depth:

            Maximum depth (relative to start node) how search should progress in tree.
            `None` means no depth limit.  Only relevant if `shortcuts` are allowed.

        :param auto_load:

            If data should be loaded from the storage service if it cannot be found in the
            current trajectory tree. Auto-loading will load group and leaf nodes currently
            not in memory and it will load data into empty leaves. Be aware that auto-loading
            does not work with shortcuts.

        :return:

            Ordered dictionary with run names or indices as keys and found items as values.
            Will only include runs where an item was actually found.


Private function such that it can still be called by the environment during
        a single run


Called if trajectory is expanded, deletes all explored parameters from disk


Pass a ``node`` to insert the full tree to the trajectory.

        Considers all links in the given node!
        Ignored nodes already found in the current trajectory.

        :param node: The node to insert

        :param copy_leaves:

            If leaves should be **shallow** copied or simply referred to by both trees.
            **Shallow** copying is established using the copy module.

            Accepts the setting ``'explored'`` to only copy explored parameters.
            Note that ``v_full_copy`` determines how these will be copied.

        :param overwrite:

            If existing elemenst should be overwritten. Requries ``__getstate__`` and
            ``__setstate__`` being implemented in the leaves.

        :param with_links: If links should be ignored or followed and copied as well

        :return: The corresponding (new) node in the tree.


Prepares the trajectory to explore the parameter space.

        To explore the parameter space you need to provide a dictionary with the names of the
        parameters to explore as keys and iterables specifying the exploration ranges as values.

        All iterables need to have the same length otherwise a ValueError is raised.
        A ValueError is also raised if the names from the dictionary map to groups or results
        and not parameters.

        If your trajectory is already explored but not stored yet and your parameters are
        not locked you can add new explored parameters to the current ones if their
        iterables match the current length of the trajectory.

        Raises an AttributeError if the names from the dictionary are not found at all in
        the trajectory and NotUniqueNodeError if the keys not unambiguously map
        to single parameters.

        Raises a TypeError if the trajectory has been stored already, please use
        :func:`~pypet.trajectory.Trajectory.f_expand` then instead.

        Example usage:

        >>> traj.f_explore({'groupA.param1' : [1,2,3,4,5], 'groupA.param2':['a','b','c','d','e']})

        Could also be called consecutively:

        >>> traj.f_explore({'groupA.param1' : [1,2,3,4,5]})
        >>> traj.f_explore({'groupA.param2':['a','b','c','d','e']})

        NOTE:

        Since parameters are very conservative regarding the data they accept
        (see :ref:`type_conservation`), you sometimes won't be able to use Numpy arrays
        for exploration as iterables.

        For instance, the following code snippet won't work:

        ::

            import numpy a np
            from pypet.trajectory import Trajectory
            traj = Trajectory()
            traj.f_add_parameter('my_float_parameter', 42.4,
                                 comment='My value is a standard python float')

            traj.f_explore( { 'my_float_parameter': np.arange(42.0, 44.876, 0.23) } )

        This will result in a `TypeError` because your exploration iterable
        `np.arange(42.0, 44.876, 0.23)` contains `numpy.float64` values
        whereas you parameter is supposed to use standard python floats.

        Yet, you can use Numpys `tolist()` function to overcome this problem:

        ::

            traj.f_explore( { 'my_float_parameter': np.arange(42.0, 44.876, 0.23).tolist() } )

        Or you could specify your parameter directly as a numpy float:

        ::

            traj.f_add_parameter('my_float_parameter', np.float64(42.4),
                                   comment='My value is a numpy 64 bit float')


Overwrites the run information of a particular run


Locks all non-empty parameters


Loads the full skeleton from the storage service.

        This needs to be done after a successful exploration in order to update the
        trajectory tree with all results and derived parameters from the individual single runs.
        This will only add empty results and derived parameters (i.e. the skeleton)
        and load annotations.


Loads a trajectory via the storage service.

        If you want to load individual results or parameters manually, you can take
        a look at :func:`~pypet.trajectory.Trajectory.f_load_items`.
        To only load subtrees check out :func:`~pypet.naturalnaming.NNGroupNode.f_load_child`.

        For `f_load` you can pass the following arguments:

        :param name:

            Name of the trajectory to be loaded. If no name or index is specified
            the current name of the trajectory is used.

        :param index:

            If you don't specify a name you can specify an integer index instead.
            The corresponding trajectory in the hdf5 file at the index
            position is loaded (counting starts with 0). Negative indices are also allowed
            counting in reverse order. For instance, `-1` refers to the last trajectory in
            the file, `-2` to the second last, and so on.

        :param as_new:

            Whether you want to rerun the experiments. So the trajectory is loaded only
            with parameters. The current trajectory name is kept in this case, which should be
            different from the trajectory name specified in the input parameter `name`.
            If you load `as_new=True` all parameters are unlocked.
            If you load `as_new=False` the current trajectory is replaced by the one on disk,
            i.e. name, timestamp, formatted time etc. are all taken from disk.

        :param load_parameters: How parameters and config items are loaded

        :param load_derived_parameters: How derived parameters are loaded

        :param load_results: How results are loaded

            You can specify how to load the parameters, derived parameters and results
            as follows:

                * :const:`pypet.pypetconstants.LOAD_NOTHING`: (0)

                    Nothing is loaded.

                * :const:`pypet.pypetconstants.LOAD_SKELETON`: (1)

                    The skeleton is loaded including annotations (See :ref:`more-on-annotations`).
                    This means that only empty
                    *parameter* and *result* objects will
                    be created  and you can manually load the data into them afterwards.
                    Note that :class:`pypet.annotations.Annotations` do not count as data and they
                    will be loaded because they are assumed to be small.

                * :const:`pypet.pypetconstants.LOAD_DATA`: (2)

                    The whole data is loaded. Note in case you have non-empty leaves
                    already in RAM, these are left untouched.

                * :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3)

                    As before, but non-empty nodes are emptied and reloaded.

                Note that in all cases except :const:`pypet.pypetconstants.LOAD_NOTHING`,
                annotations will be reloaded if the corresponding instance
                is created or the annotations of an existing instance were emptied before.

        :param recursive:

            If data should be loaded recursively. If set to `None`, this is equivalent to
            set all data loading to `:const:`pypet.pypetconstants.LOAD_NOTHING`.

        :param load_data:

            As the above, per default set to `None`. If not `None` the setting of `load_data`
            will overwrite the settings of `load_parameters`, `load_derived_parameters`,
            `load_results`, and `load_other_data`. This is more or less or shortcut if all
            types should be loaded the same.

        :param max_depth:

            Maximum depth to load nodes (inclusive).

        :param force:

            *pypet* will refuse to load trajectories that have been created using *pypet* with a
            different version number or a different python version.
            To force the load of a trajectory from a previous version
            simply set ``force = True``. Note that it is not checked if other versions of packages
            differ from previous experiments, i.e. numpy, scipy, etc. But you can check
            for this manually. The versions of other packages can be found under
            ``'config.environment.name_of_environment.versions.package_name'``.

        :param dynamic_imports:

            If you've written a custom parameter that needs to be loaded dynamically
            during runtime, this needs to be specified here as a list of classes or
            strings naming classes and there module paths. For example:
            `dynamic_imports = ['pypet.parameter.PickleParameter',MyCustomParameter]`

            If you only have a single class to import, you do not need the list brackets:
            `dynamic_imports = 'pypet.parameter.PickleParameter'`

            The classes passed here are added for good and will be kept by the trajectory.
            Please add your dynamically imported classes only once.

        :param with_run_information:

            If information about the individual runs should be loaded. If you have many
            runs, like 1,000,000 or more you can spare time by setting
            `with_run_information=False`.
            Note that `f_get_run_information` and `f_idx_to_run` do not work in such a case.
            Moreover, setting `v_idx` does not work either. If you load the trajectory
            without this information, be careful, this is not recommended.

        :param wiht_meta_data:

            If meta data should be loaded.

        :param storage_service:

            Pass a storage service used by the trajectory. Alternatively pass a constructor
            and other ``**kwargs`` are passed onto the constructor. Leave `None` in combination
            with using no other kwargs, if you don't want to change the service
            the trajectory is currently using.

        :param kwargs:

            Other arguments passed to the storage service constructor. Don't pass any
            other kwargs and ``storage_service=None``,
            if you don't want to change the current service.


Backs up the trajectory with the given storage service.

        Arguments of ``kwargs`` are directly passed to the storage service,
        for the HDF5StorageService you can provide the following argument:

        :param backup_filename:

            Name of file where to store the backup.

            In case you use the standard HDF5 storage service and `backup_filename=None`,
            the file will be chosen automatically.
            The backup file will be in the same folder as your hdf5 file and
            named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory.


Can be used to merge several `other_trajectories` into your current one.

        IMPORTANT `backup=True` only backs up the current trajectory not any of
        the `other_trajectories`. If you need a backup of these, do it manually.

        Parameters as for :func:`~pypet.trajectory.Trajectory.f_merge`.


Renames a full name based on the wildcards and a particular run


Merges derived parameters that have the `run_ALL` in a name.

        Creates a new parameter with the name of the first new run and links to this
        parameter to avoid copying in all other runs.


Merges all links


Merges meta data about previous merges, git commits, and environment settings
        of the other trajectory into the current one.


Merges all results.

        :param rename_dict:

            Dictionary that is filled with the names of results in the `other_trajectory`
            as keys and the corresponding new names in the current trajectory as values.
            Note for results kept under trajectory run branch there is actually no need to
            change the names. So we will simply keep the original name.


Can be called to rename and relocate the trajectory.

        :param new_name: New name of the trajectory, None if you do not want to change the name.

        :param in_store:

            Set this to True if the trajectory has been stored with the new name at the new
            file before  and you just want to "switch back" to the location.
            If you migrate to a store used before and you do not set `in_store=True`,
            the storage service will throw a RuntimeError in case you store the Trajectory
            because it will assume that you try to store a new trajectory that accidentally has
            the very same name as another trajectory. If set to `True` and trajectory is not found
            in the file, the trajectory is simply stored to the file.

        :param new_storage_service:

            New service where you want to migrate to. Leave none if you want to keep the olde one.

        :param kwargs:

            Additional keyword arguments passed to the service.
            For instance, to change the file of the trajectory use ``filename='my_new_file.hdf5``.


Restores the default value in all explored parameters and sets the
        v_idx property back to -1 and v_crun to None.


Notifies the explored parameters what current point in the parameter space
        they should represent.


Returns a dictionary containing information about a single run.

        ONLY useful during a single run if ``v_full_copy` was set to ``True``.
        Otherwise only the current run is available.

        The information dictionaries have the following key, value pairings:

            * completed: Boolean, whether a run was completed

            * idx: Index of a run

            * timestamp: Timestamp of the run as a float

            * time: Formatted time string

            * finish_timestamp: Timestamp of the finishing of the run

            * runtime: Total runtime of the run in human readable format

            * name: Name of the run

            * parameter_summary:

                A string summary of the explored parameter settings for the particular run

            * short_environment_hexsha: The short version of the environment SHA-1 code

        If no name or idx is given then a nested dictionary with keys as run names and
        info dictionaries as values is returned.

        :param name_or_idx: str or int

        :param copy:

            Whether you want the dictionary used by the trajectory or a copy. Note if
            you want the real thing, please do not modify it, i.e. popping or adding stuff. This
            could mess up your whole trajectory.

        :return:

            A run information dictionary or a nested dictionary of information dictionaries
            with the run names as keys.


Finds a single run index given a particular condition on parameters.

        ONLY useful for a single run if ``v_full_copy` was set to ``True``.
        Otherwise a TypeError is thrown.

        :param name_list:

            A list of parameter names the predicate applies to, if you have only a single
            parameter name you can omit the list brackets.

        :param predicate:

            A lambda predicate for filtering that evaluates to either ``True`` or  ``False``

        :return: A generator yielding the matching single run indices

        Example:

        >>> predicate = lambda param1, param2: param1==4 and param2 in [1.0, 2.0]
        >>> iterator = traj.f_find_idx(['groupA.param1', 'groupA.param2'], predicate)
        >>> [x for x in iterator]
        [0, 2, 17, 36]


Can be used to manually allow running of an experiment without using an environment.

        :param run_name_or_idx:

            Can manually set a trajectory to a particular run. If `None` the current run
            the trajectory is set to is used.

        :param turn_into_run:

            Turns the trajectory into a run, i.e. reduces functionality but makes storing
            more efficient.


Sets the start timestamp and formatted time to the current time.


Returns a dictionary containing either all parameters, all explored parameters,
        all config, all derived parameters, or all results.

        :param param_dict: The dictionary which is about to be returned
        :param fast_access: Whether to use fast access
        :param copy: If the original dict should be returned or a shallow copy

        :return: The dictionary

        :raises: ValueError if `copy=False` and fast_access=True`


Called by the environment after storing to perform some rollback operations.

        All results and derived parameters created in the current run are removed.

        Important for single processing to not blow up the parent trajectory with the results
        of all runs.


Stores individual items to disk.

        This function is useful if you calculated very large results (or large derived parameters)
        during runtime and you want to write these to disk immediately and empty them afterwards
        to free some memory.

        Instead of storing individual parameters or results you can also store whole subtrees with
        :func:`~pypet.naturalnaming.NNGroupNode.f_store_child`.

        You can pass the following arguments to `f_store_items`:

        :param iterator:

            An iterable containing the parameters or results to store, either their
            names or the instances. You can also pass group instances or names here
            to store the annotations of the groups.

        :param non_empties:

            Optional keyword argument (boolean),
            if `True` will only store the subset of provided items that are not empty.
            Empty parameters or results found in `iterator` are simply ignored.

        :param args: Additional arguments passed to the storage service

        :param kwargs:

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword argument:

            :param overwrite:

                List names of parts of your item that should
                be erased and overwritten by the new data in your leaf.
                You can also set `overwrite=True`
                to overwrite all parts.

                For instance:

                    >>> traj.f_add_result('mygroup.myresult', partA=42, partB=44, partC=46)
                    >>> traj.f_store()
                    >>> traj.mygroup.myresult.partA = 333
                    >>> traj.mygroup.myresult.partB = 'I am going to change to a string'
                    >>> traj.f_store_item('mygroup.myresult', overwrite=['partA', 'partB'])

                Will store `'mygroup.myresult'` to disk again and overwrite the parts
                `'partA'` and `'partB'` with the new values `333` and
                `'I am going to change to a string'`.
                The data stored as `partC` is not changed.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                Note that massive overwriting will fragment and blow up your HDF5 file.
                Try to avoid changing data on disk whenever you can.

        :raises:

            TypeError:

                If the (parent) trajectory has never been stored to disk. In this case
                use :func:`pypet.trajectory.f_store` first.

            ValueError: If no item could be found to be stored.

        Note if you use the standard hdf5 storage service, there are no additional arguments
        or keyword arguments to pass!


Loads parameters and results specified in `iterator`.

        You can directly list the Parameter objects or just their names.

        If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the
        parameters or results in the trajectory. Accordingly, the parameters and results
        you want to load must already exist in your trajectory (in RAM), probably they
        are just empty skeletons waiting desperately to handle data.
        If they do not exist in RAM yet, but have been stored to disk before,
        you can call :func:`~pypet.trajectory.Trajectory.f_load_skeleton` in order to
        bring your trajectory tree skeleton up to date. In case of a single run you can
        use the :func:`~pypet.naturalnaming.NNGroupNode.f_load_child` method to recursively
        load a subtree without any data.
        Then you can load the data of individual results or parameters one by one.

        If want to load the whole trajectory at once or ALL results and parameters that are
        still empty take a look at :func:`~pypet.trajectory.Trajectory.f_load`.
        As mentioned before, to load subtrees of your trajectory you might want to check out
        :func:`~pypet.naturalnaming.NNGroupNode.f_load_child`.

        To load a list of parameters or results with `f_load_items` you can pass
        the following arguments:

        :param iterator: A list with parameters or results to be loaded.

        :param only_empties:

            Optional keyword argument (boolean),
            if `True` only empty parameters or results are passed
            to the storage service to get loaded. Non-empty parameters or results found in
            `iterator` are simply ignored.

        :param args: Additional arguments directly passed to the storage service

        :param kwargs:

            Additional keyword arguments directly passed to the storage service
            (except the kwarg `only_empties`)

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword arguments:

            :param load_only:

                If you load a result, you can partially load it and ignore the rest of data items.
                Just specify the name of the data you want to load. You can also provide a list,
                for example `load_only='spikes'`, `load_only=['spikes','membrane_potential']`.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                A warning is issued if data specified in `load_only` cannot be found in the
                instances specified in `iterator`.

            :param load_except:

                Analogous to the above, but everything is loaded except names or parts
                specified in `load_except`.
                You cannot use `load_only` and `load_except` at the same time. If you do
                a ValueError is thrown.

                A warning is issued if names listed in `load_except` are not part of the
                items to load.


Removes parameters, results or groups from the trajectory.

        This function ONLY removes items from your current trajectory and does not delete
        data stored to disk. If you want to delete data from disk, take a look at
        :func:`~pypet.trajectory.Trajectory.f_delete_items`.

        This will also remove all links if items are linked.

        :param iterator:

            A sequence of items you want to remove. Either the instances themselves
            or strings with the names of the items.

        :param recursive:

            In case you want to remove group nodes, if the children should be removed, too.


Recursively removes all children of the trajectory

        :param recursive:

            Only here for consistency with signature of parent method. Cannot be set
            to `False` because the trajectory root node cannot be removed.

        :param predicate:

            Predicate which can evaluate for each node to ``True`` in order to remove the node or
            ``False`` if the node should be kept. Leave ``None`` if you want to remove all nodes.


Deletes items from storage on disk.

        Per default the item is NOT removed from the trajectory.

        Links are NOT deleted on the hard disk, please delete links manually before deleting
        data!

        :param iterator:

            A sequence of items you want to remove. Either the instances themselves
            or strings with the names of the items.

        :param remove_from_trajectory:

            If items should also be removed from trajectory. Default is `False`.

        :param args: Additional arguments passed to the storage service

        :param kwargs: Additional keyword arguments passed to the storage service

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword argument:

            :param delete_only:

                You can partially delete leaf nodes. Specify a list of parts of the result node
                that should be deleted like `delete_only=['mystuff','otherstuff']`.
                This wil only delete the hdf5 sub parts `mystuff` and `otherstuff` from disk.
                BE CAREFUL,
                erasing data partly happens at your own risk. Depending on how complex the
                loading process of your result node is, you might not be able to reconstruct
                any data due to partially deleting some of it.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                If the hdf5 nodes you specified in `delete_only` cannot be found a warning
                is issued.

                Note that massive deletion will fragment your HDF5 file.
                Try to avoid changing data on disk whenever you can.

                If you want to erase a full node, simply ignore this argument or set to `None`.

            :param remove_from_item:

                If data that you want to delete from storage should also be removed from
                the items in `iterator` if they contain these. Default is `False`.

            :param recursive:

                If you want to delete a group node and it has children you need to
                set `recursive` to `True. Default is `False`.


A class to replace the strftime in datetime package or time module.
	Identical to strftime behavior in those modules except supports any
	year.
	Also supports datetime.datetime times.
	Also supports milliseconds using %s
	Also supports microseconds using %u


A function to replace strptime in the time module.  Should behave
	identically to the strptime function except it returns a datetime.datetime
	object instead of a time.struct_time object.
	Also takes an optional tzinfo parameter which is a time zone info object.


Returns the nearest year to now inferred from a Julian date.


return the number of seconds in the specified period

	>>> get_period_seconds('day')
	86400
	>>> get_period_seconds(86400)
	86400
	>>> get_period_seconds(datetime.timedelta(hours=24))
	86400
	>>> get_period_seconds('day + os.system("rm -Rf *")')
	Traceback (most recent call last):
	...
	ValueError: period not in (second, minute, hour, day, month, year)


Divide a timedelta by a float value

	>>> one_day = datetime.timedelta(days=1)
	>>> half_day = datetime.timedelta(days=.5)
	>>> divide_timedelta_float(one_day, 2.0) == half_day
	True
	>>> divide_timedelta_float(one_day, 2) == half_day
	True


Take a string representing a span of time and parse it to a time delta.
	Accepts any string of comma-separated numbers each with a unit indicator.

	>>> parse_timedelta('1 day')
	datetime.timedelta(days=1)

	>>> parse_timedelta('1 day, 30 seconds')
	datetime.timedelta(days=1, seconds=30)

	>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')
	datetime.timedelta(days=47, seconds=28848, microseconds=15400)

	Supports weeks, months, years

	>>> parse_timedelta('1 week')
	datetime.timedelta(days=7)

	>>> parse_timedelta('1 year, 1 month')
	datetime.timedelta(days=395, seconds=58685)

	Note that months and years strict intervals, not aligned
	to a calendar:

	>>> now = datetime.datetime.now()
	>>> later = now + parse_timedelta('1 year')
	>>> diff = later.replace(year=now.year) - now
	>>> diff.seconds
	20940


Get the ratio of two timedeltas

	>>> one_day = datetime.timedelta(days=1)
	>>> one_hour = datetime.timedelta(hours=1)
	>>> divide_timedelta(one_hour, one_day) == 1 / 24
	True


Construct a datetime.datetime from a number of different time
		types found in python and pythonwin


Starts a pool single run and passes the storage service


Single run wrapper for the frozen pool, makes a single run and passes kwargs


Configures the pool and keeps the storage service


Configures the frozen pool and keeps all kwargs


Wrapper function that configures a frozen SCOOP set up.

    Deletes of data if necessary.


Starts running a queue handler and creates a log file for the queue.


String summary of the value handled by the parameter.

        Note that representing the parameter as a string accesses its value,
        but for simpler debugging, this does not lock the parameter or counts as usage!

        Calls `__repr__` of the contained value.


Explores the parameter according to the iterable.

        Raises ParameterLockedException if the parameter is locked.
        Raises TypeError if the parameter does not support the data,
        the types of the data in the iterable are not the same as the type of the default value,
        or the parameter has already an exploration range.

        Note that the parameter will iterate over the whole iterable once and store
        the individual data values into a tuple. Thus, the whole exploration range is
        explicitly stored in memory.

        :param explore_iterable: An iterable specifying the exploration range

        For example:

        >>> param._explore([3.0,2.0,1.0])
        >>> param.f_get_range()
        (3.0, 2.0, 1.0)

        :raises TypeError,ParameterLockedException


Explores the parameter according to the iterable and appends to the exploration range.

        Raises ParameterLockedException if the parameter is locked.
        Raises TypeError if the parameter does not support the data,
        the types of the data in the iterable are not the same as the type of the default value,
        or the parameter did not have an array before.

        Note that the parameter will iterate over the whole iterable once and store
        the individual data values into a tuple. Thus, the whole exploration range is
        explicitly stored in memory.

        :param explore_iterable: An iterable specifying the exploration range

         For example:

         >>> param = Parameter('Im.an.example', data=33.33, comment='Wooohoo!')
         >>> param._explore([3.0,2.0,1.0])
         >>> param._expand([42.0, 43.42])
         >>> param.f_get_range()
         >>> [3.0, 2.0, 1.0, 42.0, 43.42]

        :raises TypeError, ParameterLockedException


Loads the data and exploration range from the `load_dict`.

        The `load_dict` needs to be in the same format as the result of the
        :func:`~pypet.parameter.Parameter._store` method.


Reconstructs the data and exploration array.

        Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
        If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.

        If the parameter is explored, the exploration range of arrays is reconstructed
        as it was stored in :func:`~pypet.parameter.ArrayParameter._store`.


Matrices are equal if they hash to the same value.


Extracts data from a sparse matrix to make it serializable in a human readable format.

        :return: Tuple with following elements:

            1.

                A list containing data that is necessary to reconstruct the matrix.
                For csr, csc, and bsr matrices the following attributes are extracted:
                `format`, `data`, `indices`, `indptr`, `shape`.
                Where format is simply one of the strings 'csr', 'csc', or 'bsr'.

                For dia matrices the following attributes are extracted:
                `format`, `data`, `offsets`, `shape`.
                Where `format` is simply the string 'dia'.

            2.

                A list containing the names of the extracted attributes.
                For csr, csc, and bsr:

                    [`format`, `data`, `indices`, `indptr`, `shape`]

                For dia:

                    [`format`, `data`, `offsets`, `shape`]

            3.

                A tuple containing the hashable parts of (1) in order to use the tuple as
                a key for a dictionary. Accordingly, the numpy arrays of (1) are
                changed to read-only.


Reconstructs a matrix from a list containing sparse matrix extracted properties

        `data_list` needs to be formatted as the first result of
        :func:`~pypet.parameter.SparseParameter._serialize_matrix`


Reconstructs the data and exploration array

        Checks if it can find the array identifier in the `load_dict`, i.e. '__spsp__'.
        If not, calls :class:`~pypet.parameter.ArrayParameter._load` of the parent class.

        If the parameter is explored, the exploration range of matrices is reconstructed
        as it was stored in :func:`~pypet.parameter.SparseParameter._store`.


Returns a dictionary for storage.

        Every element in the dictionary except for 'explored_data' is a pickle dump.

        Reusage of objects is identified over the object id, i.e. python's built-in id function.

        'explored_data' contains the references to the objects to be able to recall the
        order of objects later on.


Reconstructs objects from the pickle dumps in `load_dict`.

        The 'explored_data' entry in `load_dict` is used to reconstruct
        the exploration range in the correct order.

        Sets the `v_protocol` property to the protocol used to store 'data'.


Translates integer indices into the appropriate names


Returns all handled data as a dictionary.

        :param copy:

            Whether the original dictionary or a shallow copy is returned.

        :return: Data dictionary


Method to put data into the result.

        :param args:

            The first positional argument is stored with the name of the result.
            Following arguments are stored with `name_X` where `X` is the position
            of the argument.

        :param kwargs: Arguments are stored with the key as name.

        :raises: TypeError if outer data structure is not understood.

        Example usage:

        >>> res = Result('supergroup.subgroup.myresult', comment='I am a neat example!')
        >>> res.f_set(333,42.0, mystring='String!')
        >>> res.f_get('myresult')
        333
        >>> res.f_get('myresult_1')
        42.0
        >>> res.f_get(1)
        42.0
        >>> res.f_get('mystring')
        'String!'


Sets a single data item of the result.

        Raises TypeError if the type of the outer data structure is not understood.
        Note that the type check is shallow. For example, if the data item is a list,
        the individual list elements are NOT checked whether their types are appropriate.

        :param name: The name of the data item

        :param item: The data item

        :raises: TypeError

        Example usage:

        >>> res.f_set_single('answer', 42)
        >>> res.f_get('answer')
        42


Supports everything of parent class and csr, csc, bsr, and dia sparse matrices.


Returns a storage dictionary understood by the storage service.

        Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
        marked with the identifier `__spsp__`.


Loads data from `load_dict`

        Reconstruction of sparse matrices similar to the :class:`~pypet.parameter.SparseParameter`.


Simply merge all trajectories in the working directory


Creates and returns a new SAGA session


Starts all jobs and runs `the_task.py` in batches.


Sophisticated simulation of multiplication


Runs a simulation of a model neuron.

    :param traj:

        Container with all parameters.

    :return:

        An estimate of the firing rate of the neuron


Postprocessing, sorts computed firing rates into a table

    :param traj:

        Container for results and parameters

    :param result_list:

        List of tuples, where first entry is the run index and second is the actual
        result of the corresponding run.

    :return:


Extracts subruns from the trajectory.

        :param traj: Trajectory container

        :param pre_run: Boolean whether current run is regular or a pre-run

        :raises: RuntimeError if orders are duplicates or even missing


Generic `execute_network_run` function, handles experimental runs as well as pre-runs.

        See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and
         :func:`~pypet.brian2.network.NetworkRunner.execute_network_pre_run`.


Top-level simulation function, pass this to the environment

        Performs an individual network run during parameter exploration.

        `run_network` does not need to be called by the user. If this
        method (not this one of the NetworkManager)
        is passed to an :class:`~pypet.environment.Environment` with this NetworkManager,
        `run_network` and :func:`~pypet.brian2.network.NetworkManager.build`
        are automatically called for each individual experimental run.

        This function will create a new BRIAN2 network in case one was not pre-run.
        The execution of the network run is carried out by
        the :class:`~pypet.brian2.network.NetworkRunner` and it's
        :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` (also take
        a look at this function's documentation to see the structure of a network run).

        :param traj: Trajectory container


Starts a single run carried out by a NetworkRunner.

        Called from the public function :func:`~pypet.brian2.network.NetworkManger.run_network`.

        :param traj: Trajectory container


Function to create generic filenames based on what has been explored


Merges all files in a given folder.

    IMPORTANT: Does not check if there are more than 1 trajectory in a file. Always
    uses the last trajectory in file and ignores the other ones.

    Trajectories are merged according to the alphabetical order of the files,
    i.e. the resulting merged trajectory is found in the first file
    (according to lexicographic ordering).

    :param folder: folder (not recursive) where to look for files
    :param ext: only files with the given extension are used
    :param dynamic_imports: Dynamic imports for loading
    :param storage_service: storage service to use, leave `None` to use the default one
    :param force: If loading should be forced.
    :param delete_other_files: Deletes files of merged trajectories

    All other parameters as in `f_merge_many` of the trajectory.

    :return: The merged traj


Handler of SIGINT

        Does nothing if SIGINT is encountered once but raises a KeyboardInterrupt in case it
        is encountered twice.
        immediatly.


Small configuration file management function


Method to request API tokens from ecobee


Write api tokens to a file


The minimum time, in minutes, to run the fan each hour. Value from 1 to 60


Set a climate hold - ie away, home, sleep


Delete the vacation with name vacation


Resume currently scheduled program


Set humidity level


Generate the time in seconds in which DHCPDISCOVER wil be retransmited.

    [:rfc:`2131#section-3.1`]::

        might retransmit the
        DHCPREQUEST message four times, for a total delay of 60 seconds

    [:rfc:`2131#section-4.1`]::

        For example, in a 10Mb/sec Ethernet
        internetwork, the delay before the first retransmission SHOULD be 4
        seconds randomized by the value of a uniform random number chosen
        from the range -1 to +1.  Clients with clocks that provide resolution
        granularity of less than one second may choose a non-integer
        randomization value.  The delay before the next retransmission SHOULD
        be 8 seconds randomized by the value of a uniform number chosen from
        the range -1 to +1.  The retransmission delay SHOULD be doubled with
        subsequent retransmissions up to a maximum of 64 seconds.


Generate time in seconds to retransmit DHCPREQUEST.

    [:rfc:`2131#section-4..4.5`]::

        In both RENEWING and REBINDING states,
        if the client receives no response to its DHCPREQUEST
        message, the client SHOULD wait one-half of the remaining
        time until T2 (in RENEWING state) and one-half of the
        remaining lease time (in REBINDING state), down to a
        minimum of 60 seconds, before retransmitting the
        DHCPREQUEST message.


Return the self object attributes not inherited as dict.


Reset object attributes when state is INIT.


Workaround to get timeout in the ATMT.timeout class method.


Workaround to change timeout values in the ATMT.timeout class method.

        self.timeout format is::

            {'STATE': [
                (TIMEOUT0, <function foo>),
                (TIMEOUT1, <function bar>)),
                (None, None)
                ],
            }


Select an offer from the offers received.

        [:rfc:`2131#section-4.2`]::

            DHCP clients are free to use any strategy in selecting a DHCP
            server among those from which the client receives a DHCPOFFER.

        [:rfc:`2131#section-4.4.1`]::

            The time
            over which the client collects messages and the mechanism used to
            select one DHCPOFFER are implementation dependent.

        Nor [:rfc:`7844`] nor [:rfc:`2131`] specify the algorithm.
        Here, currently the first offer is selected.

        .. todo::

           - Check other implementations algorithm to select offer.


Send request.

        [:rfc:`2131#section-3.1`]::

        a client retransmitting as described in section 4.1 might retransmit
        the DHCPREQUEST message four times, for a total delay of 60 seconds

        .. todo::

           - The maximum number of retransmitted REQUESTs is per state or in
             total?
           - Are the retransmitted REQUESTs independent to the retransmitted
             DISCOVERs?


INIT state.

        [:rfc:`2131#section-4.4.1`]::

            The client SHOULD wait a random time between one and ten
            seconds to desynchronize the use of DHCP at startup

        .. todo::
           - The initial delay is implemented, but probably is not in other
             implementations. Check what other implementations do.


END state.


ERROR state.


Timeout of selecting on SELECTING state.

        Not specifiyed in [:rfc:`7844`].
        See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.


Timeout requesting in REQUESTING state.

        Not specifiyed in [:rfc:`7844`]

        [:rfc:`2131#section-3.1`]::

            might retransmit the
            DHCPREQUEST message four times, for a total delay of 60 seconds


Timeout of renewing on RENEWING state.

        Same comments as in
        :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.


Timeout of request rebinding on REBINDING state.

        Same comments as in
        :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.


Receive offer on SELECTING state.


Receive ACK in REQUESTING state.


Receive ACK in RENEWING state.


Receive NAK in RENEWING state.


Assign a value, remove if it's None


Append a value to multiple value parameter.


Remove a value from multiple value parameter.


Pass in an Overpass query in Overpass QL.


This attempts to allocate v6 addresses as per RFC2462 and RFC3041.

        To accomodate this, we effectively treat all v6 assignment as a
        first time allocation utilizing the MAC address of the VIF. Because
        we recycle MACs, we will eventually attempt to recreate a previously
        generated v6 address. Instead of failing, we've opted to handle
        reallocating that address in this method.

        This should provide a performance boost over attempting to check
        each and every subnet in the existing reallocate logic, as we'd
        have to iterate over each and every subnet returned


Associates the flip with ports and creates it with the flip driver

    :param context: neutron api request context.
    :param flip: quark.db.models.IPAddress object representing a floating IP
    :param port_fixed_ips: dictionary of the structure:
    {"<id of port>": {"port": <quark.db.models.Port>,
     "fixed_ip": "<fixed ip address>"}}
    :return: None


Update an existing floating IP.

    :param context: neutron api request context.
    :param id: id of the floating ip
    :param content: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.

    :returns: Dictionary containing details for the new floating IP.  If values
        are declared in the fields parameter, then only those keys will be
        present.


deallocate a floating IP.

    :param context: neutron api request context.
    :param id: id of the floating ip


Retrieve a list of floating ips.

    :param context: neutron api request context.
    :param filters: a dictionary with keys that are valid keys for
        a floating ip as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.
    :param fields: a list of strings that are valid keys in a
        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.

    :returns: List of floating IPs that are accessible to the tenant who
        submits the request (as indicated by the tenant id of the context)
        as well as any filters.


Return the number of floating IPs.

    :param context: neutron api request context
    :param filters: a dictionary with keys that are valid keys for
        a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    :returns: The number of floating IPs that are accessible to the tenant who
        submits the request (as indicated by the tenant id of the context)
        as well as any filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


Update an existing scaling IP.

    :param context: neutron api request context.
    :param id: id of the scaling ip
    :param content: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.

    :returns: Dictionary containing details for the new scaling IP.  If values
        are declared in the fields parameter, then only those keys will be
        present.


Splits VIFs into three explicit categories and one implicit

    Added - Groups exist in Redis that have not been ack'd and the VIF
            is not tagged.
            Action: Tag the VIF and apply flows
    Updated - Groups exist in Redis that have not been ack'd and the VIF
              is already tagged
              Action: Do not tag the VIF, do apply flows
    Removed - Groups do NOT exist in Redis but the VIF is tagged
              Action: Untag the VIF, apply default flows
    Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat
                this case as if it were an "added" group.
                Action: Tag the VIF and apply flows
    NOOP - The VIF is not tagged and there are no matching groups in Redis.
           This is our implicit category
           Action: Do nothing


Fetches changes and applies them to VIFs periodically

    Process as of RM11449:
    * Get all groups from redis
    * Fetch ALL VIFs from Xen
    * Walk ALL VIFs and partition them into added, updated and removed
    * Walk the final "modified" VIFs list and apply flows to each


Delete the quota entries for a given tenant_id.

        Atfer deletion, this tenant will use default quota values in conf.


Validate the CIDR for a subnet.

    Verifies the specified CIDR does not overlap with the ones defined
    for the other subnets specified for this network, or with any other
    CIDR if overlapping IPs are disabled.


Retrieve a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to fetch.
    : param fields: a list of strings that are valid keys in a
        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


Return the number of subnets.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


Updates a rule and updates the ports


Returns the public net id


A decorator to be used on another decorator

    This is done to allow separate handling on the basis of argument values


Will add the tenant_id to the context from body.

        It is assumed that the body must have a tenant_id because neutron
        core could never have gotten here otherwise.


Validate IP allocation pools.

        Verify start and end address for each allocation pool are valid,
        ie: constituted by valid and appropriately ordered IP addresses.
        Also, verify pools do not overlap among themselves.
        Finally, verify that each range fall within the subnet's CIDR.


Creates a job with support for subjobs.

    If parent_id is not in the body:
    * the job is considered a parent job
    * it will have a NULL transaction id
    * its transaction id == its id
    * all subjobs will use its transaction id as theirs

    Else:
    * the job is a sub job
    * the parent id is the id passed in
    * the transaction id is the root of the job tree


Deconfigure any additional default transport zone bindings.


Public interface for fetching lswitch ids for a given network.

        NOTE(morgabra) This is here because calling private methods
        from outside the class feels wrong, and we need to be able to
        fetch lswitch ids for use in other drivers.


Looks for modules with amtching entry points.


Chunks data into chunk with size<=chunk_size.


Find a deallocated network segment id and reallocate it.

        NOTE(morgabra) This locks the segment table, but only the rows
        in use by the segment, which is pretty handy if we ever have
        more than 1 segment or segment type.


Deletes locks for each IP address that is no longer null-routed.


Creates locks for each IP address that is null-routed.

    The function creates the IP address if it is not present in the database.


Return relevant IPAM strategy name.

        :param network_id: neutron network id.
        :param network_strategy: default strategy for the network.

        NOTE(morgabra) This feels like a hack but I can't think of a better
        idea. The root problem is we can now attach ports to networks with
        a different backend driver/ipam strategy than the network speficies.

        We handle the the backend driver part with allowing network_plugin to
        be specified for port objects. This works pretty well because nova or
        whatever knows when we are hooking up an Ironic node so it can pass
        along that key during port_create().

        IPAM is a little trickier, especially in Ironic's case, because we
        *must* use a specific IPAM for provider networks. There isn't really
        much of an option other than involve the backend driver when selecting
        the IPAM strategy.


Return a dict of extra network information.

        :param context: neutron request context.
        :param network_id: neturon network id.
        :param net_driver: network driver associated with network_id.
        :raises IronicException: Any unexpected data fetching failures will
            be logged and IronicException raised.

        This driver can attach to networks managed by other drivers. We may
        need some information from these drivers, or otherwise inform
        downstream about the type of network we are attaching to. We can
        make these decisions here.


Set tag on model object.


Get a matching valid tag off the model.


Pop all matching tags off the model and return them.


Get all known tags from a model.

        Returns a dict of {<tag_name>:<tag_value>}.


Gets security groups for interfaces from Redis

        Returns a dictionary of xapi.VIFs with values of the current
        acknowledged status in Redis.

        States not explicitly handled:
        * ack key, no rules - This is the same as just tagging the VIF,
          the instance will be inaccessible
        * rules key, no ack - Nothing will happen, the VIF will
          not be tagged.


Updates security groups by setting the ack field


Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.


Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.


Generic Notifier.

    Parameters:
        - `context`: session context
        - `event_type`: the event type to report, i.e. ip.usage
        - `payload`: dict containing the payload to send


Method to send notifications.

    We must send USAGE when a public IPv4 address is deallocated or a FLIP is
    associated.
    Parameters:
        - `context`: the context for notifier
        - `event_type`: the event type for IP allocate, deallocate, associate,
        disassociate
        - `ipaddress`: the ipaddress object to notify about
    Returns:
        nothing
    Notes: this may live in the billing module


Returns a tuple of start_period and end_period.

    Assumes that the period is 24-hrs.
    Parameters:
        - `hour`: the hour from 0 to 23 when the period ends
        - `minute`: the minute from 0 to 59 when the period ends
    This method will calculate the end of the period as the closest hour/minute
    going backwards.
    It will also calculate the start of the period as the passed hour/minute
    but 24 hrs ago.
    Example, if we pass 0, 0 - we will get the events from 0:00 midnight of the
    day before yesterday until today's midnight.
    If we pass 2,0 - we will get the start time as 2am of the previous morning
    till 2am of today's morning.
    By default it's midnight.


Creates the view for a job while calculating progress.

    Since a root job does not have a transaction id (TID) it will return its
    id as the TID.


Retrieve a mac_address_range.

    : param context: neutron api request context
    : param id: UUID representing the network to fetch.
    : param fields: a list of strings that are valid keys in a
        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


Delete a segment_allocation_range.

    : param context: neutron api request context
    : param id: UUID representing the segment_allocation_range to delete.


Returns a WSGI filter app for use with paste.deploy.


Returns dictionary with keys segment_id and value used IPs count.

    Used IP address count is determined by:
    - allocated IPs
    - deallocated IPs whose `deallocated_at` is within the `reuse_after`
    window compared to the present time, excluding IPs that are accounted for
    in the current IP policy (because IP policy is mutable and deallocated IPs
    are not checked nor deleted on IP policy creation, thus deallocated IPs
    that don't fit the current IP policy can exist in the neutron database).


Returns dictionary with key segment_id, and value unused IPs count.

    Unused IP address count is determined by:
    - adding subnet's cidr's size
    - subtracting IP policy exclusions on subnet
    - subtracting used ips per segment


Handles changes to interfaces' security groups

        Calls refresh_interfaces on argument VIFs. Set security groups on
        added_sg's VIFs. Unsets security groups on removed_sg's VIFs.


Retrieve a network.

    : param context: neutron api request context
    : param id: UUID representing the network to fetch.
    : param fields: a list of strings that are valid keys in a
        network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.


Return the number of networks.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.


Delete a network.

    : param context: neutron api request context
    : param id: UUID representing the network to delete.


This is a helper method for testing.

    When run with the current context, it will create a case 2 entries
    in the database. See top of file for what case 2 is.


Runs billing report. Optionally sends notifications to billing


Provides an admin context for workers.


Begins the async update process.


Updates the ports through redis.


Gather all ports associated to security group.

    Returns:
    * list, or None


Updates a security group rule.

    NOTE(alexm) this is non-standard functionality.


Sends the given command to Niko Home Control and returns the output of
        the system.

        Aliases: write, put, sendall, send_all


Implements the 'if' operator with support for multiple elseif-s.


Implements the '==' operator, which does type JS-style coertion.


Implements the '<' operator with JS-style type coertion.


Also, converts either to ints or to floats.


Implements the 'merge' operator for merging lists.


Gets variable value from data dictionary.


Implements the missing operator for finding missing variables.


Implements the missing_some operator for finding missing variables.


Executes the json-logic with given data.


Performs an indentation


Performs an un-indentation


Handle indent between symbols such as parenthesis, braces,...


Extends mouseMoveEvent to display a pointing hand cursor when the
        mouse cursor is over a file location


Emits open_file_requested if the press event occured  over
        a file location string.


Connects slots to signals


Setup the python editor, run the server and connect a few signals.

        :param editor: editor to setup.


Creates a new GenericCodeEdit, opens the requested file and adds it
        to the tab widget.

        :param path: Path of the file to open

        :return The opened editor if open succeeded.


Add a new empty code editor to the tab widget


Save the current editor document as.


Update action states when the current tab changed.


Run the current current script


Worker that returns a list of calltips.

    A calltips is a tuple made of the following parts:
      - module_name: name of the module of the function invoked
      - call_name: name of the function that is being called
      - params: the list of parameter names.
      - index: index of the current parameter
      - bracket_start

    :returns tuple(module_name, call_name, params)


Go to assignements worker.


Worker that returns the documentation of the symbol under cursor.


Worker that run the pep8 tool on the current editor text.

    :returns a list of tuples (msg, msg_type, line_number)


Completes python code using `jedi`_.

        :returns: a list of completion.


Request a go to assignment.

        :param tc: Text cursor which contains the text that we must look for
                   its assignment. Can be None to go to the text that is under
                   the text cursor.
        :type tc: QtGui.QTextCursor


Not performant but works.


r"""Create variants metadata file.

    Variants metadata file helps speed up subsequent reads of the associated
    bgen file.

    Parameters
    ----------
    bgen_filepath : str
        Bgen file path.
    metafile_file : str
        Metafile file path.
    verbose : bool
        ``True`` to show progress; ``False`` otherwise.

    Examples
    --------
    .. doctest::

        >>> import os
        >>> from bgen_reader import create_metafile, example_files
        >>>
        >>> with example_files("example.32bits.bgen") as filepath:
        ...     folder = os.path.dirname(filepath)
        ...     metafile_filepath = os.path.join(folder, filepath + ".metadata")
        ...
        ...     try:
        ...         create_metafile(filepath, metafile_filepath, verbose=False)
        ...     finally:
        ...         if os.path.exists(metafile_filepath):
        ...             os.remove(metafile_filepath)


Search through lines for match.
            Raise an Exception if a match


Return true if ``instance`` is an instance of any the Directive
        types in ``typeList``


Get programs statuses.

    :param options: parsed commandline arguments.
    :type options: optparse.Values.
    :return: supervisord XML-RPC call result.
    :rtype: dict.


Create Nagios and human readable supervisord statuses.

    :param data: supervisord XML-RPC call result.
    :type data: dict.
    :param options: parsed commandline arguments.
    :type options: optparse.Values.
    :return: Nagios and human readable supervisord statuses and exit code.
    :rtype: (str, int).


r""" Compute allele frequency from its expectation.

    Parameters
    ----------
    expec : array_like
        Allele expectations encoded as a samples-by-alleles matrix.

    Returns
    -------
    :class:`numpy.ndarray`
        Allele frequencies encoded as a variants-by-alleles matrix.

    Examples
    --------
    .. doctest::

        >>> from bgen_reader import read_bgen, example_files
        >>> from bgen_reader import allele_expectation, allele_frequency
        >>>
        >>> # Download an example
        >>> example = example_files("example.32bits.bgen")
        >>> filepath = example.filepath
        >>>
        >>> bgen = read_bgen(filepath, verbose=False)
        >>>
        >>> variants = bgen["variants"]
        >>> samples = bgen["samples"]
        >>> genotype = bgen["genotype"]
        >>>
        >>> variant = variants[variants["rsid"] == "RSID_6"].compute()
        >>> variant_idx = variant.index.item()
        >>>
        >>> p = genotype[variant_idx].compute()["probs"]
        >>> # For unphased genotypes only.
        >>> e = allele_expectation(bgen, variant_idx)
        >>> f = allele_frequency(e)
        >>>
        >>> alleles = variant["allele_ids"].item().split(",")
        >>> print(alleles[0] + ": {}".format(f[0]))
        A: 229.23103218810434
        >>> print(alleles[1] + ": {}".format(f[1]))
        G: 270.7689678118956
        >>> print(variant)
                id    rsid chrom   pos  nalleles allele_ids  vaddr
        4  SNPID_6  RSID_6    01  6000         2        A,G  19377
        >>>
        >>> # Clean-up the example
        >>> example.close()


Fit distance-based AD.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            The input samples. Use ``dtype=np.float32`` for maximum
            efficiency.

        Returns
        -------
        self : object
            Returns self.


Learning is to find the inverse matrix for X and calculate the threshold.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            The input samples. Use ``dtype=np.float32`` for maximum
            efficiency.
        y : array-like, shape = [n_samples] or [n_samples, n_outputs]
            The target values (real numbers in regression).

        Returns
        -------
        self : object


Predict the distances for X to center of the training set.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            The input samples. Internally, it will be converted to
            ``dtype=np.float32`` and if a sparse matrix is provided
            to a sparse ``csr_matrix``.

        Returns
        -------
        leverages: array of shape = [n_samples]
                   The objects distances to center of the training set.


Find min and max values of every feature.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The training input samples.
        y : Ignored
            not used, present for API consistency by convention.

        Returns
        -------
        self : object


Do nothing and return the estimator unchanged

        This method is just there to implement the usual API and hence work in pipelines.


finalize partial fitting procedure


Compute the header.


Return whether this model has a self ref FK, and the name for the field


All concrete fields of the ``SyncableModel`` subclass, except for those specifically blacklisted, are returned in a dict.


Returns an unsaved class object based on the valid properties passed in.


Returns the default value for this field.


Should return a 32-digit hex string for a UUID that is calculated as a function of a set of fields from the model.


Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark
    the model as deleted in the store.


Static method for error handling.

        :param resp - API response
        :param error - Error thrown
        :param mode - Error mode
        :param response_format - XML or json


Checks the condition in poll response to determine if it is complete
        and no subsequent poll requests should be done.


We set the lower counter between two same instance ids.
    If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.

    :param fsic1: dictionary containing (instance_id, counter) pairs
    :param fsic2: dictionary containing (instance_id, counter) pairs
    :return ``dict`` of fsics to be used in queueing the correct records to the buffer


Takes data from the buffers and merges into the store and record max counters.


SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but
    can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device.
    We use the calculated value to chunk our SQL bulk insert statements when deserializing from the store to the app layer.


Authenticate the userargs and password against Django auth backends.
        The "userargs" string may be just the username, or a querystring-encoded set of params.


Per profile, adds each model to a dictionary mapping the morango model name to its model class.
    We sort by ForeignKey dependencies to safely sync data.


Generic request method designed to handle any morango endpoint.

        :param endpoint: constant representing which morango endpoint we are querying
        :param method: HTTP verb/method for request
        :param lookup: the pk value for the specific object we are querying
        :param data: dict that will be form-encoded in request
        :param params: dict to be sent as part of URL's query string
        :param userargs: Authorization credentials
        :param password:
        :return: ``Response`` object from request


Validate a decoded SNS message.

    Parameters:
        message:
            Decoded SNS message.

        get_certificate:
            Function that receives a URL, and returns the certificate from that
            URL as a string. The default doesn't implement caching.

        certificate_url_regex:
            Regex that validates the signing certificate URL. Default value
            checks it's hosted on an AWS-controlled domain, in the format
            "https://sns.<data-center>.amazonaws.com/"

        max_age:
            Maximum age of an SNS message before it fails validation, expressed
            as a `datetime.timedelta`. Defaults to one hour, the max. lifetime
            of an SNS message.


Creates an access token.

        TODO: check valid in hours
        TODO: maybe specify how often a token can be used


Stores an OWS service in mongodb.


Lists all services in mongodb storage.


Gets service for given ``name`` from mongodb storage.


Gets service for given ``url`` from mongodb storage.


Delegates owsproxy request to external twitcher service.


A tween factory which produces a tween which raises an exception
    if access to OWS service is not allowed.


Read tdms file and return channel names and data


From circularity, compute the deformation

    This method is useful for RT-DC data sets that contain
    the circularity but not the deformation.


Creates an fcs file for a given tdms file


Store an OWS service in database.


Lists all services in memory storage.


Get service for given ``name`` from memory storage.


Generates a new private key and certificate request, submits the request to be
        signed by the SLCS CA and returns the certificate.


Get parameter in GET request.


Find requested request type in POST request.


Provide a timzeone-aware object for a given datetime and timezone name


return baseurl of given url


Call 'setup egg_info' and return the parsed meta-data.


Distribute the project.


Prepare for a release.


Perform source code checks via pylint.


Check for uncommitted changes, return `True` if everything is clean.

            Inspired by http://stackoverflow.com/questions/3878624/.


Dump project metadata for Jenkins Description Setter Plugin.


Run a command and return its stripped captured output.


Run a command and flush its output.


Adds a new patch with patchname to the queue

        The new patch will be added as the topmost applied patch.


Factory for the correct SCM provider in `workdir`.


Delete specified patch from the series
        If remove is True the patch file will also be removed. If remove and
        backup are True a copy of the deleted patch file will be made.


Checks if a backup file of the filename in the current patch
        exists


Creates a backup of file


Run command as a subprocess and wait until it is finished.

        The command should be given as a list of strings to avoid problems
        with shell quoting.  If the command exits with a return code other
        than 0, a SubprocessError is raised.


Creates the directory and all its parent directories if it does not
        exist yet


Create hard link as link to this file


Copy file to destination


Returns the directory where the file is placed in or None if the
        path to the file doesn't contain a directory


Provide a zipped stream of the docs tree.


Upload to PyPI.


Upload to WebDAV store.


A context that enters a given directory and restores the old state on exit.

        The original directory is returned as the context variable.


Backup file in dest_dir Directory.
        The return value is a File object pointing to the copied file in the
        destination directory or None if no file is copied.

        If file exists and it is not empty it is copied to dest_dir.
        If file exists and it is empty the file is copied only if copy_empty is
        True.
        If file does not exist and copy_empty is True a new file in dest_dir
        will be created.
        In all other cases no file will be copied and None is returned.


Refresh patch with patch_name or applied top patch if patch_name is
        None


Unapply top patch


Unapply all patches


Emit a normal message.


Emit an error message to stderr.


Get currently used 'devpi' base URL.


Apply all patches up to patch_name


Apply next patch in series file


Apply all patches in series file


Determine location of `tasks.py`.


Load and return configuration as a ``Bunch``.

        Values are based on ``DEFAULTS``, and metadata from ``setup.py``.


Convert a path part to regex syntax.


Generate parts of regex transformed from glob pattern.


Convert the given glob `spec` to a compiled regex.


Check patterns in order, last match that includes or excludes `path` wins. Return `None` on undecided.


Build a DEB package.


Reads all patches from the series file


Saves current patches list in the series file


Add a patch to the patches list


Add a list of patches to the patches list


Returns a list of patches before patch from the patches list
        including the provided patch


Replace old_patch with new_patch
        The method only replaces the patch and doesn't change any comments.


Creates the dirname and inserts a .version file


Checks if the .version file in dirname has the correct supported
            version number


Build the project.


Freeze currently installed requirements.


Adds the argument to an argparse.ArgumentParser instance

        @param parser An argparse.ArgumentParser instance


Adds this SubParser to the subparsers created by
        argparse.ArgumentParser.add_subparsers method.

        @param subparsers Normally a _SubParsersAction instance created by
        argparse.ArgumentParser.add_subparsers method


Checks if a backup file of the filename in the current patch
        exists and raises a QuiltError if not.


Revert not added changes of filename.
        If patch_name is None or empty the topmost patch will be used.


Return current or given time formatted according to ISO-8601.


Windows allow application paths to be registered in the registry.


Return a generator of full paths to the given command.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned for each
        match. The second element is a textual description of where the
        match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    This method returns a generator which yields either full paths to
    the given command or, if verbose, tuples of the form (<path to
    command>, <where path found>).


Return the full path to the first match of the given command on
    the path.

    "command" is a the name of the executable to search for.
    "path" is an optional alternate path list to search. The default it
        to use the PATH environment variable.
    "verbose", if true, will cause a 2-tuple to be returned. The second
        element is a textual description of where the match was found.
    "exts" optionally allows one to specify a list of extensions to use
        instead of the standard list for this system. This can
        effectively be used as an optimization to, for example, avoid
        stat's of "foo.vbs" when searching for "foo" and you know it is
        not a VisualBasic script but ".vbs" is on PATHEXT. This option
        is only supported on Windows.

    If no match is found for the command, a WhichError is raised.


Import patch into the patch queue
        The patch is inserted as the next unapplied patch.


Import several patches into the patch queue


Process each way.


Get a list of nodes not found in OSM data.


Process each node.


Extract information of one route.


Create a meaningful route name.


Process the files and collect necessary data.


Process each relation.


Fill the fields that are necessary for passing transitfeed checks.


Create station stop times for each trip.


Write the GTFS feed in the given file.


Write GTFS text files in the given path.


Extract stops in a relation.


Gets a list of supported U2F versions from the device.


Sends an APDU to the device, and waits for a response.


Register a U2F device

    data = {
        "version": "U2F_V2",
        "challenge": string, //b64 encoded challenge
        "appId": string, //app_id
    }


Perform a rachted step, replacing one of the internally managed chains with a new
        one.

        :param key: A bytes-like object encoding the key to initialize the replacement
            chain with.
        :param chain: The chain to replace. This parameter must be one of the two strings
            "sending" and "receiving".


Derive a new set of internal and output data from given input data and the data
        stored internally.

        Use the key derivation function to derive new data. The kdf gets supplied with the
        current key and the data passed to this method.

        :param data: A bytes-like object encoding the data to pass to the key derivation
            function.
        :returns: A bytes-like object encoding the output material.


Create a connection to an other mesh.

        .. warning:: Both meshes need to be disconnected and one needs to be
          a consumed and the other a produced mesh. You can check if a
          connection is possible using :meth:`can_connect_to`.

        .. seealso:: :meth:`is_consumed`, :meth:`is_produced`,
          :meth:`can_connect_to`


Saves the dump in a file-like object in text mode.

        :param file: :obj:`None` or a file-like object.
        :return: a file-like object

        If :paramref:`file` is :obj:`None`, a new :class:`io.StringIO`
        is returned.
        If :paramref:`file` is not :obj:`None` it should be a file-like object.

        The content is written to the file. After writing, the file's
        read/write position points behind the dumped content.


Saves the dump in a file named `path`.


Saves the dump in a temporary file and returns its path.

        .. warning:: The user of this method is responsible for deleting this
                     file to save space on the hard drive.
                     If you only need a file object for a short period of time
                     you can use the method :meth:`temporary_file`.

        :param str extension: the ending ot the file name e.g. ``".png"``
        :return: a path to the temporary file
        :rtype: str


set the pixel but convert the color before.


set the color of the pixel.

        :param color: must be a valid color in the form of "#RRGGBB".
          If you need to convert color, use `_set_pixel_and_convert_color()`.


The id that identifies the instruction in this cache.

        :param instruction_or_id: an :class:`instruction
          <knittingpattern.Instruction.Instruction>` or an instruction id
        :return: a :func:`hashable <hash>` object
        :rtype: tuple


Return the SVG for an instruction.

        :param instruction_or_id: either an
          :class:`~knittingpattern.Instruction.Instruction` or an id
          returned by :meth:`get_instruction_id`
        :param bool i_promise_not_to_change_the_result:

          - :obj:`False`: the result is copied, you can alter it.
          - :obj:`True`: the result is directly from the cache. If you change
            the result, other calls of this function get the changed result.

        :return: an SVGDumper
        :rtype: knittingpattern.Dumper.SVGDumper


Return the SVG dict for the SVGBuilder.

        :param instruction_or_id: the instruction or id, see
          :meth:`get_instruction_id`
        :param bool copy_result: whether to copy the result
        :rtype: dict

        The result is cached.


The last produced mesh.

        :return: the last produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`number_of_produced_meshes`


The last consumed mesh.

        :return: the last consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`number_of_consumed_meshes`


The first produced mesh.

        :return: the first produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`number_of_produced_meshes`


The first consumed mesh.

        :return: the first consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`number_of_consumed_meshes`


The rows that produce meshes for this row.

        :rtype: list
        :return: a list of rows that produce meshes for this row. Each row
          occurs only once. They are sorted by the first occurrence in the
          instructions.


The rows that consume meshes from this row.

        :rtype: list
        :return: a list of rows that consume meshes from this row. Each row
          occurs only once. They are sorted by the first occurrence in the
          instructions.


Load all files from a folder recursively.

        Depending on :meth:`chooses_path` some paths may not be loaded.
        Every loaded path is processed and returned part of the returned list.

        :param str folder: the folder to load the files from
        :rtype: list
        :return: a list of the results of the processing steps of the loaded
          files


Load a folder located relative to a module and return the processed
        result.

        :param str module: can be

          - a path to a folder
          - a path to a file
          - a module name

        :param str folder: the path of a folder relative to :paramref:`module`
        :return: a list of the results of the processing
        :rtype: list

        Depending on :meth:`chooses_path` some paths may not be loaded.
        Every loaded path is processed and returned part of the returned list.
        You can use :meth:`choose_paths` to find out which paths are chosen to
        load.


Load a file relative to a module.

        :param str module: can be

          - a path to a folder
          - a path to a file
          - a module name

        :param str folder: the path of a folder relative to :paramref:`module`
        :return: the result of the processing


Load an example from the knitting pattern examples.

        :param str relative_path: the path to load
        :return: the result of the processing

        You can use :meth:`knittingpattern.Loader.PathLoader.examples`
        to find out the paths of all examples.


load and process the content behind a url

        :return: the processed result of the :paramref:`url's <url>` content
        :param str url: the url to retrieve the content from
        :param str encoding: the encoding of the retrieved content.
          The default encoding is UTF-8.


dump a knitting pattern to a file.


Create a definition for the instruction.

        :return: the id of a symbol in the defs for the specified
          :paramref:`instruction`
        :rtype: str

        If no symbol yet exists in the defs for the :paramref:`instruction` a
        symbol is created and saved using :meth:`_make_symbol`.


Compute the scale of an instruction svg.

        Compute the scale using the bounding box stored in the
        :paramref:`svg_dict`. The scale is saved in a dictionary using
        :paramref:`instruction_id` as key.

        :param str instruction_id: id identifying a symbol in the defs
        :param dict svg_dict: dictionary containing the SVG for the
          instruction currently processed


Add a new, empty knitting pattern to the set.

        :param id_: the id of the pattern
        :param name: the name of the pattern to add or if :obj:`None`, the
          :paramref:`id_` is used
        :return: a new, empty knitting pattern
        :rtype: knittingpattern.KnittingPattern.KnittingPattern


Index of the instruction in the instructions of the row or None.

        :return: index in the :attr:`row`'s instructions or None, if the
          instruction is not in the row
        :rtype: int

        .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`,
          :meth:`is_in_row`


The instruction after this one or None.

        :return: the instruction in :attr:`row_instructions` after this or
          :obj:`None` if this is the last
        :rtype: knittingpattern.Instruction.InstructionInRow

        This can be used to traverse the instructions.

        .. seealso:: :attr:`previous_instruction_in_row`


Index of the first produced mesh in the row that consumes it.

        :return: an index of the first produced mesh of rows produced meshes
        :rtype: int

        .. note:: If the instruction :meth:`produces meshes
          <Instruction.produces_meshes>`, this is the index of the first
          mesh the instruction produces in all the meshes of the row.
          If the instruction does not produce meshes, the index of the mesh is
          returned as if the instruction had produced a mesh.

        .. code::

            if instruction.produces_meshes():
                index = instruction.index_of_first_produced_mesh_in_row


The index of the first consumed mesh of this instruction in its row.

        Same as :attr:`index_of_first_produced_mesh_in_row`
        but for consumed meshes.


Parse a knitting pattern set.

        :param dict value: the specification of the knitting pattern set
        :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet
        :raises knittingpattern.KnittingPatternSet.ParsingError: if
          :paramref:`value` does not fulfill the :ref:`specification
          <FileFormatSpecification>`.


Fill a pattern collection.


Parse a pattern.


Parse a collection of rows.


Connect the parsed rows.


Create a new pattern set.


Write bytes to the file.


Write a string to the file.


An SVG object.

        :return: an SVG object
        :rtype: kivy.graphics.svg.Svg
        :raises ImportError: if the module was not found


Adds the defs to the SVG structure.

        :param defs: a list of SVG dictionaries, which contain the defs,
          which should be added to the SVG structure.


For ``self.width``.


Walk through the knitting pattern by expanding an row.


expand the consumed meshes


expand the produced meshes


place the instruction on a grid


Loop through all the instructions that are `_todo`.


Returns an `InstructionInGrid` object for the `instruction`


Iterate over instructions.

        :return: an iterator over :class:`instructions in grid
          <InstructionInGrid>`
        :param mapping: funcion to map the result

        .. code:: python

            for pos, c in layout.walk_instructions(lambda i: (i.xy, i.color)):
                print("color {} at {}".format(c, pos))


Iterate over rows.

        :return: an iterator over :class:`rows <RowsInGrid>`
        :param mapping: funcion to map the result, see
          :meth:`walk_instructions` for an example usage


The minimum and maximum bounds of this layout.

        :return: ``(min_x, min_y, max_x, max_y)`` the bounding box
          of this layout
        :rtype: tuple


dump to the file


Add an instruction specification

        :param specification: a specification with a key
          :data:`knittingpattern.Instruction.TYPE`

        .. seealso:: :meth:`as_instruction`


Listen to parameters change.

        Parameters
        ----------
        func : callable
            Function to be called when a parameter changes.


Gradient of K.

        Returns
        -------
        C0 : ndarray
            Derivative of C₀ over its parameters.
        C1 : ndarray
            Derivative of C₁ over its parameters.


Poisson likelihood sampling.

    Parameters
    ----------
    random_state : random_state
        Set the initial random state.

    Example
    -------

    .. doctest::

        >>> from glimix_core.random import poisson_sample
        >>> from numpy.random import RandomState
        >>> offset = -0.5
        >>> G = [[0.5, -1], [2, 1]]
        >>> poisson_sample(offset, G, random_state=RandomState(0))
        array([0, 6])


Helper function for retrieving a particular entry from the prefix trees


This is not a general purpose converter. Only converts this readme


This method starts the server. There are two processes, one is an HTTP server that shows
    and admin interface and the second is a Thrift server that the client code calls.

    Arguments:
        `conf_path` - The path to your flawless.cfg file
        `storage_factory` - You can pass in your own storage class that implements StorageInterface. You must implement
                            storage_cls if you want Flawless to be horizontally scalable, since by default it will just
                            store everything on the local disk.


r""" Mean of the estimated posteriori.

        This is also the maximum a posteriori estimation of the latent variable.


r""" Covariance of the estimated posteriori.


Eigen decomposition of a zero matrix.


r"""Gradient of the log of the marginal likelihood.

        Returns
        -------
        dict
            Map between variables to their gradient values.


Derivative of the covariance matrix over the lower triangular, flat part of L.

        It is equal to

            ∂K/∂Lᵢⱼ = ALᵀ + LAᵀ,

        where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1.

        Returns
        -------
        Lu : ndarray
            Derivative of K over the lower-triangular, flat part of L.


Fixed-effect sizes.

        Returns
        -------
        effect-sizes : numpy.ndarray
            Optimal fixed-effect sizes.

        Notes
        -----
        Setting the derivative of log(p(𝐲)) over effect sizes equal
        to zero leads to solutions 𝜷 from equation ::

            (QᵀX)ᵀD⁻¹(QᵀX)𝜷 = (QᵀX)ᵀD⁻¹(Qᵀ𝐲).


Estimates the covariance-matrix of the optimal beta.

        Returns
        -------
        beta-covariance : ndarray
            (Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹.

        References
        ----------
        .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John
           Wiley & Sons.


Disable parameter optimization.

        Parameters
        ----------
        param : str
            Possible values are ``"delta"``, ``"beta"``, and ``"scale"``.


Maximise the marginal likelihood.

        Parameters
        ----------
        verbose : bool, optional
            ``True`` for progress output; ``False`` otherwise.
            Defaults to ``True``.


Internal use only.


Variance ratio between ``K`` and ``I``.


Log of the marginal likelihood for optimal scale.

        Implementation for unrestricted LML::

        Returns
        -------
        lml : float
            Log of the marginal likelihood.


Degrees of freedom.


r"""Log of the marginal likelihood.

        Formally,

        .. math::

            - \frac{n}{2}\log{2\pi} - \frac{1}{2} \log{\left|
                v_0 \mathrm K + v_1 \mathrm I + \tilde{\Sigma} \right|}
                    - \frac{1}{2}
                    \left(\tilde{\boldsymbol\mu} -
                    \mathrm X\boldsymbol\beta\right)^{\intercal}
                    \left( v_0 \mathrm K + v_1 \mathrm I +
                    \tilde{\Sigma} \right)^{-1}
                    \left(\tilde{\boldsymbol\mu} -
                    \mathrm X\boldsymbol\beta\right)

        Returns
        -------
        float
            :math:`\log{p(\tilde{\boldsymbol\mu})}`