本文整理汇总了Python中itertools.chain方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.chain方法的具体用法?Python itertools.chain怎么用?Python itertools.chain使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.chain方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_training
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def setup_training(self):
'''
Setup Pyro SVI, optimizers.
'''
if not self.is_train:
return
self.pyro_optimizer = optim.Adam({'lr': self.lr_init})
self.svis = {'elbo': SVI(self.model, self.guide, self.pyro_optimizer, loss=Trace_ELBO())}
# Separate pose_model parameters and other networks' parameters
params = []
for name, net in self.nets.items():
if name != 'pose_model':
params.append(net.parameters())
self.optimizer = torch.optim.Adam(\
[{'params': self.pose_model.parameters(), 'lr': self.lr_init},
{'params': itertools.chain(*params), 'lr': self.lr_init}
], betas=(0.5, 0.999))
示例2: CreateWeightLoss
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def CreateWeightLoss(self):
"""Returns L2 loss list of (almost) all variables used inside this block.
When this method needs to be overridden, there are two choices.
1. Override CreateWeightLoss() to change the weight loss of all variables
that belong to this block, both directly and indirectly.
2. Override _CreateWeightLoss() to change the weight loss of all
variables that directly belong to this block but not to the sub-blocks.
Returns:
A Tensor object or None.
"""
losses = list(itertools.chain(
itertools.chain.from_iterable(
t.CreateWeightLoss() for t in self._subblocks),
self._CreateWeightLoss()))
return losses
示例3: sub_spf1
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def sub_spf1(ni, subtree1, subtree2, op, calculate):
"""Implements spf1 single path function for the case when the
other subtree is a single node
Params:
ni -- node indexer for the subtree that has more than one element
subtree1 -- subtree that has a single element
subtree2 -- subtree that has more than one element
op -- cost of deleting/inserting node
calculate -- function(node, other) that returns the cost of
renaming nodes
"""
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
cost = subtree2.sum_cost
max_cost = cost + op
min_ren_minus_op = min(chain([cost], [
calculate(subtree1, info)
for _, info in ni.preorder_ltr(subtree2)
]))
return min(min_ren_minus_op + cost, max_cost)
示例4: forward
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def forward(self, *inputs, **kwargs):
if not self.device_ids:
return self.module(*inputs, **kwargs)
for t in chain(self.module.parameters(), self.module.buffers()):
if t.device != self.src_device_obj:
raise RuntimeError(
"module must have its parameters and buffers "
"on device {} (device_ids[0]) but found one of "
"them on device: {}".format(
self.src_device_obj, t.device))
inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
if len(self.device_ids) == 1:
return self.module(*inputs, **kwargs)
replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
outputs = self.parallel_apply(replicas, inputs, kwargs)
return outputs
示例5: update_template_context
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.template_context_processors[None]
if has_request_context():
blueprint = _request_ctx_stack.top.request.blueprint
if blueprint is not None and blueprint in self.template_context_processors:
processors = chain( # type: ignore
processors, self.template_context_processors[blueprint]
)
extra_context: dict = {}
for processor in processors:
extra_context.update(await processor())
original = context.copy()
context.update(extra_context)
context.update(original)
示例6: do_teardown_request
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def do_teardown_request(
self, exc: Optional[BaseException], request_context: Optional[RequestContext] = None
) -> None:
"""Teardown the request, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the request
to teardown.
request_context: The request context, optional as Flask
omits this argument.
"""
request_ = (request_context or _request_ctx_stack.top).request
functions = self.teardown_request_funcs[None]
blueprint = request_.blueprint
if blueprint is not None:
functions = chain(functions, self.teardown_request_funcs[blueprint]) # type: ignore
for function in functions:
await function(exc)
await request_tearing_down.send(self, exc=exc)
示例7: do_teardown_websocket
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def do_teardown_websocket(
self, exc: Optional[BaseException], websocket_context: Optional[WebsocketContext] = None
) -> None:
"""Teardown the websocket, calling the teardown functions.
Arguments:
exc: Any exception not handled that has caused the websocket
to teardown.
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket
functions = self.teardown_websocket_funcs[None]
blueprint = websocket_.blueprint
if blueprint is not None:
functions = chain(functions, self.teardown_websocket_funcs[blueprint]) # type: ignore
for function in functions:
await function(exc)
await websocket_tearing_down.send(self, exc=exc)
示例8: preprocess_request
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def preprocess_request(
self, request_context: Optional[RequestContext] = None
) -> Optional[ResponseReturnValue]:
"""Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
request_ = (request_context or _request_ctx_stack.top).request
blueprint = request_.blueprint
processors = self.url_value_preprocessors[None]
if blueprint is not None:
processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore
for processor in processors:
processor(request.endpoint, request.view_args)
functions = self.before_request_funcs[None]
if blueprint is not None:
functions = chain(functions, self.before_request_funcs[blueprint]) # type: ignore
for function in functions:
result = await function()
if result is not None:
return result
return None
示例9: preprocess_websocket
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def preprocess_websocket(
self, websocket_context: Optional[WebsocketContext] = None
) -> Optional[ResponseReturnValue]:
"""Preprocess the websocket i.e. call before_websocket functions.
Arguments:
websocket_context: The websocket context, optional as Flask
omits this argument.
"""
websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket
blueprint = websocket_.blueprint
processors = self.url_value_preprocessors[None]
if blueprint is not None:
processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore
for processor in processors:
processor(websocket_.endpoint, websocket_.view_args)
functions = self.before_websocket_funcs[None]
if blueprint is not None:
functions = chain(functions, self.before_websocket_funcs[blueprint]) # type: ignore
for function in functions:
result = await function()
if result is not None:
return result
return None
示例10: point_entropy
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def point_entropy(self, unlabeled_sequence):
"""
Returns the pointwise entropy over the possible states at each
position in the chain, given the observation sequence.
"""
unlabeled_sequence = self._transform(unlabeled_sequence)
T = len(unlabeled_sequence)
N = len(self._states)
alpha = self._forward_probability(unlabeled_sequence)
beta = self._backward_probability(unlabeled_sequence)
normalisation = logsumexp2(alpha[T-1])
entropies = np.zeros(T, np.float64)
probs = np.zeros(N, np.float64)
for t in range(T):
for s in range(N):
probs[s] = alpha[t, s] + beta[t, s] - normalisation
for s in range(N):
entropies[t] -= 2**(probs[s]) * probs[s]
return entropies
示例11: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def __init__(
self, geom, debug=False, restart=None, maxsteps=100, logger=None, **params
):
self._debug = debug
self._maxsteps = maxsteps
self._converged = False
self._n = 0
self._log = BernyAdapter(logger or log, {'step': self._n})
s = self._state = Berny.State()
if restart:
vars(s).update(restart)
return
s.geom = geom
s.params = dict(chain(defaults.items(), params.items()))
s.trust = s.params['trust']
s.coords = InternalCoords(
s.geom, dihedral=s.params['dihedral'], superweakdih=s.params['superweakdih']
)
s.H = s.coords.hessian_guess(s.geom)
s.weights = s.coords.weights(s.geom)
s.future = Berny.Point(s.coords.eval_geom(s.geom), None, None)
s.first = True
for line in str(s.coords).split('\n'):
self._log.info(line)
示例12: get_attribute_suggestions
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def get_attribute_suggestions(type_str, attribute, frame):
"""Get the suggestions closest to the attribute name for a given type."""
types = get_types_for_str(type_str, frame)
attributes = set(a for t in types for a in dir(t))
if type_str == 'module':
# For module, we manage to get the corresponding 'module' type
# but the type doesn't bring much information about its content.
# A hacky way to do so is to assume that the exception was something
# like 'module_name.attribute' so that we can actually find the module
# based on the name. Eventually, we check that the found object is a
# module indeed. This is not failproof but it brings a whole lot of
# interesting suggestions and the (minimal) risk is to have invalid
# suggestions.
module_name = frame.f_code.co_names[0]
objs = get_objects_in_frame(frame)
mod = objs[module_name][0].obj
if inspect.ismodule(mod):
attributes = set(dir(mod))
return itertools.chain(
suggest_attribute_as_builtin(attribute, type_str, frame),
suggest_attribute_alternative(attribute, type_str, attributes),
suggest_attribute_as_typo(attribute, attributes),
suggest_attribute_as_special_case(attribute))
示例13: process
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def process(parser, widget_dict):
mutually_exclusive_groups = [
[mutex_action for mutex_action in group_actions._group_actions]
for group_actions in parser._mutually_exclusive_groups]
group_options = list(chain(*mutually_exclusive_groups))
base_actions = [action for action in parser._actions
if action not in group_options
and action.dest != 'help']
required_actions = filter(is_required, base_actions)
optional_actions = filter(is_optional, base_actions)
return list(categorize(required_actions, widget_dict, required=True)) + \
list(categorize(optional_actions, widget_dict)) + \
map(build_radio_group, mutually_exclusive_groups)
示例14: _wait_for_volumes_deleted
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def _wait_for_volumes_deleted(self, context, volmaps, container,
timeout=60, poll_interval=1):
start_time = time.time()
try:
volmaps = itertools.chain(volmaps)
volmap = next(volmaps)
while time.time() - start_time < timeout:
if not volmap.auto_remove:
volmap = next(volmaps)
driver = self._get_driver(container)
is_deleted, is_error = driver.is_volume_deleted(
context, volmap)
if is_deleted:
volmap = next(volmaps)
if is_error:
break
time.sleep(poll_interval)
except StopIteration:
return
msg = _("Volumes cannot be successfully deleted after "
"%d seconds") % (timeout)
self._fail_container(context, container, msg, unset_host=True)
raise exception.Conflict(msg)
示例15: __iter__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import chain [as 别名]
def __iter__(self):
alists = []
for var in self.varieties_iter():
alists.append(self.vars[var]["agents"])
# create an iterator that chains the lists together as if one:
return itertools.chain(*alists)