本文整理汇总了Python中itertools.product方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.product方法的具体用法?Python itertools.product怎么用?Python itertools.product使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.product方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tasks
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def tasks(args):
list_clusters = clients.ecs.get_paginator("list_clusters")
list_tasks = clients.ecs.get_paginator("list_tasks")
def list_tasks_worker(worker_args):
cluster, status = worker_args
return cluster, status, list(paginate(list_tasks, cluster=cluster, desiredStatus=status))
def describe_tasks_worker(t, cluster=None):
return clients.ecs.describe_tasks(cluster=cluster, tasks=t)["tasks"] if t else []
task_descs = []
if args.clusters is None:
args.clusters = [__name__.replace(".", "_")] if args.tasks else list(paginate(list_clusters))
if args.tasks:
task_descs = describe_tasks_worker(args.tasks, cluster=args.clusters[0])
else:
with ThreadPoolExecutor() as executor:
for cluster, status, tasks in executor.map(list_tasks_worker, product(args.clusters, args.desired_status)):
worker = partial(describe_tasks_worker, cluster=cluster)
descs = executor.map(worker, (tasks[pos:pos + 100] for pos in range(0, len(tasks), 100)))
task_descs += sum(descs, [])
page_output(tabulate(task_descs, args))
示例2: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def __init__(self, width, height, depth, rand_max, table=None):
self.toroidal = True
self._rand_max = rand_max
if table:
self.table = table
self.depth = len(table)
self.height = len(table[0])
self.width = len(table[0][0])
else:
self.height = height
self.width = width
self.depth = depth
self.genNewTable()
self._oldStates = deque()
for i in range(3):
self._oldStates.append([])
self.offsets = list(itertools.product([-1, 0, 1], repeat=3))
self.offsets.remove((0, 0, 0)) # remove center point
示例3: test_max_pool_2d
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_max_pool_2d():
test_cases = OrderedDict([('in_w', [10, 20]), ('in_h', [10, 20]),
('in_channel', [1, 3]), ('out_channel', [1, 3]),
('kernel_size', [3, 5]), ('stride', [1, 2]),
('padding', [0, 1]), ('dilation', [1, 2])])
for in_h, in_w, in_cha, out_cha, k, s, p, d in product(
*list(test_cases.values())):
# wrapper op with 0-dim input
x_empty = torch.randn(0, in_cha, in_h, in_w, requires_grad=True)
wrapper = MaxPool2d(k, stride=s, padding=p, dilation=d)
wrapper_out = wrapper(x_empty)
# torch op with 3-dim input as shape reference
x_normal = torch.randn(3, in_cha, in_h, in_w)
ref = nn.MaxPool2d(k, stride=s, padding=p, dilation=d)
ref_out = ref(x_normal)
assert wrapper_out.shape[0] == 0
assert wrapper_out.shape[1:] == ref_out.shape[1:]
assert torch.equal(wrapper(x_normal), ref_out)
示例4: init_from_dataset_and_submissions_write_to_datastore
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def init_from_dataset_and_submissions_write_to_datastore(
self, dataset_batches, attack_submission_ids):
"""Init list of adversarial batches from dataset batches and submissions.
Args:
dataset_batches: instances of DatasetBatches
attack_submission_ids: iterable with IDs of all (targeted and nontargeted)
attack submissions, could be obtains as
CompetitionSubmissions.get_all_attack_ids()
"""
batches_x_attacks = itertools.product(dataset_batches.data.keys(),
attack_submission_ids)
for idx, (dataset_batch_id, attack_id) in enumerate(batches_x_attacks):
adv_batch_id = ADVERSARIAL_BATCH_ID_PATTERN.format(idx)
self.add_batch(adv_batch_id,
{'dataset_batch_id': dataset_batch_id,
'submission_id': attack_id})
self.write_to_datastore()
示例5: share
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def share(self, users):
"""
Ensures self is shared with given users (can accept users who are
already shared on self).
"""
users = [u for u in users if not self.shared_with(user=u)]
if users:
members = [self] + self.members(direct=False)
FM, DM = self.shared_user_model(), Document.shared_user_model()
fm, dm = [], []
for member, user in itertools.product(members, users):
if user.pk == member.author_id:
continue
if isinstance(member, Folder):
fm.append(FM(**{FM.obj_attr: member, "user": user}))
if isinstance(member, Document):
dm.append(DM(**{DM.obj_attr: member, "user": user}))
FM._default_manager.bulk_create(fm)
DM._default_manager.bulk_create(dm)
示例6: main
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def main():
# testing configurations
cell_types = [gluon.rnn.RNNCell,
gluon.rnn.GRUCell,
gluon.rnn.LSTMCell]
ctxs = [mx.cpu(0)]
if args.gpu:
ctxs = ctxs + [mx.gpu(i) for i in _get_gpus()]
seq_lens = [100]
batch_sizes = [1, 32]
hidden_dims = [512]
print("--------------------------------------")
print("Benchmarking", args.benchmark)
for cell_type, ctx, seq_len, batch_size, hidden_dim in product( \
cell_types, ctxs, seq_lens, batch_sizes, hidden_dims):
print("--------------------------------------")
print("cell: %s ctx: %s length: %d batch size: %d dim: %d" % \
(cell_type.__name__, str(ctx), seq_len, batch_size, hidden_dim))
run_benchmark(cell_type, ctx, seq_len, batch_size, hidden_dim)
示例7: _is_close_to_existing_points
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def _is_close_to_existing_points(self, point):
"""Checks if the point is close to any already sampled (and stored) points.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
True iff the distance of the point to any existing points is smaller than
the min_radius
"""
px, py = self._point_to_index_2d(point)
# Now we can check nearby cells for existing points
for neighbor_cell in itertools.product(
xrange(px - 1, px + 2), xrange(py - 1, py + 2)):
if not self._is_in_range(neighbor_cell):
continue
maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)]
if maybe_a_point is not None and np.linalg.norm(
maybe_a_point - point) < self._min_radius:
return True
return False
示例8: test_circuit_generation_and_accuracy
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_circuit_generation_and_accuracy():
for dim in range(2, 10):
qubits = cirq.LineQubit.range(dim)
u_generator = numpy.random.random(
(dim, dim)) + 1j * numpy.random.random((dim, dim))
u_generator = u_generator - numpy.conj(u_generator).T
assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)
unitary = scipy.linalg.expm(u_generator)
circuit = cirq.Circuit()
circuit.append(optimal_givens_decomposition(qubits, unitary))
fermion_generator = QubitOperator(()) * 0.0
for i, j in product(range(dim), repeat=2):
fermion_generator += jordan_wigner(
FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))
true_unitary = scipy.linalg.expm(
get_sparse_operator(fermion_generator).toarray())
assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
numpy.eye(2 ** dim, dtype=complex))
test_unitary = cirq.unitary(circuit)
assert numpy.isclose(
abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
示例9: get_matrix_of_eigs
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def get_matrix_of_eigs(w: np.ndarray) -> np.ndarray:
"""
Transform the eigenvalues for getting the gradient
.. math:
f(w) \rightarrow \frac{e^{i (\lambda_{i} - \lambda_{j})}{i (\lambda_{i} - \lambda_{j})}
:param w: eigenvalues of C-matrix
:return: new array of transformed eigenvalues
"""
transform_eigs = np.zeros((w.shape[0], w.shape[0]),
dtype=np.complex128)
for i, j in product(range(w.shape[0]), repeat=2):
if np.isclose(abs(w[i] - w[j]), 0):
transform_eigs[i, j] = 1
else:
transform_eigs[i, j] = (np.exp(1j * (w[i] - w[j])) - 1) / (
1j * (w[i] - w[j]))
return transform_eigs
示例10: test_get_matrix_of_eigs
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_get_matrix_of_eigs():
"""
Generate the matrix of [exp(i (li - lj)) - 1] / (i(li - lj)
:return:
"""
lam_vals = np.random.randn(4) + 1j * np.random.randn(4)
mat_eigs = np.zeros((lam_vals.shape[0],
lam_vals.shape[0]),
dtype=np.complex128)
for i, j in product(range(lam_vals.shape[0]), repeat=2):
if np.isclose(abs(lam_vals[i] - lam_vals[j]), 0):
mat_eigs[i, j] = 1
else:
mat_eigs[i, j] = (np.exp(1j * (lam_vals[i] - lam_vals[j])) - 1) / (
1j * (lam_vals[i] - lam_vals[j]))
test_mat_eigs = get_matrix_of_eigs(lam_vals)
assert np.allclose(test_mat_eigs, mat_eigs)
示例11: test_matrix_2_tensor
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_matrix_2_tensor():
dim = 10
np.random.seed(42)
mat = np.random.random((dim**2, dim**2))
mat = 0.5 * (mat + mat.T)
tensor = map_to_tensor(mat)
for p, q, r, s in product(range(dim), repeat=4):
assert np.isclose(tensor[p, q, r, s], mat[p * dim + q, r * dim + s])
test_mat = map_to_matrix(tensor)
assert np.allclose(test_mat, mat)
with pytest.raises(TypeError):
map_to_tensor(np.zeros((4, 4, 4, 4)))
with pytest.raises(TypeError):
map_to_matrix(np.zeros((4, 4)))
示例12: test_basic_use
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_basic_use(self, simple_linear_model):
""" Test the basic use of `ConstantParameter` using the Python API """
model = simple_linear_model
# Add two scenarios
scA = Scenario(model, 'Scenario A', size=2)
scB = Scenario(model, 'Scenario B', size=5)
p = ConstantParameter(model, np.pi, name='pi', comment='Mmmmm Pi!')
assert not p.is_variable
assert p.double_size == 1
assert p.integer_size == 0
model.setup()
ts = model.timestepper.current
# Now ensure the appropriate value is returned for all scenarios
for i, (a, b) in enumerate(itertools.product(range(scA.size), range(scB.size))):
si = ScenarioIndex(i, np.array([a, b], dtype=np.int32))
np.testing.assert_allclose(p.value(ts, si), np.pi)
示例13: test_parameter_constant_scenario
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_parameter_constant_scenario(simple_linear_model):
"""
Test ConstantScenarioParameter
"""
model = simple_linear_model
# Add two scenarios
scA = Scenario(model, 'Scenario A', size=2)
scB = Scenario(model, 'Scenario B', size=5)
p = ConstantScenarioParameter(model, scB, np.arange(scB.size, dtype=np.float64))
model.setup()
ts = model.timestepper.current
# Now ensure the appropriate value is returned for the Scenario B indices.
for i, (a, b) in enumerate(itertools.product(range(scA.size), range(scB.size))):
si = ScenarioIndex(i, np.array([a, b], dtype=np.int32))
np.testing.assert_allclose(p.value(ts, si), float(b))
示例14: test_load
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def test_load(self, simple_linear_model):
""" Test load from JSON dict"""
model = simple_linear_model
data = {
"type": "aggregated",
"agg_func": "product",
"parameters": [
0.8,
{
"type": "monthlyprofile",
"values": list(range(12))
}
]
}
p = load_parameter(model, data)
# Correct instance is loaded
assert isinstance(p, AggregatedParameter)
@assert_rec(model, p)
def expected(timestep, scenario_index):
return (timestep.month - 1) * 0.8
model.run()
示例15: _match_with_bipartite
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import product [as 别名]
def _match_with_bipartite(
self,
subject_ids: MultisetOfInt,
pattern_set: MultisetOfInt,
substitution: Substitution,
) -> Iterator[Tuple[Substitution, MultisetOfInt]]:
bipartite = self._build_bipartite(subject_ids, pattern_set)
for matching in enum_maximum_matchings_iter(bipartite):
if len(matching) < len(pattern_set):
break
if not self._is_canonical_matching(matching):
continue
for substs in itertools.product(*(bipartite[edge] for edge in matching.items())):
try:
bipartite_substitution = substitution.union(*substs)
except ValueError:
continue
matched_subjects = Multiset(subexpression for subexpression, _ in matching)
yield bipartite_substitution, matched_subjects