当前位置: 首页>>代码示例>>Python>>正文


Python OrderedDict.values方法代码示例

本文整理汇总了Python中diffpy.srfit.util.ordereddict.OrderedDict.values方法的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict.values方法的具体用法?Python OrderedDict.values怎么用?Python OrderedDict.values使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在diffpy.srfit.util.ordereddict.OrderedDict的用法示例。


在下文中一共展示了OrderedDict.values方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_iterators

# 需要导入模块: from diffpy.srfit.util.ordereddict import OrderedDict [as 别名]
# 或者: from diffpy.srfit.util.ordereddict.OrderedDict import values [as 别名]
 def test_iterators(self):
     pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
     shuffle(pairs)
     od = OrderedDict(pairs)
     self.assertEqual(list(od), [t[0] for t in pairs])
     self.assertEqual(list(od.keys()), [t[0] for t in pairs])
     self.assertEqual(list(od.values()), [t[1] for t in pairs])
     self.assertEqual(list(od.items()), pairs)
     self.assertEqual(list(reversed(od)),
                      [t[0] for t in reversed(pairs)])
开发者ID:XiaohaoYang,项目名称:diffpy.srfit,代码行数:12,代码来源:testordereddict.py

示例2: RecipeContainer

# 需要导入模块: from diffpy.srfit.util.ordereddict import OrderedDict [as 别名]
# 或者: from diffpy.srfit.util.ordereddict.OrderedDict import values [as 别名]
class RecipeContainer(Observable, Configurable, Validatable):
    """Base class for organizing pieces of a FitRecipe.

    RecipeContainers are hierarchical organizations of Parameters and other
    RecipeContainers. This class provides attribute-access to these contained
    objects.  Parameters and other RecipeContainers can be found within the
    hierarchy with the _locateManagedObject method.

    A RecipeContainer can manage dictionaries for that store various objects.
    These dictionaries can be added to the RecipeContainer using the _manage
    method. RecipeContainer methods that add, remove or retrieve objects will
    work with any managed dictionary. This makes it easy to add new types of
    objects to be contained by a RecipeContainer. By default, the
    RecipeContainer is configured to manage an OrderedDict of Parameter
    objects.

    RecipeContainer is an Observable, and observes its managed objects and
    Parameters. This allows hierarchical calculation elements, such as
    ProfileGenerator, to detect changes in Parameters and Restraints on which
    it may depend.

    Attributes
    name            --  A name for this RecipeContainer. Names should be unique
                        within a RecipeContainer and should be valid attribute
                        names.
    _parameters     --  A managed OrderedDict of contained Parameters.
    __managed       --  A list of managed dictionaries. This is used for
                        attribute access, addition and removal.
    _configobjs     --  A set of configurable objects that must know of
                        configuration changes within this object.

    Properties
    names           --  Variable names (read only). See getNames.
    values          --  Variable values (read only). See getValues.
    """

    names = property(lambda self: self.getNames())
    values = property(lambda self: self.getValues())

    def __init__(self, name):
        Observable.__init__(self)
        Configurable.__init__(self)
        validateName(name)
        self.name = name
        self._parameters = OrderedDict()

        self.__managed = []
        self._manage(self._parameters)

        return

    def _manage(self, d):
        """Manage a dictionary of objects.

        This adds the dictionary to the __managed list. Dictionaries in
        __managed are used for attribute access, addition, and removal.
        """
        self.__managed.append(d)
        return

    def _iterManaged(self):
        """Get iterator over managed objects."""
        return chain(*(d.values() for d in self.__managed))

    def iterPars(self, name=".", recurse=True):
        """Iterate over Parameters.

        name    --  Select parameters with this name (regular expression,
                    default ".").
        recurse --  Recurse into managed objects (default True)
        """
        for par in self._parameters.itervalues():
            if re.match(name, par.name):
                yield par

        if not recurse:
            return

        # Iterate over objects within the managed dictionaries.
        managed = self.__managed[:]
        managed.remove(self._parameters)
        for m in managed:
            for obj in m.values():
                if hasattr(obj, "iterPars"):
                    for par in obj.iterPars(name=name):
                        yield par

        return

    def __iter__(self):
        """Iterate over top-level parameters."""
        return self._parameters.itervalues()

    def __len__(self):
        """Get number of top-level parameters."""
        return len(self._parameters)

    def __getitem__(self, idx):
        """Get top-level parameters by index."""
        return self._parameters.values()[idx]
#.........这里部分代码省略.........
开发者ID:kevinrknox,项目名称:diffpy.srfit,代码行数:103,代码来源:recipeorganizer.py

示例3: FitResults

# 需要导入模块: from diffpy.srfit.util.ordereddict import OrderedDict [as 别名]
# 或者: from diffpy.srfit.util.ordereddict.OrderedDict import values [as 别名]
class FitResults(object):
    """Class for processing, presenting and storing results of a fit.

    Attributes
    recipe      --  The recipe containing the results.
    cov         --  The covariance matrix from the recipe.
    conresults  --  An ordered dictionary of ContributionResults for each
                    FitContribution, indexed by the FitContribution name.
    derivstep   --  The fractional step size for calculating numeric
                    derivatives. Default 1e-8.
    varnames    --  Names of the variables in the recipe.
    varvals     --  Values of the variables in the recipe.
    varunc      --  Uncertainties in the variable values.
    showfixed   --  Show fixed variables (default True).
    fixednames  --  Names of the fixed variables of the recipe.
    fixedvals   --  Values of the fixed variables of the recipe.
    showcon     --  Show constraint values in the output (default False).
    connames    --  Names of the constrained parameters.
    convals     --  Values of the constrained parameters.
    conunc      --  Uncertainties in the constraint values.
    residual    --  The scalar residual of the recipe.
    penalty     --  The penalty to residual from the restraints.
    chi2        --  The chi2 of the recipe.
    cumchi2     --  The cumulative chi2 of the recipe.
    rchi2       --  The reduced chi2 of the recipe.
    rw          --  The Rw of the recipe.
    cumrw       --  The cumulative Rw of the recipe.
    messages    --  A list of messages about the results.
    precision   --  The precision of numeric output (default 8).
    _dcon       --  The derivatives of the constraint equations with respect to
                    the variables. This is used internally.

    Each of these attributes, except the recipe, are created or updated when
    the update method is called.

    """

    def __init__(self, recipe, update = True, showfixed = True, showcon =
            False):
        """Initialize the attributes.

        recipe   --  The recipe containing the results
        update  --  Flag indicating whether to do an immediate update (default
                    True).
        showcon --  Show fixed variables in the output (default True).
        showcon --  Show constraint values in the output (default False).

        """
        self.recipe = recipe
        self.conresults = OrderedDict()
        self.derivstep = 1e-8
        self.varnames = []
        self.varvals = []
        self.varunc = []
        self.fixednames = []
        self.fixedvals = []
        self.connames = []
        self.convals = []
        self.conunc = []
        self.cov = None
        self.residual = 0
        self.penalty = 0
        self.chi2 = 0
        self.rchi2 = 0
        self.rw = 0
        self.precision = 8
        self._dcon = []
        self.messages = []

        self.showfixed = bool(showfixed)
        self.showcon = bool(showcon)

        if update:
            self.update()
        return

    def update(self):
        """Update the results according to the current state of the recipe."""
        ## Note that the order of these operations are chosen to reduce
        ## computation time.

        recipe = self.recipe

        if not recipe._contributions:
            return

        # Make sure everything is ready for calculation
        recipe._prepare()

        # Store the variable names and values
        self.varnames = recipe.getNames()
        self.varvals = recipe.getValues()
        fixedpars = recipe._tagmanager.union(recipe._fixedtag)
        fixedpars = [p for p in fixedpars if not p.constrained]
        self.fixednames = [p.name for p in fixedpars]
        self.fixedvals = [p.value for p in fixedpars]

        # Store the constraint information
        self.connames = [con.par.name for con in recipe._oconstraints]
        self.convals = [con.par.getValue() for con in recipe._oconstraints]
#.........这里部分代码省略.........
开发者ID:kevinrknox,项目名称:diffpy.srfit,代码行数:103,代码来源:fitresults.py

示例4: Equation

# 需要导入模块: from diffpy.srfit.util.ordereddict import OrderedDict [as 别名]
# 或者: from diffpy.srfit.util.ordereddict.OrderedDict import values [as 别名]
class Equation(Operator):
    """Class for holding and evaluating a Literal tree.

    Instances have attributes that are the non-const Arguments of the tree
    (accessed by name) and a __call__ method that evaluates the tree.  It is
    assumed, but not enforced that Arguments have unique names.  If this is not
    the case, then one should keep its own list of Arguments.

    The tree is scanned for errors when it is added. Thus, the tree should be
    complete before putting it inside an Equation.

    Equations can act as Operator nodes within a literal tree. In this context,
    they evaluate as the root node, but provide a calling interface that
    accepts new argument values for the literal tree.

    Attributes
    root    --  The root Literal of the equation tree
    argdict --  An OrderedDict of Arguments from the root.
    args    --  Property that gets the values of argdict.

    Operator Attributes
    args    --  List of Literal arguments, set with 'addLiteral'
    name    --  A name for this operator. e.g. "add" or "sin"
    nin     --  Number of inputs (<1 means this is variable)
    nout    --  Number of outputs
    operation   --  Function that performs the operation. e.g. numpy.add.
    symbol  --  The symbolic representation. e.g. "+" or "sin".
    _value  --  The value of the Operator.
    value   --  Property for 'getValue'.

    """

    def __init__(self, name = None, root = None):
        """Initialize.

        name    --  A name for this Equation.
        root    --  The root node of the Literal tree (default None). If root
                    is not passed here, you must call the 'setRoot' method to
                    set or change the root node.

        """
        # Operator stuff. We circumvent Operator.__init__ since we're using
        # args as a property. We cannot set it, as the Operator tries to do.
        if name is None and root is not None:
            name = "eq_%s"%root.name
        Literal.__init__(self, name)
        self.symbol = name
        self.nin = None
        self.nout = 1
        self.operation = self.__call__

        self.root = None
        self.argdict = OrderedDict()
        if root is not None:
            self.setRoot(root)

        return

    def _getArgs(self):
        return self.argdict.values()

    args = property(_getArgs)

    def __getattr__(self, name):
        """Gives access to the Arguments as attributes."""
        arg = self.argdict.get(name)
        if arg is None:
            raise AttributeError("No argument named '%s' here"%name)
        return arg

    def setRoot(self, root):
        """Set the root of the Literal tree.

        Raises:
        ValueError if errors are found in the Literal tree.

        """

        # Validate the new root
        validate(root)

        # Stop observing the old root
        if self.root is not None:
            self.root.removeObserver(self._flush)

        # Add the new root
        self.root = root
        self.root.addObserver(self._flush)
        self._flush(self)

        # Get the args
        args = getArgs(root, getconsts=False)
        self.argdict = OrderedDict( [(arg.name, arg) for arg in args] )

        # Set Operator attributes
        self.nin = len(self.args)

        return

    def __call__(self, *args, **kw):
#.........这里部分代码省略.........
开发者ID:XiaohaoYang,项目名称:diffpy.srfit,代码行数:103,代码来源:equationmod.py

示例5: FitRecipe

# 需要导入模块: from diffpy.srfit.util.ordereddict import OrderedDict [as 别名]
# 或者: from diffpy.srfit.util.ordereddict.OrderedDict import values [as 别名]
class FitRecipe(_fitrecipe_interface, RecipeOrganizer):
    """FitRecipe class.

    Attributes
    name            --  A name for this FitRecipe.
    fithooks        --  List of FitHook instances that can pass information out
                        of the system during a refinement. By default, the is
                        populated by a PrintFitHook instance.
    _constraints    --  A dictionary of Constraints, indexed by the constrained
                        Parameter. Constraints can be added using the
                        'constrain' method.
    _oconstraints   --  An ordered list of the constraints from this and all
                        sub-components.
    _calculators    --  A managed dictionary of Calculators.
    _contributions  --  A managed OrderedDict of FitContributions.
    _parameters     --  A managed OrderedDict of parameters (in this case the
                        parameters are varied).
    _parsets        --  A managed dictionary of ParameterSets.
    _eqfactory      --  A diffpy.srfit.equation.builder.EquationFactory
                        instance that is used to create constraints and
                        restraints from string
    _restraintlist  --  A list of restraints from this and all sub-components.
    _restraints     --  A set of Restraints. Restraints can be added using the
                        'restrain' or 'confine' methods.
    _ready          --  A flag indicating if all attributes are ready for the
                        calculation.
    _tagmanager     --  A TagManager instance for managing tags on Parameters.
    _weights        --  List of weighing factors for each FitContribution. The
                        weights are multiplied by the residual of the
                        FitContribution when determining the overall residual.
    _fixedtag       --  "__fixed", used for tagging variables as fixed. Don't
                        use this tag unless you want issues.

    Properties
    names           --  Variable names (read only). See getNames.
    values          --  Variable values (read only). See getValues.
    fixednames      --  Names of the fixed refinable variables (read only).
    fixedvalues     --  Values of the fixed refinable variables (read only).
    bounds          --  Bounds on parameters (read only). See getBounds.
    bounds2         --  Bounds on parameters (read only). See getBounds2.
    """

    fixednames = property(lambda self:
            [v.name for v in self._parameters.values()
                if not (self.isFree(v) or self.isConstrained(v))],
            doc='names of the fixed refinable variables')
    fixedvalues = property(lambda self:
            array([v.value for v in self._parameters.values()
                if not (self.isFree(v) or self.isConstrained(v))]),
            doc='values of the fixed refinable variables')
    bounds = property(lambda self: self.getBounds())
    bounds2 = property(lambda self: self.getBounds2())

    def __init__(self, name = "fit"):
        """Initialization."""
        RecipeOrganizer.__init__(self, name)
        self.fithooks = []
        self.pushFitHook(PrintFitHook())
        self._restraintlist = []
        self._oconstraints = []
        self._ready = False
        self._fixedtag = "__fixed"

        self._weights = []
        self._tagmanager = TagManager()

        self._parsets = {}
        self._manage(self._parsets)

        self._contributions = OrderedDict()
        self._manage(self._contributions)

        return

    def pushFitHook(self, fithook, index = None):
        """Add a FitHook to be called within the residual method.

        The hook is an object for reporting updates, or more fundamentally,
        passing information out of the system during a refinement. See the
        diffpy.srfit.fitbase.fithook.FitHook class for the required interface.
        Added FitHooks will be called sequentially during refinement.

        fithook --  FitHook instance to add to the sequence
        index   --  Index for inserting fithook into the list of fit hooks.  If
                    this is None (default), the fithook is added to the end.
        """
        if index is None:
            index = len(self.fithooks)
        self.fithooks.insert(index, fithook)
        # Make sure the added FitHook gets its reset method called.
        self._updateConfiguration()
        return

    def popFitHook(self, fithook = None, index = -1):
        """Remove a FitHook by index or reference.

        fithook --  FitHook instance to remove from the sequence. If this is
                    None (default), default to index.
        index   --  Index of FitHook instance to remove (default -1).

#.........这里部分代码省略.........
开发者ID:XiaohaoYang,项目名称:diffpy.srfit,代码行数:103,代码来源:fitrecipe.py


注:本文中的diffpy.srfit.util.ordereddict.OrderedDict.values方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。