本文整理汇总了Python中diffpy.srfit.util.ordereddict.OrderedDict类的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict类的具体用法?Python OrderedDict怎么用?Python OrderedDict使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OrderedDict类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_clear
def test_clear(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
self.assertEqual(len(od), len(pairs))
od.clear()
self.assertEqual(len(od), 0)
示例2: test_delitem
def test_delitem(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
del od['a']
self.assert_('a' not in od)
self.assertRaises(KeyError, od.__delitem__, 'a')
self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
示例3: test_popitem
def test_popitem(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
while pairs:
self.assertEqual(od.popitem(), pairs.pop())
self.assertRaises(KeyError, od.popitem)
self.assertEqual(len(od), 0)
示例4: test_reinsert
def test_reinsert(self):
# Given insert a, insert b, delete a, re-insert a,
# verify that a is now later than b.
od = OrderedDict()
od['a'] = 1
od['b'] = 2
del od['a']
od['a'] = 1
self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])
示例5: test_iterators
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)])
示例6: test_pop
def test_pop(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
shuffle(pairs)
while pairs:
k, v = pairs.pop()
self.assertEqual(od.pop(k), v)
self.assertRaises(KeyError, od.pop, 'xyz')
self.assertEqual(len(od), 0)
self.assertEqual(od.pop(k, 12345), 12345)
示例7: __init__
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
示例8: setRoot
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
示例9: test_init
def test_init(self):
self.assertRaises(TypeError, OrderedDict, ([('a', 1), ('b', 2)], None))
# too many args
pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input
self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input
self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input
self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],
c=3, e=5).items()), pairs) # mixed input
# make sure no positional args conflict with possible kwdargs
self.assertEqual(inspect.getargspec(OrderedDict.__dict__['__init__'])[0],
['self'])
# Make sure that direct calls to __init__ do not clear previous contents
d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
d.__init__([('e', 5), ('f', 6)], g=7, d=4)
self.assertEqual(list(d.items()),
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
示例10: __init__
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
示例11: update
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]
if self.varnames:
# Calculate the covariance
self._calculateCovariance()
# Get the variable uncertainties
self.varunc = [self.cov[i,i]**0.5 for i in \
range(len(self.varnames))]
# Get the constraint uncertainties
self._calculateConstraintUncertainties()
# Store the fitting arrays and metrics for each FitContribution.
self.conresults = OrderedDict()
for con, weight in zip(recipe._contributions.values(), recipe._weights):
self.conresults[con.name] = ContributionResults(con, weight, self)
# Calculate the metrics
res = recipe.residual()
self.residual = numpy.dot(res, res)
self._calculateMetrics()
# Calcualte the restraints penalty
w = self.chi2 / len(res)
self.penalty = sum([res.penalty(w) for res in recipe._restraintlist])
return
示例12: test_setdefault
def test_setdefault(self):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
shuffle(pairs)
od = OrderedDict(pairs)
pair_order = list(od.items())
self.assertEqual(od.setdefault('a', 10), 3)
# make sure order didn't change
self.assertEqual(list(od.items()), pair_order)
self.assertEqual(od.setdefault('x', 10), 10)
# make sure 'x' is added to the end
self.assertEqual(list(od.items())[-1], ('x', 10))
示例13: __init__
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
示例14: __init__
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
示例15: test_copying
def test_copying(self):
# Check that ordered dicts are copyable, deepcopyable, picklable,
# and have a repr/eval round-trip
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
update_test = OrderedDict()
update_test.update(od)
for i, dup in enumerate([
od.copy(),
copy.copy(od),
copy.deepcopy(od),
pickle.loads(pickle.dumps(od, 0)),
pickle.loads(pickle.dumps(od, 1)),
pickle.loads(pickle.dumps(od, 2)),
pickle.loads(pickle.dumps(od, -1)),
eval(repr(od)),
update_test,
OrderedDict(od),
]):
self.assert_(dup is not od)
self.assertEquals(dup, od)
self.assertEquals(list(dup.items()), list(od.items()))
self.assertEquals(len(dup), len(od))
self.assertEquals(type(dup), type(od))