repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
rigetti/quantumflow | quantumflow/measures.py | mutual_info | def mutual_info(rho: Density,
qubits0: Qubits,
qubits1: Qubits = None,
base: float = None) -> float:
"""Compute the bipartite von-Neumann mutual information of a mixed
quantum state.
Args:
rho: A density matrix of the complete system
qubits0: Qubits of system 0
qubits1: Qubits of system 1. If none, taken to be all remaining qubits
base: Optional logarithm base. Default is base e
Returns:
The bipartite von-Neumann mutual information.
"""
if qubits1 is None:
qubits1 = tuple(set(rho.qubits) - set(qubits0))
rho0 = rho.partial_trace(qubits1)
rho1 = rho.partial_trace(qubits0)
ent = entropy(rho, base)
ent0 = entropy(rho0, base)
ent1 = entropy(rho1, base)
return ent0 + ent1 - ent | python | def mutual_info(rho: Density,
qubits0: Qubits,
qubits1: Qubits = None,
base: float = None) -> float:
"""Compute the bipartite von-Neumann mutual information of a mixed
quantum state.
Args:
rho: A density matrix of the complete system
qubits0: Qubits of system 0
qubits1: Qubits of system 1. If none, taken to be all remaining qubits
base: Optional logarithm base. Default is base e
Returns:
The bipartite von-Neumann mutual information.
"""
if qubits1 is None:
qubits1 = tuple(set(rho.qubits) - set(qubits0))
rho0 = rho.partial_trace(qubits1)
rho1 = rho.partial_trace(qubits0)
ent = entropy(rho, base)
ent0 = entropy(rho0, base)
ent1 = entropy(rho1, base)
return ent0 + ent1 - ent | [
"def",
"mutual_info",
"(",
"rho",
":",
"Density",
",",
"qubits0",
":",
"Qubits",
",",
"qubits1",
":",
"Qubits",
"=",
"None",
",",
"base",
":",
"float",
"=",
"None",
")",
"->",
"float",
":",
"if",
"qubits1",
"is",
"None",
":",
"qubits1",
"=",
"tuple",... | Compute the bipartite von-Neumann mutual information of a mixed
quantum state.
Args:
rho: A density matrix of the complete system
qubits0: Qubits of system 0
qubits1: Qubits of system 1. If none, taken to be all remaining qubits
base: Optional logarithm base. Default is base e
Returns:
The bipartite von-Neumann mutual information. | [
"Compute",
"the",
"bipartite",
"von",
"-",
"Neumann",
"mutual",
"information",
"of",
"a",
"mixed",
"quantum",
"state",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L152-L178 | train | 229,700 |
rigetti/quantumflow | quantumflow/measures.py | gate_angle | def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor:
"""The Fubini-Study angle between gates"""
return fubini_study_angle(gate0.vec, gate1.vec) | python | def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor:
"""The Fubini-Study angle between gates"""
return fubini_study_angle(gate0.vec, gate1.vec) | [
"def",
"gate_angle",
"(",
"gate0",
":",
"Gate",
",",
"gate1",
":",
"Gate",
")",
"->",
"bk",
".",
"BKTensor",
":",
"return",
"fubini_study_angle",
"(",
"gate0",
".",
"vec",
",",
"gate1",
".",
"vec",
")"
] | The Fubini-Study angle between gates | [
"The",
"Fubini",
"-",
"Study",
"angle",
"between",
"gates"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L183-L185 | train | 229,701 |
rigetti/quantumflow | quantumflow/measures.py | channel_angle | def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor:
"""The Fubini-Study angle between channels"""
return fubini_study_angle(chan0.vec, chan1.vec) | python | def channel_angle(chan0: Channel, chan1: Channel) -> bk.BKTensor:
"""The Fubini-Study angle between channels"""
return fubini_study_angle(chan0.vec, chan1.vec) | [
"def",
"channel_angle",
"(",
"chan0",
":",
"Channel",
",",
"chan1",
":",
"Channel",
")",
"->",
"bk",
".",
"BKTensor",
":",
"return",
"fubini_study_angle",
"(",
"chan0",
".",
"vec",
",",
"chan1",
".",
"vec",
")"
] | The Fubini-Study angle between channels | [
"The",
"Fubini",
"-",
"Study",
"angle",
"between",
"channels"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L199-L201 | train | 229,702 |
rigetti/quantumflow | quantumflow/qubits.py | inner_product | def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor:
""" Hilbert-Schmidt inner product between qubit vectors
The tensor rank and qubits must match.
"""
if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb:
raise ValueError('Incompatibly vectors. Qubits and rank must match')
vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order
return bk.inner(vec0.tensor, vec1.tensor) | python | def inner_product(vec0: QubitVector, vec1: QubitVector) -> bk.BKTensor:
""" Hilbert-Schmidt inner product between qubit vectors
The tensor rank and qubits must match.
"""
if vec0.rank != vec1.rank or vec0.qubit_nb != vec1.qubit_nb:
raise ValueError('Incompatibly vectors. Qubits and rank must match')
vec1 = vec1.permute(vec0.qubits) # Make sure qubits in same order
return bk.inner(vec0.tensor, vec1.tensor) | [
"def",
"inner_product",
"(",
"vec0",
":",
"QubitVector",
",",
"vec1",
":",
"QubitVector",
")",
"->",
"bk",
".",
"BKTensor",
":",
"if",
"vec0",
".",
"rank",
"!=",
"vec1",
".",
"rank",
"or",
"vec0",
".",
"qubit_nb",
"!=",
"vec1",
".",
"qubit_nb",
":",
... | Hilbert-Schmidt inner product between qubit vectors
The tensor rank and qubits must match. | [
"Hilbert",
"-",
"Schmidt",
"inner",
"product",
"between",
"qubit",
"vectors"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L233-L242 | train | 229,703 |
rigetti/quantumflow | quantumflow/qubits.py | outer_product | def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector:
"""Direct product of qubit vectors
The tensor ranks must match and qubits must be disjoint.
"""
R = vec0.rank
R1 = vec1.rank
N0 = vec0.qubit_nb
N1 = vec1.qubit_nb
if R != R1:
raise ValueError('Incompatibly vectors. Rank must match')
if not set(vec0.qubits).isdisjoint(vec1.qubits):
raise ValueError('Overlapping qubits')
qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits)
tensor = bk.outer(vec0.tensor, vec1.tensor)
# Interleave (super)-operator axes
# R = 1 perm = (0, 1)
# R = 2 perm = (0, 2, 1, 3)
# R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7)
tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R))
perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij]
tensor = bk.transpose(tensor, perm)
return QubitVector(tensor, qubits) | python | def outer_product(vec0: QubitVector, vec1: QubitVector) -> QubitVector:
"""Direct product of qubit vectors
The tensor ranks must match and qubits must be disjoint.
"""
R = vec0.rank
R1 = vec1.rank
N0 = vec0.qubit_nb
N1 = vec1.qubit_nb
if R != R1:
raise ValueError('Incompatibly vectors. Rank must match')
if not set(vec0.qubits).isdisjoint(vec1.qubits):
raise ValueError('Overlapping qubits')
qubits: Qubits = tuple(vec0.qubits) + tuple(vec1.qubits)
tensor = bk.outer(vec0.tensor, vec1.tensor)
# Interleave (super)-operator axes
# R = 1 perm = (0, 1)
# R = 2 perm = (0, 2, 1, 3)
# R = 4 perm = (0, 4, 1, 5, 2, 6, 3, 7)
tensor = bk.reshape(tensor, ([2**N0] * R) + ([2**N1] * R))
perm = [idx for ij in zip(range(0, R), range(R, 2*R)) for idx in ij]
tensor = bk.transpose(tensor, perm)
return QubitVector(tensor, qubits) | [
"def",
"outer_product",
"(",
"vec0",
":",
"QubitVector",
",",
"vec1",
":",
"QubitVector",
")",
"->",
"QubitVector",
":",
"R",
"=",
"vec0",
".",
"rank",
"R1",
"=",
"vec1",
".",
"rank",
"N0",
"=",
"vec0",
".",
"qubit_nb",
"N1",
"=",
"vec1",
".",
"qubit... | Direct product of qubit vectors
The tensor ranks must match and qubits must be disjoint. | [
"Direct",
"product",
"of",
"qubit",
"vectors"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L248-L277 | train | 229,704 |
rigetti/quantumflow | quantumflow/qubits.py | vectors_close | def vectors_close(vec0: QubitVector, vec1: QubitVector,
tolerance: float = TOLERANCE) -> bool:
"""Return True if vectors in close in the projective Hilbert space.
Similarity is measured with the Fubini–Study metric.
"""
if vec0.rank != vec1.rank:
return False
if vec0.qubit_nb != vec1.qubit_nb:
return False
if set(vec0.qubits) ^ set(vec1.qubits):
return False
return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance | python | def vectors_close(vec0: QubitVector, vec1: QubitVector,
tolerance: float = TOLERANCE) -> bool:
"""Return True if vectors in close in the projective Hilbert space.
Similarity is measured with the Fubini–Study metric.
"""
if vec0.rank != vec1.rank:
return False
if vec0.qubit_nb != vec1.qubit_nb:
return False
if set(vec0.qubits) ^ set(vec1.qubits):
return False
return bk.evaluate(fubini_study_angle(vec0, vec1)) <= tolerance | [
"def",
"vectors_close",
"(",
"vec0",
":",
"QubitVector",
",",
"vec1",
":",
"QubitVector",
",",
"tolerance",
":",
"float",
"=",
"TOLERANCE",
")",
"->",
"bool",
":",
"if",
"vec0",
".",
"rank",
"!=",
"vec1",
".",
"rank",
":",
"return",
"False",
"if",
"vec... | Return True if vectors in close in the projective Hilbert space.
Similarity is measured with the Fubini–Study metric. | [
"Return",
"True",
"if",
"vectors",
"in",
"close",
"in",
"the",
"projective",
"Hilbert",
"space",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L310-L325 | train | 229,705 |
rigetti/quantumflow | quantumflow/qubits.py | QubitVector.flatten | def flatten(self) -> bk.BKTensor:
"""Return tensor with with qubit indices flattened"""
N = self.qubit_nb
R = self.rank
return bk.reshape(self.tensor, [2**N]*R) | python | def flatten(self) -> bk.BKTensor:
"""Return tensor with with qubit indices flattened"""
N = self.qubit_nb
R = self.rank
return bk.reshape(self.tensor, [2**N]*R) | [
"def",
"flatten",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"R",
"=",
"self",
".",
"rank",
"return",
"bk",
".",
"reshape",
"(",
"self",
".",
"tensor",
",",
"[",
"2",
"**",
"N",
"]",
"*",
"R",
")"
] | Return tensor with with qubit indices flattened | [
"Return",
"tensor",
"with",
"with",
"qubit",
"indices",
"flattened"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L131-L135 | train | 229,706 |
rigetti/quantumflow | quantumflow/qubits.py | QubitVector.relabel | def relabel(self, qubits: Qubits) -> 'QubitVector':
"""Return a copy of this vector with new qubits"""
qubits = tuple(qubits)
assert len(qubits) == self.qubit_nb
vec = copy(self)
vec.qubits = qubits
return vec | python | def relabel(self, qubits: Qubits) -> 'QubitVector':
"""Return a copy of this vector with new qubits"""
qubits = tuple(qubits)
assert len(qubits) == self.qubit_nb
vec = copy(self)
vec.qubits = qubits
return vec | [
"def",
"relabel",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'QubitVector'",
":",
"qubits",
"=",
"tuple",
"(",
"qubits",
")",
"assert",
"len",
"(",
"qubits",
")",
"==",
"self",
".",
"qubit_nb",
"vec",
"=",
"copy",
"(",
"self",
")",
"vec",... | Return a copy of this vector with new qubits | [
"Return",
"a",
"copy",
"of",
"this",
"vector",
"with",
"new",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L137-L143 | train | 229,707 |
rigetti/quantumflow | quantumflow/qubits.py | QubitVector.H | def H(self) -> 'QubitVector':
"""Return the conjugate transpose of this tensor."""
N = self.qubit_nb
R = self.rank
# (super) operator transpose
tensor = self.tensor
tensor = bk.reshape(tensor, [2**(N*R//2)] * 2)
tensor = bk.transpose(tensor)
tensor = bk.reshape(tensor, [2] * R * N)
tensor = bk.conj(tensor)
return QubitVector(tensor, self.qubits) | python | def H(self) -> 'QubitVector':
"""Return the conjugate transpose of this tensor."""
N = self.qubit_nb
R = self.rank
# (super) operator transpose
tensor = self.tensor
tensor = bk.reshape(tensor, [2**(N*R//2)] * 2)
tensor = bk.transpose(tensor)
tensor = bk.reshape(tensor, [2] * R * N)
tensor = bk.conj(tensor)
return QubitVector(tensor, self.qubits) | [
"def",
"H",
"(",
"self",
")",
"->",
"'QubitVector'",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"R",
"=",
"self",
".",
"rank",
"# (super) operator transpose",
"tensor",
"=",
"self",
".",
"tensor",
"tensor",
"=",
"bk",
".",
"reshape",
"(",
"tensor",
",",
"... | Return the conjugate transpose of this tensor. | [
"Return",
"the",
"conjugate",
"transpose",
"of",
"this",
"tensor",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L165-L178 | train | 229,708 |
rigetti/quantumflow | quantumflow/qubits.py | QubitVector.norm | def norm(self) -> bk.BKTensor:
"""Return the norm of this vector"""
return bk.absolute(bk.inner(self.tensor, self.tensor)) | python | def norm(self) -> bk.BKTensor:
"""Return the norm of this vector"""
return bk.absolute(bk.inner(self.tensor, self.tensor)) | [
"def",
"norm",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"return",
"bk",
".",
"absolute",
"(",
"bk",
".",
"inner",
"(",
"self",
".",
"tensor",
",",
"self",
".",
"tensor",
")",
")"
] | Return the norm of this vector | [
"Return",
"the",
"norm",
"of",
"this",
"vector"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L180-L182 | train | 229,709 |
rigetti/quantumflow | quantumflow/qubits.py | QubitVector.partial_trace | def partial_trace(self, qubits: Qubits) -> 'QubitVector':
"""
Return the partial trace over some subset of qubits"""
N = self.qubit_nb
R = self.rank
if R == 1:
raise ValueError('Cannot take trace of vector')
new_qubits: List[Qubit] = list(self.qubits)
for q in qubits:
new_qubits.remove(q)
if not new_qubits:
raise ValueError('Cannot remove all qubits with partial_trace.')
indices = [self.qubits.index(qubit) for qubit in qubits]
subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R]
for idx in indices:
for r in range(1, R):
subscripts[r * N + idx] = subscripts[idx]
subscript_str = ''.join(subscripts)
# Only numpy's einsum works with repeated subscripts
tensor = self.asarray()
tensor = np.einsum(subscript_str, tensor)
return QubitVector(tensor, new_qubits) | python | def partial_trace(self, qubits: Qubits) -> 'QubitVector':
"""
Return the partial trace over some subset of qubits"""
N = self.qubit_nb
R = self.rank
if R == 1:
raise ValueError('Cannot take trace of vector')
new_qubits: List[Qubit] = list(self.qubits)
for q in qubits:
new_qubits.remove(q)
if not new_qubits:
raise ValueError('Cannot remove all qubits with partial_trace.')
indices = [self.qubits.index(qubit) for qubit in qubits]
subscripts = list(EINSUM_SUBSCRIPTS)[0:N*R]
for idx in indices:
for r in range(1, R):
subscripts[r * N + idx] = subscripts[idx]
subscript_str = ''.join(subscripts)
# Only numpy's einsum works with repeated subscripts
tensor = self.asarray()
tensor = np.einsum(subscript_str, tensor)
return QubitVector(tensor, new_qubits) | [
"def",
"partial_trace",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'QubitVector'",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"R",
"=",
"self",
".",
"rank",
"if",
"R",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"'Cannot take trace of vector'",
... | Return the partial trace over some subset of qubits | [
"Return",
"the",
"partial",
"trace",
"over",
"some",
"subset",
"of",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qubits.py#L201-L227 | train | 229,710 |
rigetti/quantumflow | examples/tensorflow2_fit_gate.py | fit_zyz | def fit_zyz(target_gate):
"""
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
steps = 1000
dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0'
with tf.device(dev):
t = tf.Variable(tf.random.normal([3]))
def loss_fn():
"""Loss"""
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
return ang
opt = tf.optimizers.Adam(learning_rate=0.001)
opt.minimize(loss_fn, var_list=[t])
for step in range(steps):
opt.minimize(loss_fn, var_list=[t])
loss = loss_fn()
print(step, loss.numpy())
if loss < 0.01:
break
else:
print("Failed to coverge")
return bk.evaluate(t) | python | def fit_zyz(target_gate):
"""
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
steps = 1000
dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0'
with tf.device(dev):
t = tf.Variable(tf.random.normal([3]))
def loss_fn():
"""Loss"""
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
return ang
opt = tf.optimizers.Adam(learning_rate=0.001)
opt.minimize(loss_fn, var_list=[t])
for step in range(steps):
opt.minimize(loss_fn, var_list=[t])
loss = loss_fn()
print(step, loss.numpy())
if loss < 0.01:
break
else:
print("Failed to coverge")
return bk.evaluate(t) | [
"def",
"fit_zyz",
"(",
"target_gate",
")",
":",
"steps",
"=",
"1000",
"dev",
"=",
"'/gpu:0'",
"if",
"bk",
".",
"DEVICE",
"==",
"'gpu'",
"else",
"'/cpu:0'",
"with",
"tf",
".",
"device",
"(",
"dev",
")",
":",
"t",
"=",
"tf",
".",
"Variable",
"(",
"tf... | Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate. | [
"Tensorflow",
"2",
".",
"0",
"example",
".",
"Given",
"an",
"arbitrary",
"one",
"-",
"qubit",
"gate",
"use",
"gradient",
"descent",
"to",
"find",
"corresponding",
"parameters",
"of",
"a",
"universal",
"ZYZ",
"gate",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow2_fit_gate.py#L21-L53 | train | 229,711 |
rigetti/quantumflow | quantumflow/programs.py | Program.run | def run(self, ket: State = None) -> State:
"""Compiles and runs a program. The optional program argument
supplies the initial state and memory. Else qubits and classical
bits start from zero states.
"""
if ket is None:
qubits = self.qubits
ket = zero_state(qubits)
ket = self._initilize(ket)
pc = 0
while pc >= 0 and pc < len(self):
instr = self.instructions[pc]
ket = ket.update({PC: pc + 1})
ket = instr.run(ket)
pc = ket.memory[PC]
return ket | python | def run(self, ket: State = None) -> State:
"""Compiles and runs a program. The optional program argument
supplies the initial state and memory. Else qubits and classical
bits start from zero states.
"""
if ket is None:
qubits = self.qubits
ket = zero_state(qubits)
ket = self._initilize(ket)
pc = 0
while pc >= 0 and pc < len(self):
instr = self.instructions[pc]
ket = ket.update({PC: pc + 1})
ket = instr.run(ket)
pc = ket.memory[PC]
return ket | [
"def",
"run",
"(",
"self",
",",
"ket",
":",
"State",
"=",
"None",
")",
"->",
"State",
":",
"if",
"ket",
"is",
"None",
":",
"qubits",
"=",
"self",
".",
"qubits",
"ket",
"=",
"zero_state",
"(",
"qubits",
")",
"ket",
"=",
"self",
".",
"_initilize",
... | Compiles and runs a program. The optional program argument
supplies the initial state and memory. Else qubits and classical
bits start from zero states. | [
"Compiles",
"and",
"runs",
"a",
"program",
".",
"The",
"optional",
"program",
"argument",
"supplies",
"the",
"initial",
"state",
"and",
"memory",
".",
"Else",
"qubits",
"and",
"classical",
"bits",
"start",
"from",
"zero",
"states",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/programs.py#L152-L170 | train | 229,712 |
rigetti/quantumflow | quantumflow/ops.py | Gate.relabel | def relabel(self, qubits: Qubits) -> 'Gate':
"""Return a copy of this Gate with new qubits"""
gate = copy(self)
gate.vec = gate.vec.relabel(qubits)
return gate | python | def relabel(self, qubits: Qubits) -> 'Gate':
"""Return a copy of this Gate with new qubits"""
gate = copy(self)
gate.vec = gate.vec.relabel(qubits)
return gate | [
"def",
"relabel",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Gate'",
":",
"gate",
"=",
"copy",
"(",
"self",
")",
"gate",
".",
"vec",
"=",
"gate",
".",
"vec",
".",
"relabel",
"(",
"qubits",
")",
"return",
"gate"
] | Return a copy of this Gate with new qubits | [
"Return",
"a",
"copy",
"of",
"this",
"Gate",
"with",
"new",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L142-L146 | train | 229,713 |
rigetti/quantumflow | quantumflow/ops.py | Gate.run | def run(self, ket: State) -> State:
"""Apply the action of this gate upon a state"""
qubits = self.qubits
indices = [ket.qubits.index(q) for q in qubits]
tensor = bk.tensormul(self.tensor, ket.tensor, indices)
return State(tensor, ket.qubits, ket.memory) | python | def run(self, ket: State) -> State:
"""Apply the action of this gate upon a state"""
qubits = self.qubits
indices = [ket.qubits.index(q) for q in qubits]
tensor = bk.tensormul(self.tensor, ket.tensor, indices)
return State(tensor, ket.qubits, ket.memory) | [
"def",
"run",
"(",
"self",
",",
"ket",
":",
"State",
")",
"->",
"State",
":",
"qubits",
"=",
"self",
".",
"qubits",
"indices",
"=",
"[",
"ket",
".",
"qubits",
".",
"index",
"(",
"q",
")",
"for",
"q",
"in",
"qubits",
"]",
"tensor",
"=",
"bk",
".... | Apply the action of this gate upon a state | [
"Apply",
"the",
"action",
"of",
"this",
"gate",
"upon",
"a",
"state"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L161-L166 | train | 229,714 |
rigetti/quantumflow | quantumflow/ops.py | Gate.evolve | def evolve(self, rho: Density) -> Density:
"""Apply the action of this gate upon a density"""
# TODO: implement without explicit channel creation?
chan = self.aschannel()
return chan.evolve(rho) | python | def evolve(self, rho: Density) -> Density:
"""Apply the action of this gate upon a density"""
# TODO: implement without explicit channel creation?
chan = self.aschannel()
return chan.evolve(rho) | [
"def",
"evolve",
"(",
"self",
",",
"rho",
":",
"Density",
")",
"->",
"Density",
":",
"# TODO: implement without explicit channel creation?",
"chan",
"=",
"self",
".",
"aschannel",
"(",
")",
"return",
"chan",
".",
"evolve",
"(",
"rho",
")"
] | Apply the action of this gate upon a density | [
"Apply",
"the",
"action",
"of",
"this",
"gate",
"upon",
"a",
"density"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L168-L172 | train | 229,715 |
rigetti/quantumflow | quantumflow/ops.py | Gate.aschannel | def aschannel(self) -> 'Channel':
"""Converts a Gate into a Channel"""
N = self.qubit_nb
R = 4
tensor = bk.outer(self.tensor, self.H.tensor)
tensor = bk.reshape(tensor, [2**N]*R)
tensor = bk.transpose(tensor, [0, 3, 1, 2])
return Channel(tensor, self.qubits) | python | def aschannel(self) -> 'Channel':
"""Converts a Gate into a Channel"""
N = self.qubit_nb
R = 4
tensor = bk.outer(self.tensor, self.H.tensor)
tensor = bk.reshape(tensor, [2**N]*R)
tensor = bk.transpose(tensor, [0, 3, 1, 2])
return Channel(tensor, self.qubits) | [
"def",
"aschannel",
"(",
"self",
")",
"->",
"'Channel'",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"R",
"=",
"4",
"tensor",
"=",
"bk",
".",
"outer",
"(",
"self",
".",
"tensor",
",",
"self",
".",
"H",
".",
"tensor",
")",
"tensor",
"=",
"bk",
".",
... | Converts a Gate into a Channel | [
"Converts",
"a",
"Gate",
"into",
"a",
"Channel"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L243-L252 | train | 229,716 |
rigetti/quantumflow | quantumflow/ops.py | Gate.su | def su(self) -> 'Gate':
"""Convert gate tensor to the special unitary group."""
rank = 2**self.qubit_nb
U = asarray(self.asoperator())
U /= np.linalg.det(U) ** (1/rank)
return Gate(tensor=U, qubits=self.qubits) | python | def su(self) -> 'Gate':
"""Convert gate tensor to the special unitary group."""
rank = 2**self.qubit_nb
U = asarray(self.asoperator())
U /= np.linalg.det(U) ** (1/rank)
return Gate(tensor=U, qubits=self.qubits) | [
"def",
"su",
"(",
"self",
")",
"->",
"'Gate'",
":",
"rank",
"=",
"2",
"**",
"self",
".",
"qubit_nb",
"U",
"=",
"asarray",
"(",
"self",
".",
"asoperator",
"(",
")",
")",
"U",
"/=",
"np",
".",
"linalg",
".",
"det",
"(",
"U",
")",
"**",
"(",
"1"... | Convert gate tensor to the special unitary group. | [
"Convert",
"gate",
"tensor",
"to",
"the",
"special",
"unitary",
"group",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L254-L259 | train | 229,717 |
rigetti/quantumflow | quantumflow/ops.py | Channel.relabel | def relabel(self, qubits: Qubits) -> 'Channel':
"""Return a copy of this channel with new qubits"""
chan = copy(self)
chan.vec = chan.vec.relabel(qubits)
return chan | python | def relabel(self, qubits: Qubits) -> 'Channel':
"""Return a copy of this channel with new qubits"""
chan = copy(self)
chan.vec = chan.vec.relabel(qubits)
return chan | [
"def",
"relabel",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Channel'",
":",
"chan",
"=",
"copy",
"(",
"self",
")",
"chan",
".",
"vec",
"=",
"chan",
".",
"vec",
".",
"relabel",
"(",
"qubits",
")",
"return",
"chan"
] | Return a copy of this channel with new qubits | [
"Return",
"a",
"copy",
"of",
"this",
"channel",
"with",
"new",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L298-L302 | train | 229,718 |
rigetti/quantumflow | quantumflow/ops.py | Channel.permute | def permute(self, qubits: Qubits) -> 'Channel':
"""Return a copy of this channel with qubits in new order"""
vec = self.vec.permute(qubits)
return Channel(vec.tensor, qubits=vec.qubits) | python | def permute(self, qubits: Qubits) -> 'Channel':
"""Return a copy of this channel with qubits in new order"""
vec = self.vec.permute(qubits)
return Channel(vec.tensor, qubits=vec.qubits) | [
"def",
"permute",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Channel'",
":",
"vec",
"=",
"self",
".",
"vec",
".",
"permute",
"(",
"qubits",
")",
"return",
"Channel",
"(",
"vec",
".",
"tensor",
",",
"qubits",
"=",
"vec",
".",
"qubits",
... | Return a copy of this channel with qubits in new order | [
"Return",
"a",
"copy",
"of",
"this",
"channel",
"with",
"qubits",
"in",
"new",
"order"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L304-L307 | train | 229,719 |
rigetti/quantumflow | quantumflow/ops.py | Channel.sharp | def sharp(self) -> 'Channel':
r"""Return the 'sharp' transpose of the superoperator.
The transpose :math:`S^\#` switches the two covariant (bra)
indices of the superoperator. (Which in our representation
are the 2nd and 3rd super-indices)
If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map
(i.e. transforms Hermitian operators to hJrmitian operators)
Flattening the :math:`S^\#` superoperator to a matrix gives
the Choi matrix representation. (See channel.choi())
"""
N = self.qubit_nb
tensor = self.tensor
tensor = bk.reshape(tensor, [2**N] * 4)
tensor = bk.transpose(tensor, (0, 2, 1, 3))
tensor = bk.reshape(tensor, [2] * 4 * N)
return Channel(tensor, self.qubits) | python | def sharp(self) -> 'Channel':
r"""Return the 'sharp' transpose of the superoperator.
The transpose :math:`S^\#` switches the two covariant (bra)
indices of the superoperator. (Which in our representation
are the 2nd and 3rd super-indices)
If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map
(i.e. transforms Hermitian operators to hJrmitian operators)
Flattening the :math:`S^\#` superoperator to a matrix gives
the Choi matrix representation. (See channel.choi())
"""
N = self.qubit_nb
tensor = self.tensor
tensor = bk.reshape(tensor, [2**N] * 4)
tensor = bk.transpose(tensor, (0, 2, 1, 3))
tensor = bk.reshape(tensor, [2] * 4 * N)
return Channel(tensor, self.qubits) | [
"def",
"sharp",
"(",
"self",
")",
"->",
"'Channel'",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"tensor",
"=",
"self",
".",
"tensor",
"tensor",
"=",
"bk",
".",
"reshape",
"(",
"tensor",
",",
"[",
"2",
"**",
"N",
"]",
"*",
"4",
")",
"tensor",
"=",
... | r"""Return the 'sharp' transpose of the superoperator.
The transpose :math:`S^\#` switches the two covariant (bra)
indices of the superoperator. (Which in our representation
are the 2nd and 3rd super-indices)
If :math:`S^\#` is Hermitian, then :math:`S` is a Hermitian-map
(i.e. transforms Hermitian operators to hJrmitian operators)
Flattening the :math:`S^\#` superoperator to a matrix gives
the Choi matrix representation. (See channel.choi()) | [
"r",
"Return",
"the",
"sharp",
"transpose",
"of",
"the",
"superoperator",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L315-L335 | train | 229,720 |
rigetti/quantumflow | quantumflow/ops.py | Channel.choi | def choi(self) -> bk.BKTensor:
"""Return the Choi matrix representation of this super
operator"""
# Put superop axes in [ok, ib, ob, ik] and reshape to matrix
N = self.qubit_nb
return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2) | python | def choi(self) -> bk.BKTensor:
"""Return the Choi matrix representation of this super
operator"""
# Put superop axes in [ok, ib, ob, ik] and reshape to matrix
N = self.qubit_nb
return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2) | [
"def",
"choi",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"# Put superop axes in [ok, ib, ob, ik] and reshape to matrix",
"N",
"=",
"self",
".",
"qubit_nb",
"return",
"bk",
".",
"reshape",
"(",
"self",
".",
"sharp",
".",
"tensor",
",",
"[",
"2",
"**... | Return the Choi matrix representation of this super
operator | [
"Return",
"the",
"Choi",
"matrix",
"representation",
"of",
"this",
"super",
"operator"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L337-L342 | train | 229,721 |
rigetti/quantumflow | quantumflow/ops.py | Channel.evolve | def evolve(self, rho: Density) -> Density:
"""Apply the action of this channel upon a density"""
N = rho.qubit_nb
qubits = rho.qubits
indices = list([qubits.index(q) for q in self.qubits]) + \
list([qubits.index(q) + N for q in self.qubits])
tensor = bk.tensormul(self.tensor, rho.tensor, indices)
return Density(tensor, qubits, rho.memory) | python | def evolve(self, rho: Density) -> Density:
"""Apply the action of this channel upon a density"""
N = rho.qubit_nb
qubits = rho.qubits
indices = list([qubits.index(q) for q in self.qubits]) + \
list([qubits.index(q) + N for q in self.qubits])
tensor = bk.tensormul(self.tensor, rho.tensor, indices)
return Density(tensor, qubits, rho.memory) | [
"def",
"evolve",
"(",
"self",
",",
"rho",
":",
"Density",
")",
"->",
"Density",
":",
"N",
"=",
"rho",
".",
"qubit_nb",
"qubits",
"=",
"rho",
".",
"qubits",
"indices",
"=",
"list",
"(",
"[",
"qubits",
".",
"index",
"(",
"q",
")",
"for",
"q",
"in",... | Apply the action of this channel upon a density | [
"Apply",
"the",
"action",
"of",
"this",
"channel",
"upon",
"a",
"density"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L354-L363 | train | 229,722 |
rigetti/quantumflow | quantumflow/backend/eagerbk.py | fcast | def fcast(value: float) -> TensorLike:
"""Cast to float tensor"""
newvalue = tf.cast(value, FTYPE)
if DEVICE == 'gpu':
newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover
return newvalue | python | def fcast(value: float) -> TensorLike:
"""Cast to float tensor"""
newvalue = tf.cast(value, FTYPE)
if DEVICE == 'gpu':
newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover
return newvalue | [
"def",
"fcast",
"(",
"value",
":",
"float",
")",
"->",
"TensorLike",
":",
"newvalue",
"=",
"tf",
".",
"cast",
"(",
"value",
",",
"FTYPE",
")",
"if",
"DEVICE",
"==",
"'gpu'",
":",
"newvalue",
"=",
"newvalue",
".",
"gpu",
"(",
")",
"# Why is this needed?... | Cast to float tensor | [
"Cast",
"to",
"float",
"tensor"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L52-L57 | train | 229,723 |
rigetti/quantumflow | quantumflow/backend/eagerbk.py | astensor | def astensor(array: TensorLike) -> BKTensor:
"""Convert to product tensor"""
tensor = tf.convert_to_tensor(array, dtype=CTYPE)
if DEVICE == 'gpu':
tensor = tensor.gpu() # pragma: no cover
# size = np.prod(np.array(tensor.get_shape().as_list()))
N = int(math.log2(size(tensor)))
tensor = tf.reshape(tensor, ([2]*N))
return tensor | python | def astensor(array: TensorLike) -> BKTensor:
"""Convert to product tensor"""
tensor = tf.convert_to_tensor(array, dtype=CTYPE)
if DEVICE == 'gpu':
tensor = tensor.gpu() # pragma: no cover
# size = np.prod(np.array(tensor.get_shape().as_list()))
N = int(math.log2(size(tensor)))
tensor = tf.reshape(tensor, ([2]*N))
return tensor | [
"def",
"astensor",
"(",
"array",
":",
"TensorLike",
")",
"->",
"BKTensor",
":",
"tensor",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"array",
",",
"dtype",
"=",
"CTYPE",
")",
"if",
"DEVICE",
"==",
"'gpu'",
":",
"tensor",
"=",
"tensor",
".",
"gpu",
"(",
... | Convert to product tensor | [
"Convert",
"to",
"product",
"tensor"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/eagerbk.py#L60-L70 | train | 229,724 |
rigetti/quantumflow | quantumflow/circuits.py | count_operations | def count_operations(elements: Iterable[Operation]) \
-> Dict[Type[Operation], int]:
"""Return a count of different operation types given a colelction of
operations, such as a Circuit or DAGCircuit
"""
op_count: Dict[Type[Operation], int] = defaultdict(int)
for elem in elements:
op_count[type(elem)] += 1
return dict(op_count) | python | def count_operations(elements: Iterable[Operation]) \
-> Dict[Type[Operation], int]:
"""Return a count of different operation types given a colelction of
operations, such as a Circuit or DAGCircuit
"""
op_count: Dict[Type[Operation], int] = defaultdict(int)
for elem in elements:
op_count[type(elem)] += 1
return dict(op_count) | [
"def",
"count_operations",
"(",
"elements",
":",
"Iterable",
"[",
"Operation",
"]",
")",
"->",
"Dict",
"[",
"Type",
"[",
"Operation",
"]",
",",
"int",
"]",
":",
"op_count",
":",
"Dict",
"[",
"Type",
"[",
"Operation",
"]",
",",
"int",
"]",
"=",
"defau... | Return a count of different operation types given a colelction of
operations, such as a Circuit or DAGCircuit | [
"Return",
"a",
"count",
"of",
"different",
"operation",
"types",
"given",
"a",
"colelction",
"of",
"operations",
"such",
"as",
"a",
"Circuit",
"or",
"DAGCircuit"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L141-L149 | train | 229,725 |
rigetti/quantumflow | quantumflow/circuits.py | map_gate | def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit:
"""Applies the same gate all input qubits in the argument list.
>>> circ = qf.map_gate(qf.H(), [[0], [1], [2]])
>>> print(circ)
H(0)
H(1)
H(2)
"""
circ = Circuit()
for qubits in args:
circ += gate.relabel(qubits)
return circ | python | def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit:
"""Applies the same gate all input qubits in the argument list.
>>> circ = qf.map_gate(qf.H(), [[0], [1], [2]])
>>> print(circ)
H(0)
H(1)
H(2)
"""
circ = Circuit()
for qubits in args:
circ += gate.relabel(qubits)
return circ | [
"def",
"map_gate",
"(",
"gate",
":",
"Gate",
",",
"args",
":",
"Sequence",
"[",
"Qubits",
"]",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"for",
"qubits",
"in",
"args",
":",
"circ",
"+=",
"gate",
".",
"relabel",
"(",
"qubits",
")"... | Applies the same gate all input qubits in the argument list.
>>> circ = qf.map_gate(qf.H(), [[0], [1], [2]])
>>> print(circ)
H(0)
H(1)
H(2) | [
"Applies",
"the",
"same",
"gate",
"all",
"input",
"qubits",
"in",
"the",
"argument",
"list",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L152-L167 | train | 229,726 |
rigetti/quantumflow | quantumflow/circuits.py | qft_circuit | def qft_circuit(qubits: Qubits) -> Circuit:
"""Returns the Quantum Fourier Transform circuit"""
# Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py
N = len(qubits)
circ = Circuit()
for n0 in range(N):
q0 = qubits[n0]
circ += H(q0)
for n1 in range(n0+1, N):
q1 = qubits[n1]
angle = pi / 2 ** (n1-n0)
circ += CPHASE(angle, q1, q0)
circ.extend(reversal_circuit(qubits))
return circ | python | def qft_circuit(qubits: Qubits) -> Circuit:
"""Returns the Quantum Fourier Transform circuit"""
# Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py
N = len(qubits)
circ = Circuit()
for n0 in range(N):
q0 = qubits[n0]
circ += H(q0)
for n1 in range(n0+1, N):
q1 = qubits[n1]
angle = pi / 2 ** (n1-n0)
circ += CPHASE(angle, q1, q0)
circ.extend(reversal_circuit(qubits))
return circ | [
"def",
"qft_circuit",
"(",
"qubits",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"# Kudos: Adapted from Rigetti Grove, grove/qft/fourier.py",
"N",
"=",
"len",
"(",
"qubits",
")",
"circ",
"=",
"Circuit",
"(",
")",
"for",
"n0",
"in",
"range",
"(",
"N",
")",
":",... | Returns the Quantum Fourier Transform circuit | [
"Returns",
"the",
"Quantum",
"Fourier",
"Transform",
"circuit"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L170-L184 | train | 229,727 |
rigetti/quantumflow | quantumflow/circuits.py | reversal_circuit | def reversal_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit to reverse qubits"""
N = len(qubits)
circ = Circuit()
for n in range(N // 2):
circ += SWAP(qubits[n], qubits[N-1-n])
return circ | python | def reversal_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit to reverse qubits"""
N = len(qubits)
circ = Circuit()
for n in range(N // 2):
circ += SWAP(qubits[n], qubits[N-1-n])
return circ | [
"def",
"reversal_circuit",
"(",
"qubits",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"N",
"=",
"len",
"(",
"qubits",
")",
"circ",
"=",
"Circuit",
"(",
")",
"for",
"n",
"in",
"range",
"(",
"N",
"//",
"2",
")",
":",
"circ",
"+=",
"SWAP",
"(",
"qubit... | Returns a circuit to reverse qubits | [
"Returns",
"a",
"circuit",
"to",
"reverse",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L187-L193 | train | 229,728 |
rigetti/quantumflow | quantumflow/circuits.py | zyz_circuit | def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit:
"""Circuit equivalent of 1-qubit ZYZ gate"""
circ = Circuit()
circ += TZ(t0, q0)
circ += TY(t1, q0)
circ += TZ(t2, q0)
return circ | python | def zyz_circuit(t0: float, t1: float, t2: float, q0: Qubit) -> Circuit:
"""Circuit equivalent of 1-qubit ZYZ gate"""
circ = Circuit()
circ += TZ(t0, q0)
circ += TY(t1, q0)
circ += TZ(t2, q0)
return circ | [
"def",
"zyz_circuit",
"(",
"t0",
":",
"float",
",",
"t1",
":",
"float",
",",
"t2",
":",
"float",
",",
"q0",
":",
"Qubit",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"circ",
"+=",
"TZ",
"(",
"t0",
",",
"q0",
")",
"circ",
"+=",
... | Circuit equivalent of 1-qubit ZYZ gate | [
"Circuit",
"equivalent",
"of",
"1",
"-",
"qubit",
"ZYZ",
"gate"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L260-L266 | train | 229,729 |
rigetti/quantumflow | quantumflow/circuits.py | phase_estimation_circuit | def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit:
"""Returns a circuit for quantum phase estimation.
The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To
run the circuit, the eigenvector should be set on the gate qubits,
and the output qubits should be in the zero state. After evolution and
measurement, the output qubits will be (approximately) a binary fraction
representation of the phase.
The output registers can be converted with the aid of the
quantumflow.utils.bitlist_to_int() method.
>>> import numpy as np
>>> import quantumflow as qf
>>> N = 8
>>> phase = 1/4
>>> gate = qf.RZ(-4*np.pi*phase, N)
>>> circ = qf.phase_estimation_circuit(gate, range(N))
>>> res = circ.run().measure()[0:N]
>>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float
>>> print(phase, est_phase)
0.25 0.25
"""
circ = Circuit()
circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits
for cq in reversed(outputs):
cgate = control_gate(cq, gate)
circ += cgate
gate = gate @ gate
circ += qft_circuit(outputs).H
return circ | python | def phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit:
"""Returns a circuit for quantum phase estimation.
The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To
run the circuit, the eigenvector should be set on the gate qubits,
and the output qubits should be in the zero state. After evolution and
measurement, the output qubits will be (approximately) a binary fraction
representation of the phase.
The output registers can be converted with the aid of the
quantumflow.utils.bitlist_to_int() method.
>>> import numpy as np
>>> import quantumflow as qf
>>> N = 8
>>> phase = 1/4
>>> gate = qf.RZ(-4*np.pi*phase, N)
>>> circ = qf.phase_estimation_circuit(gate, range(N))
>>> res = circ.run().measure()[0:N]
>>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float
>>> print(phase, est_phase)
0.25 0.25
"""
circ = Circuit()
circ += map_gate(H(), list(zip(outputs))) # Hadamard on all output qubits
for cq in reversed(outputs):
cgate = control_gate(cq, gate)
circ += cgate
gate = gate @ gate
circ += qft_circuit(outputs).H
return circ | [
"def",
"phase_estimation_circuit",
"(",
"gate",
":",
"Gate",
",",
"outputs",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"circ",
"+=",
"map_gate",
"(",
"H",
"(",
")",
",",
"list",
"(",
"zip",
"(",
"outputs",
")",
")",
... | Returns a circuit for quantum phase estimation.
The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To
run the circuit, the eigenvector should be set on the gate qubits,
and the output qubits should be in the zero state. After evolution and
measurement, the output qubits will be (approximately) a binary fraction
representation of the phase.
The output registers can be converted with the aid of the
quantumflow.utils.bitlist_to_int() method.
>>> import numpy as np
>>> import quantumflow as qf
>>> N = 8
>>> phase = 1/4
>>> gate = qf.RZ(-4*np.pi*phase, N)
>>> circ = qf.phase_estimation_circuit(gate, range(N))
>>> res = circ.run().measure()[0:N]
>>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float
>>> print(phase, est_phase)
0.25 0.25 | [
"Returns",
"a",
"circuit",
"for",
"quantum",
"phase",
"estimation",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L269-L303 | train | 229,730 |
rigetti/quantumflow | quantumflow/circuits.py | ghz_circuit | def ghz_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit that prepares a multi-qubit Bell state from the zero
state.
"""
circ = Circuit()
circ += H(qubits[0])
for q0 in range(0, len(qubits)-1):
circ += CNOT(qubits[q0], qubits[q0+1])
return circ | python | def ghz_circuit(qubits: Qubits) -> Circuit:
"""Returns a circuit that prepares a multi-qubit Bell state from the zero
state.
"""
circ = Circuit()
circ += H(qubits[0])
for q0 in range(0, len(qubits)-1):
circ += CNOT(qubits[q0], qubits[q0+1])
return circ | [
"def",
"ghz_circuit",
"(",
"qubits",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"circ",
"=",
"Circuit",
"(",
")",
"circ",
"+=",
"H",
"(",
"qubits",
"[",
"0",
"]",
")",
"for",
"q0",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"qubits",
")",
"-",
"1... | Returns a circuit that prepares a multi-qubit Bell state from the zero
state. | [
"Returns",
"a",
"circuit",
"that",
"prepares",
"a",
"multi",
"-",
"qubit",
"Bell",
"state",
"from",
"the",
"zero",
"state",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L359-L369 | train | 229,731 |
rigetti/quantumflow | quantumflow/circuits.py | Circuit.extend | def extend(self, other: Operation) -> None:
"""Append gates from circuit to the end of this circuit"""
if isinstance(other, Circuit):
self.elements.extend(other.elements)
else:
self.elements.extend([other]) | python | def extend(self, other: Operation) -> None:
"""Append gates from circuit to the end of this circuit"""
if isinstance(other, Circuit):
self.elements.extend(other.elements)
else:
self.elements.extend([other]) | [
"def",
"extend",
"(",
"self",
",",
"other",
":",
"Operation",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"other",
",",
"Circuit",
")",
":",
"self",
".",
"elements",
".",
"extend",
"(",
"other",
".",
"elements",
")",
"else",
":",
"self",
".",
... | Append gates from circuit to the end of this circuit | [
"Append",
"gates",
"from",
"circuit",
"to",
"the",
"end",
"of",
"this",
"circuit"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L53-L58 | train | 229,732 |
rigetti/quantumflow | quantumflow/circuits.py | Circuit.run | def run(self, ket: State = None) -> State:
"""
Apply the action of this circuit upon a state.
If no initial state provided an initial zero state will be created.
"""
if ket is None:
qubits = self.qubits
ket = zero_state(qubits=qubits)
for elem in self.elements:
ket = elem.run(ket)
return ket | python | def run(self, ket: State = None) -> State:
"""
Apply the action of this circuit upon a state.
If no initial state provided an initial zero state will be created.
"""
if ket is None:
qubits = self.qubits
ket = zero_state(qubits=qubits)
for elem in self.elements:
ket = elem.run(ket)
return ket | [
"def",
"run",
"(",
"self",
",",
"ket",
":",
"State",
"=",
"None",
")",
"->",
"State",
":",
"if",
"ket",
"is",
"None",
":",
"qubits",
"=",
"self",
".",
"qubits",
"ket",
"=",
"zero_state",
"(",
"qubits",
"=",
"qubits",
")",
"for",
"elem",
"in",
"se... | Apply the action of this circuit upon a state.
If no initial state provided an initial zero state will be created. | [
"Apply",
"the",
"action",
"of",
"this",
"circuit",
"upon",
"a",
"state",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L87-L99 | train | 229,733 |
rigetti/quantumflow | quantumflow/circuits.py | Circuit.asgate | def asgate(self) -> Gate:
"""
Return the action of this circuit as a gate
"""
gate = identity_gate(self.qubits)
for elem in self.elements:
gate = elem.asgate() @ gate
return gate | python | def asgate(self) -> Gate:
"""
Return the action of this circuit as a gate
"""
gate = identity_gate(self.qubits)
for elem in self.elements:
gate = elem.asgate() @ gate
return gate | [
"def",
"asgate",
"(",
"self",
")",
"->",
"Gate",
":",
"gate",
"=",
"identity_gate",
"(",
"self",
".",
"qubits",
")",
"for",
"elem",
"in",
"self",
".",
"elements",
":",
"gate",
"=",
"elem",
".",
"asgate",
"(",
")",
"@",
"gate",
"return",
"gate"
] | Return the action of this circuit as a gate | [
"Return",
"the",
"action",
"of",
"this",
"circuit",
"as",
"a",
"gate"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/circuits.py#L111-L118 | train | 229,734 |
rigetti/quantumflow | quantumflow/channels.py | join_channels | def join_channels(*channels: Channel) -> Channel:
"""Join two channels acting on different qubits into a single channel
acting on all qubits"""
vectors = [chan.vec for chan in channels]
vec = reduce(outer_product, vectors)
return Channel(vec.tensor, vec.qubits) | python | def join_channels(*channels: Channel) -> Channel:
"""Join two channels acting on different qubits into a single channel
acting on all qubits"""
vectors = [chan.vec for chan in channels]
vec = reduce(outer_product, vectors)
return Channel(vec.tensor, vec.qubits) | [
"def",
"join_channels",
"(",
"*",
"channels",
":",
"Channel",
")",
"->",
"Channel",
":",
"vectors",
"=",
"[",
"chan",
".",
"vec",
"for",
"chan",
"in",
"channels",
"]",
"vec",
"=",
"reduce",
"(",
"outer_product",
",",
"vectors",
")",
"return",
"Channel",
... | Join two channels acting on different qubits into a single channel
acting on all qubits | [
"Join",
"two",
"channels",
"acting",
"on",
"different",
"qubits",
"into",
"a",
"single",
"channel",
"acting",
"on",
"all",
"qubits"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175 | train | 229,735 |
rigetti/quantumflow | quantumflow/channels.py | channel_to_kraus | def channel_to_kraus(chan: Channel) -> 'Kraus':
"""Convert a channel superoperator into a Kraus operator representation
of the same channel."""
qubits = chan.qubits
N = chan.qubit_nb
choi = asarray(chan.choi())
evals, evecs = np.linalg.eig(choi)
evecs = np.transpose(evecs)
assert np.allclose(evals.imag, 0.0) # FIXME exception
assert np.all(evals.real >= 0.0) # FIXME exception
values = np.sqrt(evals.real)
ops = []
for i in range(2**(2*N)):
if not np.isclose(values[i], 0.0):
mat = np.reshape(evecs[i], (2**N, 2**N))*values[i]
g = Gate(mat, qubits)
ops.append(g)
return Kraus(ops) | python | def channel_to_kraus(chan: Channel) -> 'Kraus':
"""Convert a channel superoperator into a Kraus operator representation
of the same channel."""
qubits = chan.qubits
N = chan.qubit_nb
choi = asarray(chan.choi())
evals, evecs = np.linalg.eig(choi)
evecs = np.transpose(evecs)
assert np.allclose(evals.imag, 0.0) # FIXME exception
assert np.all(evals.real >= 0.0) # FIXME exception
values = np.sqrt(evals.real)
ops = []
for i in range(2**(2*N)):
if not np.isclose(values[i], 0.0):
mat = np.reshape(evecs[i], (2**N, 2**N))*values[i]
g = Gate(mat, qubits)
ops.append(g)
return Kraus(ops) | [
"def",
"channel_to_kraus",
"(",
"chan",
":",
"Channel",
")",
"->",
"'Kraus'",
":",
"qubits",
"=",
"chan",
".",
"qubits",
"N",
"=",
"chan",
".",
"qubit_nb",
"choi",
"=",
"asarray",
"(",
"chan",
".",
"choi",
"(",
")",
")",
"evals",
",",
"evecs",
"=",
... | Convert a channel superoperator into a Kraus operator representation
of the same channel. | [
"Convert",
"a",
"channel",
"superoperator",
"into",
"a",
"Kraus",
"operator",
"representation",
"of",
"the",
"same",
"channel",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L181-L203 | train | 229,736 |
rigetti/quantumflow | quantumflow/channels.py | Kraus.run | def run(self, ket: State) -> State:
"""Apply the action of this Kraus quantum operation upon a state"""
res = [op.run(ket) for op in self.operators]
probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)]
probs = np.asarray(probs)
probs /= np.sum(probs)
newket = np.random.choice(res, p=probs)
return newket.normalize() | python | def run(self, ket: State) -> State:
"""Apply the action of this Kraus quantum operation upon a state"""
res = [op.run(ket) for op in self.operators]
probs = [asarray(ket.norm()) * w for ket, w in zip(res, self.weights)]
probs = np.asarray(probs)
probs /= np.sum(probs)
newket = np.random.choice(res, p=probs)
return newket.normalize() | [
"def",
"run",
"(",
"self",
",",
"ket",
":",
"State",
")",
"->",
"State",
":",
"res",
"=",
"[",
"op",
".",
"run",
"(",
"ket",
")",
"for",
"op",
"in",
"self",
".",
"operators",
"]",
"probs",
"=",
"[",
"asarray",
"(",
"ket",
".",
"norm",
"(",
")... | Apply the action of this Kraus quantum operation upon a state | [
"Apply",
"the",
"action",
"of",
"this",
"Kraus",
"quantum",
"operation",
"upon",
"a",
"state"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L70-L77 | train | 229,737 |
rigetti/quantumflow | quantumflow/channels.py | Kraus.evolve | def evolve(self, rho: Density) -> Density:
"""Apply the action of this Kraus quantum operation upon a density"""
qubits = rho.qubits
results = [op.evolve(rho) for op in self.operators]
tensors = [rho.tensor * w for rho, w in zip(results, self.weights)]
tensor = reduce(add, tensors)
return Density(tensor, qubits) | python | def evolve(self, rho: Density) -> Density:
"""Apply the action of this Kraus quantum operation upon a density"""
qubits = rho.qubits
results = [op.evolve(rho) for op in self.operators]
tensors = [rho.tensor * w for rho, w in zip(results, self.weights)]
tensor = reduce(add, tensors)
return Density(tensor, qubits) | [
"def",
"evolve",
"(",
"self",
",",
"rho",
":",
"Density",
")",
"->",
"Density",
":",
"qubits",
"=",
"rho",
".",
"qubits",
"results",
"=",
"[",
"op",
".",
"evolve",
"(",
"rho",
")",
"for",
"op",
"in",
"self",
".",
"operators",
"]",
"tensors",
"=",
... | Apply the action of this Kraus quantum operation upon a density | [
"Apply",
"the",
"action",
"of",
"this",
"Kraus",
"quantum",
"operation",
"upon",
"a",
"density"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L79-L85 | train | 229,738 |
rigetti/quantumflow | quantumflow/channels.py | Kraus.H | def H(self) -> 'Kraus':
"""Return the complex conjugate of this Kraus operation"""
operators = [op.H for op in self.operators]
return Kraus(operators, self.weights) | python | def H(self) -> 'Kraus':
"""Return the complex conjugate of this Kraus operation"""
operators = [op.H for op in self.operators]
return Kraus(operators, self.weights) | [
"def",
"H",
"(",
"self",
")",
"->",
"'Kraus'",
":",
"operators",
"=",
"[",
"op",
".",
"H",
"for",
"op",
"in",
"self",
".",
"operators",
"]",
"return",
"Kraus",
"(",
"operators",
",",
"self",
".",
"weights",
")"
] | Return the complex conjugate of this Kraus operation | [
"Return",
"the",
"complex",
"conjugate",
"of",
"this",
"Kraus",
"operation"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L103-L106 | train | 229,739 |
rigetti/quantumflow | quantumflow/channels.py | UnitaryMixture.asgate | def asgate(self) -> Gate:
"""Return one of the composite Kraus operators at random with
the appropriate weights"""
return np.random.choice(self.operators, p=self.weights) | python | def asgate(self) -> Gate:
"""Return one of the composite Kraus operators at random with
the appropriate weights"""
return np.random.choice(self.operators, p=self.weights) | [
"def",
"asgate",
"(",
"self",
")",
"->",
"Gate",
":",
"return",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"operators",
",",
"p",
"=",
"self",
".",
"weights",
")"
] | Return one of the composite Kraus operators at random with
the appropriate weights | [
"Return",
"one",
"of",
"the",
"composite",
"Kraus",
"operators",
"at",
"random",
"with",
"the",
"appropriate",
"weights"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L119-L122 | train | 229,740 |
rigetti/quantumflow | quantumflow/visualization.py | _display_layers | def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit:
"""Separate a circuit into groups of gates that do not visually overlap"""
N = len(qubits)
qubit_idx = dict(zip(qubits, range(N)))
gate_layers = DAGCircuit(circ).layers()
layers = []
lcirc = Circuit()
layers.append(lcirc)
unused = [True] * N
for gl in gate_layers:
assert isinstance(gl, Circuit)
for gate in gl:
indices = [qubit_idx[q] for q in gate.qubits]
if not all(unused[min(indices):max(indices)+1]):
# New layer
lcirc = Circuit()
layers.append(lcirc)
unused = [True] * N
unused[min(indices):max(indices)+1] = \
[False] * (max(indices) - min(indices) + 1)
lcirc += gate
return Circuit(layers) | python | def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit:
"""Separate a circuit into groups of gates that do not visually overlap"""
N = len(qubits)
qubit_idx = dict(zip(qubits, range(N)))
gate_layers = DAGCircuit(circ).layers()
layers = []
lcirc = Circuit()
layers.append(lcirc)
unused = [True] * N
for gl in gate_layers:
assert isinstance(gl, Circuit)
for gate in gl:
indices = [qubit_idx[q] for q in gate.qubits]
if not all(unused[min(indices):max(indices)+1]):
# New layer
lcirc = Circuit()
layers.append(lcirc)
unused = [True] * N
unused[min(indices):max(indices)+1] = \
[False] * (max(indices) - min(indices) + 1)
lcirc += gate
return Circuit(layers) | [
"def",
"_display_layers",
"(",
"circ",
":",
"Circuit",
",",
"qubits",
":",
"Qubits",
")",
"->",
"Circuit",
":",
"N",
"=",
"len",
"(",
"qubits",
")",
"qubit_idx",
"=",
"dict",
"(",
"zip",
"(",
"qubits",
",",
"range",
"(",
"N",
")",
")",
")",
"gate_l... | Separate a circuit into groups of gates that do not visually overlap | [
"Separate",
"a",
"circuit",
"into",
"groups",
"of",
"gates",
"that",
"do",
"not",
"visually",
"overlap"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L235-L261 | train | 229,741 |
rigetti/quantumflow | quantumflow/visualization.py | render_latex | def render_latex(latex: str) -> PIL.Image: # pragma: no cover
"""
Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX document as a string.
Returns:
A PIL Image
Raises:
OSError: If an external dependency is not installed.
"""
tmpfilename = 'circ'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename)
with open(tmppath + '.tex', 'w') as latex_file:
latex_file.write(latex)
subprocess.run(["pdflatex",
"-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename+'.tex')],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True)
subprocess.run(['pdftocairo',
'-singlefile',
'-png',
'-q',
tmppath + '.pdf',
tmppath])
img = PIL.Image.open(tmppath + '.png')
return img | python | def render_latex(latex: str) -> PIL.Image: # pragma: no cover
"""
Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX document as a string.
Returns:
A PIL Image
Raises:
OSError: If an external dependency is not installed.
"""
tmpfilename = 'circ'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename)
with open(tmppath + '.tex', 'w') as latex_file:
latex_file.write(latex)
subprocess.run(["pdflatex",
"-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename+'.tex')],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True)
subprocess.run(['pdftocairo',
'-singlefile',
'-png',
'-q',
tmppath + '.pdf',
tmppath])
img = PIL.Image.open(tmppath + '.png')
return img | [
"def",
"render_latex",
"(",
"latex",
":",
"str",
")",
"->",
"PIL",
".",
"Image",
":",
"# pragma: no cover",
"tmpfilename",
"=",
"'circ'",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tmpdirname",
":",
"tmppath",
"=",
"os",
".",
"path",
"... | Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX document as a string.
Returns:
A PIL Image
Raises:
OSError: If an external dependency is not installed. | [
"Convert",
"a",
"single",
"page",
"LaTeX",
"document",
"into",
"an",
"image",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L264-L305 | train | 229,742 |
rigetti/quantumflow | quantumflow/visualization.py | circuit_to_image | def circuit_to_image(circ: Circuit,
qubits: Qubits = None) -> PIL.Image: # pragma: no cover
"""Create an image of a quantum circuit.
A convenience function that calls circuit_to_latex() and render_latex().
Args:
circ: A quantum Circuit
qubits: Optional qubit list to specify qubit order
Returns:
Returns: A PIL Image (Use img.show() to display)
Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed.
"""
latex = circuit_to_latex(circ, qubits)
img = render_latex(latex)
return img | python | def circuit_to_image(circ: Circuit,
qubits: Qubits = None) -> PIL.Image: # pragma: no cover
"""Create an image of a quantum circuit.
A convenience function that calls circuit_to_latex() and render_latex().
Args:
circ: A quantum Circuit
qubits: Optional qubit list to specify qubit order
Returns:
Returns: A PIL Image (Use img.show() to display)
Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed.
"""
latex = circuit_to_latex(circ, qubits)
img = render_latex(latex)
return img | [
"def",
"circuit_to_image",
"(",
"circ",
":",
"Circuit",
",",
"qubits",
":",
"Qubits",
"=",
"None",
")",
"->",
"PIL",
".",
"Image",
":",
"# pragma: no cover",
"latex",
"=",
"circuit_to_latex",
"(",
"circ",
",",
"qubits",
")",
"img",
"=",
"render_latex",
"("... | Create an image of a quantum circuit.
A convenience function that calls circuit_to_latex() and render_latex().
Args:
circ: A quantum Circuit
qubits: Optional qubit list to specify qubit order
Returns:
Returns: A PIL Image (Use img.show() to display)
Raises:
NotImplementedError: For unsupported gates.
OSError: If an external dependency is not installed. | [
"Create",
"an",
"image",
"of",
"a",
"quantum",
"circuit",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L308-L327 | train | 229,743 |
rigetti/quantumflow | quantumflow/visualization.py | _latex_format | def _latex_format(obj: Any) -> str:
"""Format an object as a latex string."""
if isinstance(obj, float):
try:
return sympy.latex(symbolize(obj))
except ValueError:
return "{0:.4g}".format(obj)
return str(obj) | python | def _latex_format(obj: Any) -> str:
"""Format an object as a latex string."""
if isinstance(obj, float):
try:
return sympy.latex(symbolize(obj))
except ValueError:
return "{0:.4g}".format(obj)
return str(obj) | [
"def",
"_latex_format",
"(",
"obj",
":",
"Any",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"obj",
",",
"float",
")",
":",
"try",
":",
"return",
"sympy",
".",
"latex",
"(",
"symbolize",
"(",
"obj",
")",
")",
"except",
"ValueError",
":",
"return",... | Format an object as a latex string. | [
"Format",
"an",
"object",
"as",
"a",
"latex",
"string",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L332-L340 | train | 229,744 |
rigetti/quantumflow | examples/eager_fit_gate.py | fit_zyz | def fit_zyz(target_gate):
"""
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
assert bk.BACKEND == 'eager'
tf = bk.TL
tfe = bk.tfe
steps = 4000
dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0'
with tf.device(dev):
t = tfe.Variable(np.random.normal(size=[3]), name='t')
def loss_fn():
"""Loss"""
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
return ang
loss_and_grads = tfe.implicit_value_and_gradients(loss_fn)
# opt = tf.train.GradientDescentOptimizer(learning_rate=0.005)
opt = tf.train.AdamOptimizer(learning_rate=0.001)
# train = opt.minimize(ang, var_list=[t])
for step in range(steps):
loss, grads_and_vars = loss_and_grads()
sys.stdout.write('\r')
sys.stdout.write("step: {:3d} loss: {:10.9f}".format(step,
loss.numpy()))
if loss < 0.0001:
break
opt.apply_gradients(grads_and_vars)
print()
return bk.evaluate(t) | python | def fit_zyz(target_gate):
"""
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
assert bk.BACKEND == 'eager'
tf = bk.TL
tfe = bk.tfe
steps = 4000
dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0'
with tf.device(dev):
t = tfe.Variable(np.random.normal(size=[3]), name='t')
def loss_fn():
"""Loss"""
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
return ang
loss_and_grads = tfe.implicit_value_and_gradients(loss_fn)
# opt = tf.train.GradientDescentOptimizer(learning_rate=0.005)
opt = tf.train.AdamOptimizer(learning_rate=0.001)
# train = opt.minimize(ang, var_list=[t])
for step in range(steps):
loss, grads_and_vars = loss_and_grads()
sys.stdout.write('\r')
sys.stdout.write("step: {:3d} loss: {:10.9f}".format(step,
loss.numpy()))
if loss < 0.0001:
break
opt.apply_gradients(grads_and_vars)
print()
return bk.evaluate(t) | [
"def",
"fit_zyz",
"(",
"target_gate",
")",
":",
"assert",
"bk",
".",
"BACKEND",
"==",
"'eager'",
"tf",
"=",
"bk",
".",
"TL",
"tfe",
"=",
"bk",
".",
"tfe",
"steps",
"=",
"4000",
"dev",
"=",
"'/gpu:0'",
"if",
"bk",
".",
"DEVICE",
"==",
"'gpu'",
"else... | Tensorflow eager mode example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate. | [
"Tensorflow",
"eager",
"mode",
"example",
".",
"Given",
"an",
"arbitrary",
"one",
"-",
"qubit",
"gate",
"use",
"gradient",
"descent",
"to",
"find",
"corresponding",
"parameters",
"of",
"a",
"universal",
"ZYZ",
"gate",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/eager_fit_gate.py#L21-L60 | train | 229,745 |
rigetti/quantumflow | quantumflow/meta.py | print_versions | def print_versions(file: typing.TextIO = None) -> None:
"""
Print version strings of currently installed dependencies
``> python -m quantumflow.meta``
Args:
file: Output stream. Defaults to stdout.
"""
print('** QuantumFlow dependencies (> python -m quantumflow.meta) **')
print('quantumflow \t', qf.__version__, file=file)
print('python \t', sys.version[0:5], file=file)
print('numpy \t', np.__version__, file=file)
print('networkx \t', nx.__version__, file=file)
print('cvxpy \t', cvx.__version__, file=file)
print('pyquil \t', pyquil.__version__, file=file)
print(bk.name, ' \t', bk.version, '(BACKEND)', file=file) | python | def print_versions(file: typing.TextIO = None) -> None:
"""
Print version strings of currently installed dependencies
``> python -m quantumflow.meta``
Args:
file: Output stream. Defaults to stdout.
"""
print('** QuantumFlow dependencies (> python -m quantumflow.meta) **')
print('quantumflow \t', qf.__version__, file=file)
print('python \t', sys.version[0:5], file=file)
print('numpy \t', np.__version__, file=file)
print('networkx \t', nx.__version__, file=file)
print('cvxpy \t', cvx.__version__, file=file)
print('pyquil \t', pyquil.__version__, file=file)
print(bk.name, ' \t', bk.version, '(BACKEND)', file=file) | [
"def",
"print_versions",
"(",
"file",
":",
"typing",
".",
"TextIO",
"=",
"None",
")",
"->",
"None",
":",
"print",
"(",
"'** QuantumFlow dependencies (> python -m quantumflow.meta) **'",
")",
"print",
"(",
"'quantumflow \\t'",
",",
"qf",
".",
"__version__",
",",
"f... | Print version strings of currently installed dependencies
``> python -m quantumflow.meta``
Args:
file: Output stream. Defaults to stdout. | [
"Print",
"version",
"strings",
"of",
"currently",
"installed",
"dependencies"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/meta.py#L21-L40 | train | 229,746 |
rigetti/quantumflow | examples/tensorflow_fit_gate.py | fit_zyz | def fit_zyz(target_gate):
"""
Tensorflow example. Given an arbitrary one-qubit gate, use gradient
descent to find corresponding parameters of a universal ZYZ gate.
"""
assert bk.BACKEND == 'tensorflow'
tf = bk.TL
steps = 4000
t = tf.get_variable('t', [3])
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
opt = tf.train.AdamOptimizer(learning_rate=0.001)
train = opt.minimize(ang, var_list=[t])
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
for step in range(steps):
sess.run(train)
loss = sess.run(ang)
sys.stdout.write('\r')
sys.stdout.write("step: {} gate_angle: {}".format(step, loss))
if loss < 0.0001:
break
print()
return sess.run(t) | python | def fit_zyz(target_gate):
"""
Tensorflow example. Given an arbitrary one-qubit gate, use gradient
descent to find corresponding parameters of a universal ZYZ gate.
"""
assert bk.BACKEND == 'tensorflow'
tf = bk.TL
steps = 4000
t = tf.get_variable('t', [3])
gate = qf.ZYZ(t[0], t[1], t[2])
ang = qf.fubini_study_angle(target_gate.vec, gate.vec)
opt = tf.train.AdamOptimizer(learning_rate=0.001)
train = opt.minimize(ang, var_list=[t])
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
for step in range(steps):
sess.run(train)
loss = sess.run(ang)
sys.stdout.write('\r')
sys.stdout.write("step: {} gate_angle: {}".format(step, loss))
if loss < 0.0001:
break
print()
return sess.run(t) | [
"def",
"fit_zyz",
"(",
"target_gate",
")",
":",
"assert",
"bk",
".",
"BACKEND",
"==",
"'tensorflow'",
"tf",
"=",
"bk",
".",
"TL",
"steps",
"=",
"4000",
"t",
"=",
"tf",
".",
"get_variable",
"(",
"'t'",
",",
"[",
"3",
"]",
")",
"gate",
"=",
"qf",
"... | Tensorflow example. Given an arbitrary one-qubit gate, use gradient
descent to find corresponding parameters of a universal ZYZ gate. | [
"Tensorflow",
"example",
".",
"Given",
"an",
"arbitrary",
"one",
"-",
"qubit",
"gate",
"use",
"gradient",
"descent",
"to",
"find",
"corresponding",
"parameters",
"of",
"a",
"universal",
"ZYZ",
"gate",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow_fit_gate.py#L20-L50 | train | 229,747 |
rigetti/quantumflow | quantumflow/decompositions.py | zyz_decomposition | def zyz_decomposition(gate: Gate) -> Circuit:
"""
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
"""
if gate.qubit_nb != 1:
raise ValueError('Expected 1-qubit gate')
q, = gate.qubits
U = asarray(gate.asoperator())
U /= np.linalg.det(U) ** (1/2) # SU(2)
if abs(U[0, 0]) > abs(U[1, 0]):
theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1))
else:
theta1 = 2 * np.arcsin(min(abs(U[1, 0]), 1))
cos_halftheta1 = np.cos(theta1/2)
if not np.isclose(cos_halftheta1, 0.0):
phase = U[1, 1] / cos_halftheta1
theta0_plus_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
else:
theta0_plus_theta2 = 0.0
sin_halftheta1 = np.sin(theta1/2)
if not np.isclose(sin_halftheta1, 0.0):
phase = U[1, 0] / sin_halftheta1
theta0_sub_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
else:
theta0_sub_theta2 = 0.0
theta0 = (theta0_plus_theta2 + theta0_sub_theta2) / 2
theta2 = (theta0_plus_theta2 - theta0_sub_theta2) / 2
t0 = theta0/np.pi
t1 = theta1/np.pi
t2 = theta2/np.pi
circ1 = Circuit()
circ1 += TZ(t2, q)
circ1 += TY(t1, q)
circ1 += TZ(t0, q)
return circ1 | python | def zyz_decomposition(gate: Gate) -> Circuit:
"""
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
"""
if gate.qubit_nb != 1:
raise ValueError('Expected 1-qubit gate')
q, = gate.qubits
U = asarray(gate.asoperator())
U /= np.linalg.det(U) ** (1/2) # SU(2)
if abs(U[0, 0]) > abs(U[1, 0]):
theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1))
else:
theta1 = 2 * np.arcsin(min(abs(U[1, 0]), 1))
cos_halftheta1 = np.cos(theta1/2)
if not np.isclose(cos_halftheta1, 0.0):
phase = U[1, 1] / cos_halftheta1
theta0_plus_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
else:
theta0_plus_theta2 = 0.0
sin_halftheta1 = np.sin(theta1/2)
if not np.isclose(sin_halftheta1, 0.0):
phase = U[1, 0] / sin_halftheta1
theta0_sub_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
else:
theta0_sub_theta2 = 0.0
theta0 = (theta0_plus_theta2 + theta0_sub_theta2) / 2
theta2 = (theta0_plus_theta2 - theta0_sub_theta2) / 2
t0 = theta0/np.pi
t1 = theta1/np.pi
t2 = theta2/np.pi
circ1 = Circuit()
circ1 += TZ(t2, q)
circ1 += TY(t1, q)
circ1 += TZ(t0, q)
return circ1 | [
"def",
"zyz_decomposition",
"(",
"gate",
":",
"Gate",
")",
"->",
"Circuit",
":",
"if",
"gate",
".",
"qubit_nb",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Expected 1-qubit gate'",
")",
"q",
",",
"=",
"gate",
".",
"qubits",
"U",
"=",
"asarray",
"(",
... | Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. | [
"Returns",
"the",
"Euler",
"Z",
"-",
"Y",
"-",
"Z",
"decomposition",
"of",
"a",
"local",
"1",
"-",
"qubit",
"gate",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L65-L108 | train | 229,748 |
rigetti/quantumflow | quantumflow/decompositions.py | kronecker_decomposition | def kronecker_decomposition(gate: Gate) -> Circuit:
"""
Decompose a 2-qubit unitary composed of two 1-qubit local gates.
Uses the "Nearest Kronecker Product" algorithm. Will give erratic
results if the gate is not the direct product of two 1-qubit gates.
"""
# An alternative approach would be to take partial traces, but
# this approach appears to be more robust.
if gate.qubit_nb != 2:
raise ValueError('Expected 2-qubit gate')
U = asarray(gate.asoperator())
rank = 2**gate.qubit_nb
U /= np.linalg.det(U) ** (1/rank)
R = np.stack([U[0:2, 0:2].reshape(4),
U[0:2, 2:4].reshape(4),
U[2:4, 0:2].reshape(4),
U[2:4, 2:4].reshape(4)])
u, s, vh = np.linalg.svd(R)
v = vh.transpose()
A = (np.sqrt(s[0]) * u[:, 0]).reshape(2, 2)
B = (np.sqrt(s[0]) * v[:, 0]).reshape(2, 2)
q0, q1 = gate.qubits
g0 = Gate(A, qubits=[q0])
g1 = Gate(B, qubits=[q1])
if not gates_close(gate, Circuit([g0, g1]).asgate()):
raise ValueError("Gate cannot be decomposed into two 1-qubit gates")
circ = Circuit()
circ += zyz_decomposition(g0)
circ += zyz_decomposition(g1)
assert gates_close(gate, circ.asgate()) # Sanity check
return circ | python | def kronecker_decomposition(gate: Gate) -> Circuit:
"""
Decompose a 2-qubit unitary composed of two 1-qubit local gates.
Uses the "Nearest Kronecker Product" algorithm. Will give erratic
results if the gate is not the direct product of two 1-qubit gates.
"""
# An alternative approach would be to take partial traces, but
# this approach appears to be more robust.
if gate.qubit_nb != 2:
raise ValueError('Expected 2-qubit gate')
U = asarray(gate.asoperator())
rank = 2**gate.qubit_nb
U /= np.linalg.det(U) ** (1/rank)
R = np.stack([U[0:2, 0:2].reshape(4),
U[0:2, 2:4].reshape(4),
U[2:4, 0:2].reshape(4),
U[2:4, 2:4].reshape(4)])
u, s, vh = np.linalg.svd(R)
v = vh.transpose()
A = (np.sqrt(s[0]) * u[:, 0]).reshape(2, 2)
B = (np.sqrt(s[0]) * v[:, 0]).reshape(2, 2)
q0, q1 = gate.qubits
g0 = Gate(A, qubits=[q0])
g1 = Gate(B, qubits=[q1])
if not gates_close(gate, Circuit([g0, g1]).asgate()):
raise ValueError("Gate cannot be decomposed into two 1-qubit gates")
circ = Circuit()
circ += zyz_decomposition(g0)
circ += zyz_decomposition(g1)
assert gates_close(gate, circ.asgate()) # Sanity check
return circ | [
"def",
"kronecker_decomposition",
"(",
"gate",
":",
"Gate",
")",
"->",
"Circuit",
":",
"# An alternative approach would be to take partial traces, but",
"# this approach appears to be more robust.",
"if",
"gate",
".",
"qubit_nb",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
... | Decompose a 2-qubit unitary composed of two 1-qubit local gates.
Uses the "Nearest Kronecker Product" algorithm. Will give erratic
results if the gate is not the direct product of two 1-qubit gates. | [
"Decompose",
"a",
"2",
"-",
"qubit",
"unitary",
"composed",
"of",
"two",
"1",
"-",
"qubit",
"local",
"gates",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L111-L150 | train | 229,749 |
rigetti/quantumflow | quantumflow/decompositions.py | canonical_coords | def canonical_coords(gate: Gate) -> Sequence[float]:
"""Returns the canonical coordinates of a 2-qubit gate"""
circ = canonical_decomposition(gate)
gate = circ.elements[6] # type: ignore
params = [gate.params[key] for key in ('tx', 'ty', 'tz')]
return params | python | def canonical_coords(gate: Gate) -> Sequence[float]:
"""Returns the canonical coordinates of a 2-qubit gate"""
circ = canonical_decomposition(gate)
gate = circ.elements[6] # type: ignore
params = [gate.params[key] for key in ('tx', 'ty', 'tz')]
return params | [
"def",
"canonical_coords",
"(",
"gate",
":",
"Gate",
")",
"->",
"Sequence",
"[",
"float",
"]",
":",
"circ",
"=",
"canonical_decomposition",
"(",
"gate",
")",
"gate",
"=",
"circ",
".",
"elements",
"[",
"6",
"]",
"# type: ignore",
"params",
"=",
"[",
"gate... | Returns the canonical coordinates of a 2-qubit gate | [
"Returns",
"the",
"canonical",
"coordinates",
"of",
"a",
"2",
"-",
"qubit",
"gate"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L153-L158 | train | 229,750 |
rigetti/quantumflow | quantumflow/decompositions.py | _eig_complex_symmetric | def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Diagonalize a complex symmetric matrix. The eigenvalues are
complex, and the eigenvectors form an orthogonal matrix.
Returns:
eigenvalues, eigenvectors
"""
if not np.allclose(M, M.transpose()):
raise np.linalg.LinAlgError('Not a symmetric matrix')
# The matrix of eigenvectors should be orthogonal.
# But the standard 'eig' method will fail to return an orthogonal
# eigenvector matrix when the eigenvalues are degenerate. However,
# both the real and
# imaginary part of M must be symmetric with the same orthogonal
# matrix of eigenvectors. But either the real or imaginary part could
# vanish. So we use a randomized algorithm where we diagonalize a
# random linear combination of real and imaginary parts to find the
# eigenvectors, taking advantage of the 'eigh' subroutine for
# diagonalizing symmetric matrices.
# This can fail if we're very unlucky with our random coefficient, so we
# give the algorithm a few chances to succeed.
# Empirically, never seems to fail on randomly sampled complex
# symmetric 4x4 matrices.
# If failure rate is less than 1 in a million, then 16 rounds
# will have overall failure rate less than 1 in a googol.
# However, cannot (yet) guarantee that there aren't special cases
# which have much higher failure rates.
# GEC 2018
max_attempts = 16
for _ in range(max_attempts):
c = np.random.uniform(0, 1)
matrix = c * M.real + (1-c) * M.imag
_, eigvecs = np.linalg.eigh(matrix)
eigvecs = np.array(eigvecs, dtype=complex)
eigvals = np.diag(eigvecs.transpose() @ M @ eigvecs)
# Finish if we got a correct answer.
reconstructed = eigvecs @ np.diag(eigvals) @ eigvecs.transpose()
if np.allclose(M, reconstructed):
return eigvals, eigvecs
# Should never happen. Hopefully.
raise np.linalg.LinAlgError(
'Cannot diagonalize complex symmetric matrix.') | python | def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Diagonalize a complex symmetric matrix. The eigenvalues are
complex, and the eigenvectors form an orthogonal matrix.
Returns:
eigenvalues, eigenvectors
"""
if not np.allclose(M, M.transpose()):
raise np.linalg.LinAlgError('Not a symmetric matrix')
# The matrix of eigenvectors should be orthogonal.
# But the standard 'eig' method will fail to return an orthogonal
# eigenvector matrix when the eigenvalues are degenerate. However,
# both the real and
# imaginary part of M must be symmetric with the same orthogonal
# matrix of eigenvectors. But either the real or imaginary part could
# vanish. So we use a randomized algorithm where we diagonalize a
# random linear combination of real and imaginary parts to find the
# eigenvectors, taking advantage of the 'eigh' subroutine for
# diagonalizing symmetric matrices.
# This can fail if we're very unlucky with our random coefficient, so we
# give the algorithm a few chances to succeed.
# Empirically, never seems to fail on randomly sampled complex
# symmetric 4x4 matrices.
# If failure rate is less than 1 in a million, then 16 rounds
# will have overall failure rate less than 1 in a googol.
# However, cannot (yet) guarantee that there aren't special cases
# which have much higher failure rates.
# GEC 2018
max_attempts = 16
for _ in range(max_attempts):
c = np.random.uniform(0, 1)
matrix = c * M.real + (1-c) * M.imag
_, eigvecs = np.linalg.eigh(matrix)
eigvecs = np.array(eigvecs, dtype=complex)
eigvals = np.diag(eigvecs.transpose() @ M @ eigvecs)
# Finish if we got a correct answer.
reconstructed = eigvecs @ np.diag(eigvals) @ eigvecs.transpose()
if np.allclose(M, reconstructed):
return eigvals, eigvecs
# Should never happen. Hopefully.
raise np.linalg.LinAlgError(
'Cannot diagonalize complex symmetric matrix.') | [
"def",
"_eig_complex_symmetric",
"(",
"M",
":",
"np",
".",
"ndarray",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"if",
"not",
"np",
".",
"allclose",
"(",
"M",
",",
"M",
".",
"transpose",
"(",
")",
")",
":"... | Diagonalize a complex symmetric matrix. The eigenvalues are
complex, and the eigenvectors form an orthogonal matrix.
Returns:
eigenvalues, eigenvectors | [
"Diagonalize",
"a",
"complex",
"symmetric",
"matrix",
".",
"The",
"eigenvalues",
"are",
"complex",
"and",
"the",
"eigenvectors",
"form",
"an",
"orthogonal",
"matrix",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L262-L309 | train | 229,751 |
rigetti/quantumflow | examples/qaoa_maxcut.py | maxcut_qaoa | def maxcut_qaoa(
graph,
steps=DEFAULT_STEPS,
learning_rate=LEARNING_RATE,
verbose=False):
"""QAOA Maxcut using tensorflow"""
if not isinstance(graph, nx.Graph):
graph = nx.from_edgelist(graph)
init_scale = 0.01
init_bias = 0.5
init_beta = normal(loc=init_bias, scale=init_scale, size=[steps])
init_gamma = normal(loc=init_bias, scale=init_scale, size=[steps])
beta = tf.get_variable('beta', initializer=init_beta)
gamma = tf.get_variable('gamma', initializer=init_gamma)
circ = qubo_circuit(graph, steps, beta, gamma)
cuts = graph_cuts(graph)
maxcut = cuts.max()
expect = circ.run().expectation(cuts)
loss = - expect
# === Optimization ===
opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train = opt.minimize(loss, var_list=[beta, gamma])
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
block = 10
min_difference = 0.0001
last_ratio = -1
for step in range(0, MAX_OPT_STEPS, block):
for _ in range(block):
sess.run(train)
ratio = sess.run(expect) / maxcut
if ratio - last_ratio < min_difference:
break
last_ratio = ratio
if verbose:
print("# step: {} ratio: {:.4f}%".format(step, ratio))
opt_beta = sess.run(beta)
opt_gamma = sess.run(gamma)
return ratio, opt_beta, opt_gamma | python | def maxcut_qaoa(
graph,
steps=DEFAULT_STEPS,
learning_rate=LEARNING_RATE,
verbose=False):
"""QAOA Maxcut using tensorflow"""
if not isinstance(graph, nx.Graph):
graph = nx.from_edgelist(graph)
init_scale = 0.01
init_bias = 0.5
init_beta = normal(loc=init_bias, scale=init_scale, size=[steps])
init_gamma = normal(loc=init_bias, scale=init_scale, size=[steps])
beta = tf.get_variable('beta', initializer=init_beta)
gamma = tf.get_variable('gamma', initializer=init_gamma)
circ = qubo_circuit(graph, steps, beta, gamma)
cuts = graph_cuts(graph)
maxcut = cuts.max()
expect = circ.run().expectation(cuts)
loss = - expect
# === Optimization ===
opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train = opt.minimize(loss, var_list=[beta, gamma])
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
block = 10
min_difference = 0.0001
last_ratio = -1
for step in range(0, MAX_OPT_STEPS, block):
for _ in range(block):
sess.run(train)
ratio = sess.run(expect) / maxcut
if ratio - last_ratio < min_difference:
break
last_ratio = ratio
if verbose:
print("# step: {} ratio: {:.4f}%".format(step, ratio))
opt_beta = sess.run(beta)
opt_gamma = sess.run(gamma)
return ratio, opt_beta, opt_gamma | [
"def",
"maxcut_qaoa",
"(",
"graph",
",",
"steps",
"=",
"DEFAULT_STEPS",
",",
"learning_rate",
"=",
"LEARNING_RATE",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"nx",
".",
"Graph",
")",
":",
"graph",
"=",
"nx",
... | QAOA Maxcut using tensorflow | [
"QAOA",
"Maxcut",
"using",
"tensorflow"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/qaoa_maxcut.py#L37-L87 | train | 229,752 |
rigetti/quantumflow | quantumflow/gates.py | identity_gate | def identity_gate(qubits: Union[int, Qubits]) -> Gate:
"""Returns the K-qubit identity gate"""
_, qubits = qubits_count_tuple(qubits)
return I(*qubits) | python | def identity_gate(qubits: Union[int, Qubits]) -> Gate:
"""Returns the K-qubit identity gate"""
_, qubits = qubits_count_tuple(qubits)
return I(*qubits) | [
"def",
"identity_gate",
"(",
"qubits",
":",
"Union",
"[",
"int",
",",
"Qubits",
"]",
")",
"->",
"Gate",
":",
"_",
",",
"qubits",
"=",
"qubits_count_tuple",
"(",
"qubits",
")",
"return",
"I",
"(",
"*",
"qubits",
")"
] | Returns the K-qubit identity gate | [
"Returns",
"the",
"K",
"-",
"qubit",
"identity",
"gate"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L57-L60 | train | 229,753 |
rigetti/quantumflow | quantumflow/gates.py | join_gates | def join_gates(*gates: Gate) -> Gate:
"""Direct product of two gates. Qubit count is the sum of each gate's
bit count."""
vectors = [gate.vec for gate in gates]
vec = reduce(outer_product, vectors)
return Gate(vec.tensor, vec.qubits) | python | def join_gates(*gates: Gate) -> Gate:
"""Direct product of two gates. Qubit count is the sum of each gate's
bit count."""
vectors = [gate.vec for gate in gates]
vec = reduce(outer_product, vectors)
return Gate(vec.tensor, vec.qubits) | [
"def",
"join_gates",
"(",
"*",
"gates",
":",
"Gate",
")",
"->",
"Gate",
":",
"vectors",
"=",
"[",
"gate",
".",
"vec",
"for",
"gate",
"in",
"gates",
"]",
"vec",
"=",
"reduce",
"(",
"outer_product",
",",
"vectors",
")",
"return",
"Gate",
"(",
"vec",
... | Direct product of two gates. Qubit count is the sum of each gate's
bit count. | [
"Direct",
"product",
"of",
"two",
"gates",
".",
"Qubit",
"count",
"is",
"the",
"sum",
"of",
"each",
"gate",
"s",
"bit",
"count",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L63-L68 | train | 229,754 |
rigetti/quantumflow | quantumflow/gates.py | control_gate | def control_gate(control: Qubit, gate: Gate) -> Gate:
"""Return a controlled unitary gate. Given a gate acting on K qubits,
return a new gate on K+1 qubits prepended with a control bit. """
if control in gate.qubits:
raise ValueError('Gate and control qubits overlap')
qubits = [control, *gate.qubits]
gate_tensor = join_gates(P0(control), identity_gate(gate.qubits)).tensor \
+ join_gates(P1(control), gate).tensor
controlled_gate = Gate(qubits=qubits, tensor=gate_tensor)
return controlled_gate | python | def control_gate(control: Qubit, gate: Gate) -> Gate:
"""Return a controlled unitary gate. Given a gate acting on K qubits,
return a new gate on K+1 qubits prepended with a control bit. """
if control in gate.qubits:
raise ValueError('Gate and control qubits overlap')
qubits = [control, *gate.qubits]
gate_tensor = join_gates(P0(control), identity_gate(gate.qubits)).tensor \
+ join_gates(P1(control), gate).tensor
controlled_gate = Gate(qubits=qubits, tensor=gate_tensor)
return controlled_gate | [
"def",
"control_gate",
"(",
"control",
":",
"Qubit",
",",
"gate",
":",
"Gate",
")",
"->",
"Gate",
":",
"if",
"control",
"in",
"gate",
".",
"qubits",
":",
"raise",
"ValueError",
"(",
"'Gate and control qubits overlap'",
")",
"qubits",
"=",
"[",
"control",
"... | Return a controlled unitary gate. Given a gate acting on K qubits,
return a new gate on K+1 qubits prepended with a control bit. | [
"Return",
"a",
"controlled",
"unitary",
"gate",
".",
"Given",
"a",
"gate",
"acting",
"on",
"K",
"qubits",
"return",
"a",
"new",
"gate",
"on",
"K",
"+",
"1",
"qubits",
"prepended",
"with",
"a",
"control",
"bit",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L71-L83 | train | 229,755 |
rigetti/quantumflow | quantumflow/gates.py | conditional_gate | def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate:
"""Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1"""
assert gate0.qubits == gate1.qubits # FIXME
tensor = join_gates(P0(control), gate0).tensor
tensor += join_gates(P1(control), gate1).tensor
gate = Gate(tensor=tensor, qubits=[control, *gate0.qubits])
return gate | python | def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate:
"""Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1"""
assert gate0.qubits == gate1.qubits # FIXME
tensor = join_gates(P0(control), gate0).tensor
tensor += join_gates(P1(control), gate1).tensor
gate = Gate(tensor=tensor, qubits=[control, *gate0.qubits])
return gate | [
"def",
"conditional_gate",
"(",
"control",
":",
"Qubit",
",",
"gate0",
":",
"Gate",
",",
"gate1",
":",
"Gate",
")",
"->",
"Gate",
":",
"assert",
"gate0",
".",
"qubits",
"==",
"gate1",
".",
"qubits",
"# FIXME",
"tensor",
"=",
"join_gates",
"(",
"P0",
"(... | Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1 | [
"Return",
"a",
"conditional",
"unitary",
"gate",
".",
"Do",
"gate0",
"on",
"bit",
"1",
"if",
"bit",
"0",
"is",
"zero",
"else",
"do",
"gate1",
"on",
"1"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L86-L94 | train | 229,756 |
rigetti/quantumflow | quantumflow/gates.py | print_gate | def print_gate(gate: Gate, ndigits: int = 2,
file: TextIO = None) -> None:
"""Pretty print a gate tensor
Args:
gate:
ndigits:
file: Stream to which to write. Defaults to stdout
"""
N = gate.qubit_nb
gate_tensor = gate.vec.asarray()
lines = []
for index, amplitude in np.ndenumerate(gate_tensor):
ket = "".join([str(n) for n in index[0:N]])
bra = "".join([str(index[n]) for n in range(N, 2*N)])
if round(abs(amplitude)**2, ndigits) > 0.0:
lines.append('{} -> {} : {}'.format(bra, ket, amplitude))
lines.sort(key=lambda x: int(x[0:N]))
print('\n'.join(lines), file=file) | python | def print_gate(gate: Gate, ndigits: int = 2,
file: TextIO = None) -> None:
"""Pretty print a gate tensor
Args:
gate:
ndigits:
file: Stream to which to write. Defaults to stdout
"""
N = gate.qubit_nb
gate_tensor = gate.vec.asarray()
lines = []
for index, amplitude in np.ndenumerate(gate_tensor):
ket = "".join([str(n) for n in index[0:N]])
bra = "".join([str(index[n]) for n in range(N, 2*N)])
if round(abs(amplitude)**2, ndigits) > 0.0:
lines.append('{} -> {} : {}'.format(bra, ket, amplitude))
lines.sort(key=lambda x: int(x[0:N]))
print('\n'.join(lines), file=file) | [
"def",
"print_gate",
"(",
"gate",
":",
"Gate",
",",
"ndigits",
":",
"int",
"=",
"2",
",",
"file",
":",
"TextIO",
"=",
"None",
")",
"->",
"None",
":",
"N",
"=",
"gate",
".",
"qubit_nb",
"gate_tensor",
"=",
"gate",
".",
"vec",
".",
"asarray",
"(",
... | Pretty print a gate tensor
Args:
gate:
ndigits:
file: Stream to which to write. Defaults to stdout | [
"Pretty",
"print",
"a",
"gate",
"tensor"
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L116-L134 | train | 229,757 |
rigetti/quantumflow | quantumflow/gates.py | random_gate | def random_gate(qubits: Union[int, Qubits]) -> Gate:
r"""Returns a random unitary gate on K qubits.
Ref:
"How to generate random matrices from the classical compact groups"
Francesco Mezzadri, math-ph/0609050
"""
N, qubits = qubits_count_tuple(qubits)
unitary = scipy.stats.unitary_group.rvs(2**N)
return Gate(unitary, qubits=qubits, name='RAND{}'.format(N)) | python | def random_gate(qubits: Union[int, Qubits]) -> Gate:
r"""Returns a random unitary gate on K qubits.
Ref:
"How to generate random matrices from the classical compact groups"
Francesco Mezzadri, math-ph/0609050
"""
N, qubits = qubits_count_tuple(qubits)
unitary = scipy.stats.unitary_group.rvs(2**N)
return Gate(unitary, qubits=qubits, name='RAND{}'.format(N)) | [
"def",
"random_gate",
"(",
"qubits",
":",
"Union",
"[",
"int",
",",
"Qubits",
"]",
")",
"->",
"Gate",
":",
"N",
",",
"qubits",
"=",
"qubits_count_tuple",
"(",
"qubits",
")",
"unitary",
"=",
"scipy",
".",
"stats",
".",
"unitary_group",
".",
"rvs",
"(",
... | r"""Returns a random unitary gate on K qubits.
Ref:
"How to generate random matrices from the classical compact groups"
Francesco Mezzadri, math-ph/0609050 | [
"r",
"Returns",
"a",
"random",
"unitary",
"gate",
"on",
"K",
"qubits",
"."
] | 13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L159-L168 | train | 229,758 |
VirusTotal/yara-python | setup.py | has_function | def has_function(function_name, libraries=None):
"""Checks if a given functions exists in the current platform."""
compiler = distutils.ccompiler.new_compiler()
with muted(sys.stdout, sys.stderr):
result = compiler.has_function(
function_name, libraries=libraries)
if os.path.exists('a.out'):
os.remove('a.out')
return result | python | def has_function(function_name, libraries=None):
"""Checks if a given functions exists in the current platform."""
compiler = distutils.ccompiler.new_compiler()
with muted(sys.stdout, sys.stderr):
result = compiler.has_function(
function_name, libraries=libraries)
if os.path.exists('a.out'):
os.remove('a.out')
return result | [
"def",
"has_function",
"(",
"function_name",
",",
"libraries",
"=",
"None",
")",
":",
"compiler",
"=",
"distutils",
".",
"ccompiler",
".",
"new_compiler",
"(",
")",
"with",
"muted",
"(",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
")",
":",
"result"... | Checks if a given functions exists in the current platform. | [
"Checks",
"if",
"a",
"given",
"functions",
"exists",
"in",
"the",
"current",
"platform",
"."
] | c3992bdc3a95d42e9df249ae92e726b74737e859 | https://github.com/VirusTotal/yara-python/blob/c3992bdc3a95d42e9df249ae92e726b74737e859/setup.py#L80-L88 | train | 229,759 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_agent_message | async def handle_agent_message(self, agent_addr, message):
"""Dispatch messages received from agents to the right handlers"""
message_handlers = {
AgentHello: self.handle_agent_hello,
AgentJobStarted: self.handle_agent_job_started,
AgentJobDone: self.handle_agent_job_done,
AgentJobSSHDebug: self.handle_agent_job_ssh_debug,
Pong: self._handle_pong
}
try:
func = message_handlers[message.__class__]
except:
raise TypeError("Unknown message type %s" % message.__class__)
self._create_safe_task(func(agent_addr, message)) | python | async def handle_agent_message(self, agent_addr, message):
"""Dispatch messages received from agents to the right handlers"""
message_handlers = {
AgentHello: self.handle_agent_hello,
AgentJobStarted: self.handle_agent_job_started,
AgentJobDone: self.handle_agent_job_done,
AgentJobSSHDebug: self.handle_agent_job_ssh_debug,
Pong: self._handle_pong
}
try:
func = message_handlers[message.__class__]
except:
raise TypeError("Unknown message type %s" % message.__class__)
self._create_safe_task(func(agent_addr, message)) | [
"async",
"def",
"handle_agent_message",
"(",
"self",
",",
"agent_addr",
",",
"message",
")",
":",
"message_handlers",
"=",
"{",
"AgentHello",
":",
"self",
".",
"handle_agent_hello",
",",
"AgentJobStarted",
":",
"self",
".",
"handle_agent_job_started",
",",
"AgentJ... | Dispatch messages received from agents to the right handlers | [
"Dispatch",
"messages",
"received",
"from",
"agents",
"to",
"the",
"right",
"handlers"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L59-L72 | train | 229,760 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_client_hello | async def handle_client_hello(self, client_addr, _: ClientHello):
""" Handle an ClientHello message. Send available containers to the client """
self._logger.info("New client connected %s", client_addr)
self._registered_clients.add(client_addr)
await self.send_container_update_to_client([client_addr]) | python | async def handle_client_hello(self, client_addr, _: ClientHello):
""" Handle an ClientHello message. Send available containers to the client """
self._logger.info("New client connected %s", client_addr)
self._registered_clients.add(client_addr)
await self.send_container_update_to_client([client_addr]) | [
"async",
"def",
"handle_client_hello",
"(",
"self",
",",
"client_addr",
",",
"_",
":",
"ClientHello",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"New client connected %s\"",
",",
"client_addr",
")",
"self",
".",
"_registered_clients",
".",
"add",
"(... | Handle an ClientHello message. Send available containers to the client | [
"Handle",
"an",
"ClientHello",
"message",
".",
"Send",
"available",
"containers",
"to",
"the",
"client"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L103-L107 | train | 229,761 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_client_ping | async def handle_client_ping(self, client_addr, _: Ping):
""" Handle an Ping message. Pong the client """
await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong()) | python | async def handle_client_ping(self, client_addr, _: Ping):
""" Handle an Ping message. Pong the client """
await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong()) | [
"async",
"def",
"handle_client_ping",
"(",
"self",
",",
"client_addr",
",",
"_",
":",
"Ping",
")",
":",
"await",
"ZMQUtils",
".",
"send_with_addr",
"(",
"self",
".",
"_client_socket",
",",
"client_addr",
",",
"Pong",
"(",
")",
")"
] | Handle an Ping message. Pong the client | [
"Handle",
"an",
"Ping",
"message",
".",
"Pong",
"the",
"client"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L109-L111 | train | 229,762 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_client_new_job | async def handle_client_new_job(self, client_addr, message: ClientNewJob):
""" Handle an ClientNewJob message. Add a job to the queue and triggers an update """
self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id)
self._waiting_jobs[(client_addr, message.job_id)] = message
await self.update_queue() | python | async def handle_client_new_job(self, client_addr, message: ClientNewJob):
""" Handle an ClientNewJob message. Add a job to the queue and triggers an update """
self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id)
self._waiting_jobs[(client_addr, message.job_id)] = message
await self.update_queue() | [
"async",
"def",
"handle_client_new_job",
"(",
"self",
",",
"client_addr",
",",
"message",
":",
"ClientNewJob",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Adding a new job %s %s to the queue\"",
",",
"client_addr",
",",
"message",
".",
"job_id",
")",
... | Handle an ClientNewJob message. Add a job to the queue and triggers an update | [
"Handle",
"an",
"ClientNewJob",
"message",
".",
"Add",
"a",
"job",
"to",
"the",
"queue",
"and",
"triggers",
"an",
"update"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L113-L117 | train | 229,763 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_client_kill_job | async def handle_client_kill_job(self, client_addr, message: ClientKillJob):
""" Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """
# Check if the job is not in the queue
if (client_addr, message.job_id) in self._waiting_jobs:
del self._waiting_jobs[(client_addr, message.job_id)]
# Do not forget to send a JobDone
await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(message.job_id, ("killed", "You killed the job"),
0.0, {}, {}, {}, "", None, "", ""))
# If the job is running, transmit the info to the agent
elif (client_addr, message.job_id) in self._job_running:
agent_addr = self._job_running[(client_addr, message.job_id)][0]
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendKillJob((client_addr, message.job_id)))
else:
self._logger.warning("Client %s attempted to kill unknown job %s", str(client_addr), str(message.job_id)) | python | async def handle_client_kill_job(self, client_addr, message: ClientKillJob):
""" Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """
# Check if the job is not in the queue
if (client_addr, message.job_id) in self._waiting_jobs:
del self._waiting_jobs[(client_addr, message.job_id)]
# Do not forget to send a JobDone
await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(message.job_id, ("killed", "You killed the job"),
0.0, {}, {}, {}, "", None, "", ""))
# If the job is running, transmit the info to the agent
elif (client_addr, message.job_id) in self._job_running:
agent_addr = self._job_running[(client_addr, message.job_id)][0]
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendKillJob((client_addr, message.job_id)))
else:
self._logger.warning("Client %s attempted to kill unknown job %s", str(client_addr), str(message.job_id)) | [
"async",
"def",
"handle_client_kill_job",
"(",
"self",
",",
"client_addr",
",",
"message",
":",
"ClientKillJob",
")",
":",
"# Check if the job is not in the queue",
"if",
"(",
"client_addr",
",",
"message",
".",
"job_id",
")",
"in",
"self",
".",
"_waiting_jobs",
"... | Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. | [
"Handle",
"an",
"ClientKillJob",
"message",
".",
"Remove",
"a",
"job",
"from",
"the",
"waiting",
"list",
"or",
"send",
"the",
"kill",
"message",
"to",
"the",
"right",
"agent",
"."
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L119-L132 | train | 229,764 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_client_get_queue | async def handle_client_get_queue(self, client_addr, _: ClientGetQueue):
""" Handles a ClientGetQueue message. Send back info about the job queue"""
#jobs_running: a list of tuples in the form
#(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end)
jobs_running = list()
for backend_job_id, content in self._job_running.items():
jobs_running.append((content[1].job_id, backend_job_id[0] == client_addr, self._registered_agents[content[0]],
content[1].course_id+"/"+content[1].task_id,
content[1].launcher, int(content[2]), int(content[2])+content[1].time_limit))
#jobs_waiting: a list of tuples in the form
#(job_id, is_current_client_job, info, launcher, max_time)
jobs_waiting = list()
for job_client_addr, msg in self._waiting_jobs.items():
if isinstance(msg, ClientNewJob):
jobs_waiting.append((msg.job_id, job_client_addr[0] == client_addr, msg.course_id+"/"+msg.task_id, msg.launcher,
msg.time_limit))
await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendGetQueue(jobs_running, jobs_waiting)) | python | async def handle_client_get_queue(self, client_addr, _: ClientGetQueue):
""" Handles a ClientGetQueue message. Send back info about the job queue"""
#jobs_running: a list of tuples in the form
#(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end)
jobs_running = list()
for backend_job_id, content in self._job_running.items():
jobs_running.append((content[1].job_id, backend_job_id[0] == client_addr, self._registered_agents[content[0]],
content[1].course_id+"/"+content[1].task_id,
content[1].launcher, int(content[2]), int(content[2])+content[1].time_limit))
#jobs_waiting: a list of tuples in the form
#(job_id, is_current_client_job, info, launcher, max_time)
jobs_waiting = list()
for job_client_addr, msg in self._waiting_jobs.items():
if isinstance(msg, ClientNewJob):
jobs_waiting.append((msg.job_id, job_client_addr[0] == client_addr, msg.course_id+"/"+msg.task_id, msg.launcher,
msg.time_limit))
await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendGetQueue(jobs_running, jobs_waiting)) | [
"async",
"def",
"handle_client_get_queue",
"(",
"self",
",",
"client_addr",
",",
"_",
":",
"ClientGetQueue",
")",
":",
"#jobs_running: a list of tuples in the form",
"#(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end)",
"jobs_running",
"=",
"list",
... | Handles a ClientGetQueue message. Send back info about the job queue | [
"Handles",
"a",
"ClientGetQueue",
"message",
".",
"Send",
"back",
"info",
"about",
"the",
"job",
"queue"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L134-L154 | train | 229,765 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.update_queue | async def update_queue(self):
"""
Send waiting jobs to available agents
"""
# For now, round-robin
not_found_for_agent = []
while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0:
agent_addr = self._available_agents.pop(0)
# Find first job that can be run on this agent
found = False
client_addr, job_id, job_msg = None, None, None
for (client_addr, job_id), job_msg in self._waiting_jobs.items():
if job_msg.environment in self._containers_on_agent[agent_addr]:
found = True
break
if not found:
self._logger.debug("Nothing to do for agent %s", agent_addr)
not_found_for_agent.append(agent_addr)
continue
# Remove the job from the queue
del self._waiting_jobs[(client_addr, job_id)]
job_id = (client_addr, job_msg.job_id)
self._job_running[job_id] = (agent_addr, job_msg, time.time())
self._logger.info("Sending job %s %s to agent %s", client_addr, job_msg.job_id, agent_addr)
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendNewJob(job_id, job_msg.course_id, job_msg.task_id,
job_msg.inputdata, job_msg.environment,
job_msg.enable_network, job_msg.time_limit,
job_msg.hard_time_limit, job_msg.mem_limit,
job_msg.debug))
# Do not forget to add again for which we did not find jobs to do
self._available_agents += not_found_for_agent | python | async def update_queue(self):
"""
Send waiting jobs to available agents
"""
# For now, round-robin
not_found_for_agent = []
while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0:
agent_addr = self._available_agents.pop(0)
# Find first job that can be run on this agent
found = False
client_addr, job_id, job_msg = None, None, None
for (client_addr, job_id), job_msg in self._waiting_jobs.items():
if job_msg.environment in self._containers_on_agent[agent_addr]:
found = True
break
if not found:
self._logger.debug("Nothing to do for agent %s", agent_addr)
not_found_for_agent.append(agent_addr)
continue
# Remove the job from the queue
del self._waiting_jobs[(client_addr, job_id)]
job_id = (client_addr, job_msg.job_id)
self._job_running[job_id] = (agent_addr, job_msg, time.time())
self._logger.info("Sending job %s %s to agent %s", client_addr, job_msg.job_id, agent_addr)
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendNewJob(job_id, job_msg.course_id, job_msg.task_id,
job_msg.inputdata, job_msg.environment,
job_msg.enable_network, job_msg.time_limit,
job_msg.hard_time_limit, job_msg.mem_limit,
job_msg.debug))
# Do not forget to add again for which we did not find jobs to do
self._available_agents += not_found_for_agent | [
"async",
"def",
"update_queue",
"(",
"self",
")",
":",
"# For now, round-robin",
"not_found_for_agent",
"=",
"[",
"]",
"while",
"len",
"(",
"self",
".",
"_available_agents",
")",
">",
"0",
"and",
"len",
"(",
"self",
".",
"_waiting_jobs",
")",
">",
"0",
":"... | Send waiting jobs to available agents | [
"Send",
"waiting",
"jobs",
"to",
"available",
"agents"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L156-L193 | train | 229,766 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_agent_hello | async def handle_agent_hello(self, agent_addr, message: AgentHello):
"""
Handle an AgentAvailable message. Add agent_addr to the list of available agents
"""
self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name)
if agent_addr in self._registered_agents:
# Delete previous instance of this agent, if any
await self._delete_agent(agent_addr)
self._registered_agents[agent_addr] = message.friendly_name
self._available_agents.extend([agent_addr for _ in range(0, message.available_job_slots)])
self._containers_on_agent[agent_addr] = message.available_containers.keys()
self._ping_count[agent_addr] = 0
# update information about available containers
for container_name, container_info in message.available_containers.items():
if container_name in self._containers:
# check if the id is the same
if self._containers[container_name][0] == container_info["id"]:
# ok, just add the agent to the list of agents that have the container
self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr))
self._containers[container_name][2].append(agent_addr)
elif self._containers[container_name][1] > container_info["created"]:
# containers stored have been created after the new one
# add the agent, but emit a warning
self._logger.warning("Container %s has multiple version: \n"
"\t Currently registered agents have version %s (%i)\n"
"\t New agent %s has version %s (%i)",
container_name,
self._containers[container_name][0], self._containers[container_name][1],
str(agent_addr), container_info["id"], container_info["created"])
self._containers[container_name][2].append(agent_addr)
else: # self._containers[container_name][1] < container_info["created"]:
# containers stored have been created before the new one
# add the agent, update the infos, and emit a warning
self._logger.warning("Container %s has multiple version: \n"
"\t Currently registered agents have version %s (%i)\n"
"\t New agent %s has version %s (%i)",
container_name,
self._containers[container_name][0], self._containers[container_name][1],
str(agent_addr), container_info["id"], container_info["created"])
self._containers[container_name] = (container_info["id"], container_info["created"],
self._containers[container_name][2] + [agent_addr])
else:
# just add it
self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr))
self._containers[container_name] = (container_info["id"], container_info["created"], [agent_addr])
# update the queue
await self.update_queue()
# update clients
await self.send_container_update_to_client(self._registered_clients) | python | async def handle_agent_hello(self, agent_addr, message: AgentHello):
"""
Handle an AgentAvailable message. Add agent_addr to the list of available agents
"""
self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name)
if agent_addr in self._registered_agents:
# Delete previous instance of this agent, if any
await self._delete_agent(agent_addr)
self._registered_agents[agent_addr] = message.friendly_name
self._available_agents.extend([agent_addr for _ in range(0, message.available_job_slots)])
self._containers_on_agent[agent_addr] = message.available_containers.keys()
self._ping_count[agent_addr] = 0
# update information about available containers
for container_name, container_info in message.available_containers.items():
if container_name in self._containers:
# check if the id is the same
if self._containers[container_name][0] == container_info["id"]:
# ok, just add the agent to the list of agents that have the container
self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr))
self._containers[container_name][2].append(agent_addr)
elif self._containers[container_name][1] > container_info["created"]:
# containers stored have been created after the new one
# add the agent, but emit a warning
self._logger.warning("Container %s has multiple version: \n"
"\t Currently registered agents have version %s (%i)\n"
"\t New agent %s has version %s (%i)",
container_name,
self._containers[container_name][0], self._containers[container_name][1],
str(agent_addr), container_info["id"], container_info["created"])
self._containers[container_name][2].append(agent_addr)
else: # self._containers[container_name][1] < container_info["created"]:
# containers stored have been created before the new one
# add the agent, update the infos, and emit a warning
self._logger.warning("Container %s has multiple version: \n"
"\t Currently registered agents have version %s (%i)\n"
"\t New agent %s has version %s (%i)",
container_name,
self._containers[container_name][0], self._containers[container_name][1],
str(agent_addr), container_info["id"], container_info["created"])
self._containers[container_name] = (container_info["id"], container_info["created"],
self._containers[container_name][2] + [agent_addr])
else:
# just add it
self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr))
self._containers[container_name] = (container_info["id"], container_info["created"], [agent_addr])
# update the queue
await self.update_queue()
# update clients
await self.send_container_update_to_client(self._registered_clients) | [
"async",
"def",
"handle_agent_hello",
"(",
"self",
",",
"agent_addr",
",",
"message",
":",
"AgentHello",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Agent %s (%s) said hello\"",
",",
"agent_addr",
",",
"message",
".",
"friendly_name",
")",
"if",
"ag... | Handle an AgentAvailable message. Add agent_addr to the list of available agents | [
"Handle",
"an",
"AgentAvailable",
"message",
".",
"Add",
"agent_addr",
"to",
"the",
"list",
"of",
"available",
"agents"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L195-L248 | train | 229,767 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_agent_job_started | async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted):
"""Handle an AgentJobStarted message. Send the data back to the client"""
self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr)
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1])) | python | async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted):
"""Handle an AgentJobStarted message. Send the data back to the client"""
self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr)
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1])) | [
"async",
"def",
"handle_agent_job_started",
"(",
"self",
",",
"agent_addr",
",",
"message",
":",
"AgentJobStarted",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Job %s %s started on agent %s\"",
",",
"message",
".",
"job_id",
"[",
"0",
"]",
",",
"me... | Handle an AgentJobStarted message. Send the data back to the client | [
"Handle",
"an",
"AgentJobStarted",
"message",
".",
"Send",
"the",
"data",
"back",
"to",
"the",
"client"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L250-L253 | train | 229,768 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_agent_job_done | async def handle_agent_job_done(self, agent_addr, message: AgentJobDone):
"""Handle an AgentJobDone message. Send the data back to the client, and start new job if needed"""
if agent_addr in self._registered_agents:
self._logger.info("Job %s %s finished on agent %s", message.job_id[0], message.job_id[1], agent_addr)
# Remove the job from the list of running jobs
del self._job_running[message.job_id]
# Sent the data back to the client
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobDone(message.job_id[1], message.result,
message.grade, message.problems,
message.tests, message.custom,
message.state, message.archive,
message.stdout, message.stderr))
# The agent is available now
self._available_agents.append(agent_addr)
else:
self._logger.warning("Job result %s %s from non-registered agent %s", message.job_id[0], message.job_id[1], agent_addr)
# update the queue
await self.update_queue() | python | async def handle_agent_job_done(self, agent_addr, message: AgentJobDone):
"""Handle an AgentJobDone message. Send the data back to the client, and start new job if needed"""
if agent_addr in self._registered_agents:
self._logger.info("Job %s %s finished on agent %s", message.job_id[0], message.job_id[1], agent_addr)
# Remove the job from the list of running jobs
del self._job_running[message.job_id]
# Sent the data back to the client
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobDone(message.job_id[1], message.result,
message.grade, message.problems,
message.tests, message.custom,
message.state, message.archive,
message.stdout, message.stderr))
# The agent is available now
self._available_agents.append(agent_addr)
else:
self._logger.warning("Job result %s %s from non-registered agent %s", message.job_id[0], message.job_id[1], agent_addr)
# update the queue
await self.update_queue() | [
"async",
"def",
"handle_agent_job_done",
"(",
"self",
",",
"agent_addr",
",",
"message",
":",
"AgentJobDone",
")",
":",
"if",
"agent_addr",
"in",
"self",
".",
"_registered_agents",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Job %s %s finished on agent %s\""... | Handle an AgentJobDone message. Send the data back to the client, and start new job if needed | [
"Handle",
"an",
"AgentJobDone",
"message",
".",
"Send",
"the",
"data",
"back",
"to",
"the",
"client",
"and",
"start",
"new",
"job",
"if",
"needed"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L255-L277 | train | 229,769 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend.handle_agent_job_ssh_debug | async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug):
"""Handle an AgentJobSSHDebug message. Send the data back to the client"""
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port,
message.password)) | python | async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug):
"""Handle an AgentJobSSHDebug message. Send the data back to the client"""
await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port,
message.password)) | [
"async",
"def",
"handle_agent_job_ssh_debug",
"(",
"self",
",",
"_",
",",
"message",
":",
"AgentJobSSHDebug",
")",
":",
"await",
"ZMQUtils",
".",
"send_with_addr",
"(",
"self",
".",
"_client_socket",
",",
"message",
".",
"job_id",
"[",
"0",
"]",
",",
"Backen... | Handle an AgentJobSSHDebug message. Send the data back to the client | [
"Handle",
"an",
"AgentJobSSHDebug",
"message",
".",
"Send",
"the",
"data",
"back",
"to",
"the",
"client"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L279-L282 | train | 229,770 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend._do_ping | async def _do_ping(self):
""" Ping the agents """
# the list() call here is needed, as we remove entries from _registered_agents!
for agent_addr, friendly_name in list(self._registered_agents.items()):
try:
ping_count = self._ping_count.get(agent_addr, 0)
if ping_count > 5:
self._logger.warning("Agent %s (%s) does not respond: removing from list.", agent_addr, friendly_name)
delete_agent = True
else:
self._ping_count[agent_addr] = ping_count + 1
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, Ping())
delete_agent = False
except:
# This should not happen, but it's better to check anyway.
self._logger.exception("Failed to send ping to agent %s (%s). Removing it from list.", agent_addr, friendly_name)
delete_agent = True
if delete_agent:
try:
await self._delete_agent(agent_addr)
except:
self._logger.exception("Failed to delete agent %s (%s)!", agent_addr, friendly_name)
self._loop.call_later(1, self._create_safe_task, self._do_ping()) | python | async def _do_ping(self):
""" Ping the agents """
# the list() call here is needed, as we remove entries from _registered_agents!
for agent_addr, friendly_name in list(self._registered_agents.items()):
try:
ping_count = self._ping_count.get(agent_addr, 0)
if ping_count > 5:
self._logger.warning("Agent %s (%s) does not respond: removing from list.", agent_addr, friendly_name)
delete_agent = True
else:
self._ping_count[agent_addr] = ping_count + 1
await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, Ping())
delete_agent = False
except:
# This should not happen, but it's better to check anyway.
self._logger.exception("Failed to send ping to agent %s (%s). Removing it from list.", agent_addr, friendly_name)
delete_agent = True
if delete_agent:
try:
await self._delete_agent(agent_addr)
except:
self._logger.exception("Failed to delete agent %s (%s)!", agent_addr, friendly_name)
self._loop.call_later(1, self._create_safe_task, self._do_ping()) | [
"async",
"def",
"_do_ping",
"(",
"self",
")",
":",
"# the list() call here is needed, as we remove entries from _registered_agents!",
"for",
"agent_addr",
",",
"friendly_name",
"in",
"list",
"(",
"self",
".",
"_registered_agents",
".",
"items",
"(",
")",
")",
":",
"tr... | Ping the agents | [
"Ping",
"the",
"agents"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L314-L339 | train | 229,771 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend._delete_agent | async def _delete_agent(self, agent_addr):
""" Deletes an agent """
self._available_agents = [agent for agent in self._available_agents if agent != agent_addr]
del self._registered_agents[agent_addr]
await self._recover_jobs(agent_addr) | python | async def _delete_agent(self, agent_addr):
""" Deletes an agent """
self._available_agents = [agent for agent in self._available_agents if agent != agent_addr]
del self._registered_agents[agent_addr]
await self._recover_jobs(agent_addr) | [
"async",
"def",
"_delete_agent",
"(",
"self",
",",
"agent_addr",
")",
":",
"self",
".",
"_available_agents",
"=",
"[",
"agent",
"for",
"agent",
"in",
"self",
".",
"_available_agents",
"if",
"agent",
"!=",
"agent_addr",
"]",
"del",
"self",
".",
"_registered_a... | Deletes an agent | [
"Deletes",
"an",
"agent"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L341-L345 | train | 229,772 |
UCL-INGI/INGInious | inginious/backend/backend.py | Backend._recover_jobs | async def _recover_jobs(self, agent_addr):
""" Recover the jobs sent to a crashed agent """
for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())):
if agent == agent_addr:
await ZMQUtils.send_with_addr(self._client_socket, client_addr,
BackendJobDone(job_id, ("crash", "Agent restarted"),
0.0, {}, {}, {}, "", None, None, None))
del self._job_running[(client_addr, job_id)]
await self.update_queue() | python | async def _recover_jobs(self, agent_addr):
""" Recover the jobs sent to a crashed agent """
for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())):
if agent == agent_addr:
await ZMQUtils.send_with_addr(self._client_socket, client_addr,
BackendJobDone(job_id, ("crash", "Agent restarted"),
0.0, {}, {}, {}, "", None, None, None))
del self._job_running[(client_addr, job_id)]
await self.update_queue() | [
"async",
"def",
"_recover_jobs",
"(",
"self",
",",
"agent_addr",
")",
":",
"for",
"(",
"client_addr",
",",
"job_id",
")",
",",
"(",
"agent",
",",
"job_msg",
",",
"_",
")",
"in",
"reversed",
"(",
"list",
"(",
"self",
".",
"_job_running",
".",
"items",
... | Recover the jobs sent to a crashed agent | [
"Recover",
"the",
"jobs",
"sent",
"to",
"a",
"crashed",
"agent"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L347-L356 | train | 229,773 |
UCL-INGI/INGInious | inginious/frontend/accessible_time.py | parse_date | def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y %H",
"%d/%m/%Y"]:
try:
return datetime.strptime(date, format_type)
except ValueError:
pass
raise Exception("Unknown format for " + date) | python | def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y %H",
"%d/%m/%Y"]:
try:
return datetime.strptime(date, format_type)
except ValueError:
pass
raise Exception("Unknown format for " + date) | [
"def",
"parse_date",
"(",
"date",
",",
"default",
"=",
"None",
")",
":",
"if",
"date",
"==",
"\"\"",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown format for \"",
"+",
"date",
")",... | Parse a valid date | [
"Parse",
"a",
"valid",
"date"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L11-L25 | train | 229,774 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.GET | def GET(self):
""" Handles GET request """
if self.user_manager.session_logged_in() or not self.app.allow_registration:
raise web.notfound()
error = False
reset = None
msg = ""
data = web.input()
if "activate" in data:
msg, error = self.activate_user(data)
elif "reset" in data:
msg, error, reset = self.get_reset_data(data)
return self.template_helper.get_renderer().register(reset, msg, error) | python | def GET(self):
""" Handles GET request """
if self.user_manager.session_logged_in() or not self.app.allow_registration:
raise web.notfound()
error = False
reset = None
msg = ""
data = web.input()
if "activate" in data:
msg, error = self.activate_user(data)
elif "reset" in data:
msg, error, reset = self.get_reset_data(data)
return self.template_helper.get_renderer().register(reset, msg, error) | [
"def",
"GET",
"(",
"self",
")",
":",
"if",
"self",
".",
"user_manager",
".",
"session_logged_in",
"(",
")",
"or",
"not",
"self",
".",
"app",
".",
"allow_registration",
":",
"raise",
"web",
".",
"notfound",
"(",
")",
"error",
"=",
"False",
"reset",
"=",... | Handles GET request | [
"Handles",
"GET",
"request"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L20-L35 | train | 229,775 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.get_reset_data | def get_reset_data(self, data):
""" Returns the user info to reset """
error = False
reset = None
msg = ""
user = self.database.users.find_one({"reset": data["reset"]})
if user is None:
error = True
msg = "Invalid reset hash."
else:
reset = {"hash": data["reset"], "username": user["username"], "realname": user["realname"]}
return msg, error, reset | python | def get_reset_data(self, data):
""" Returns the user info to reset """
error = False
reset = None
msg = ""
user = self.database.users.find_one({"reset": data["reset"]})
if user is None:
error = True
msg = "Invalid reset hash."
else:
reset = {"hash": data["reset"], "username": user["username"], "realname": user["realname"]}
return msg, error, reset | [
"def",
"get_reset_data",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"reset",
"=",
"None",
"msg",
"=",
"\"\"",
"user",
"=",
"self",
".",
"database",
".",
"users",
".",
"find_one",
"(",
"{",
"\"reset\"",
":",
"data",
"[",
"\"reset\"",
"... | Returns the user info to reset | [
"Returns",
"the",
"user",
"info",
"to",
"reset"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L37-L49 | train | 229,776 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.register_user | def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
# Check input format
if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None:
error = True
msg = _("Invalid username format.")
elif email_re.match(data["email"]) is None:
error = True
msg = _("Invalid email format.")
elif len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
msg = _("Passwords don't match !")
if not error:
existing_user = self.database.users.find_one({"$or": [{"username": data["username"]}, {"email": data["email"]}]})
if existing_user is not None:
error = True
if existing_user["username"] == data["username"]:
msg = _("This username is already taken !")
else:
msg = _("This email address is already in use !")
else:
passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest()
activate_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()
self.database.users.insert({"username": data["username"],
"realname": data["realname"],
"email": data["email"],
"password": passwd_hash,
"activate": activate_hash,
"bindings": {},
"language": self.user_manager._session.get("language", "en")})
try:
web.sendmail(web.config.smtp_sendername, data["email"], _("Welcome on INGInious"),
_("""Welcome on INGInious !
To activate your account, please click on the following link :
""")
+ web.ctx.home + "/register?activate=" + activate_hash)
msg = _("You are succesfully registered. An email has been sent to you for activation.")
except:
error = True
msg = _("Something went wrong while sending you activation email. Please contact the administrator.")
return msg, error | python | def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
# Check input format
if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None:
error = True
msg = _("Invalid username format.")
elif email_re.match(data["email"]) is None:
error = True
msg = _("Invalid email format.")
elif len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
msg = _("Passwords don't match !")
if not error:
existing_user = self.database.users.find_one({"$or": [{"username": data["username"]}, {"email": data["email"]}]})
if existing_user is not None:
error = True
if existing_user["username"] == data["username"]:
msg = _("This username is already taken !")
else:
msg = _("This email address is already in use !")
else:
passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest()
activate_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()
self.database.users.insert({"username": data["username"],
"realname": data["realname"],
"email": data["email"],
"password": passwd_hash,
"activate": activate_hash,
"bindings": {},
"language": self.user_manager._session.get("language", "en")})
try:
web.sendmail(web.config.smtp_sendername, data["email"], _("Welcome on INGInious"),
_("""Welcome on INGInious !
To activate your account, please click on the following link :
""")
+ web.ctx.home + "/register?activate=" + activate_hash)
msg = _("You are succesfully registered. An email has been sent to you for activation.")
except:
error = True
msg = _("Something went wrong while sending you activation email. Please contact the administrator.")
return msg, error | [
"def",
"register_user",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"email_re",
"=",
"re",
".",
"compile",
"(",
"r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"",
"# dot-atom",
"r'|^\"([\\001-\\010\\013\\014\\016-\\... | Parses input and register user | [
"Parses",
"input",
"and",
"register",
"user"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L63-L117 | train | 229,777 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.lost_passwd | def lost_passwd(self, data):
""" Send a reset link to user to recover its password """
error = False
msg = ""
# Check input format
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
if email_re.match(data["recovery_email"]) is None:
error = True
msg = _("Invalid email format.")
if not error:
reset_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()
user = self.database.users.find_one_and_update({"email": data["recovery_email"]}, {"$set": {"reset": reset_hash}})
if user is None:
error = True
msg = _("This email address was not found in database.")
else:
try:
web.sendmail(web.config.smtp_sendername, data["recovery_email"], _("INGInious password recovery"),
_("""Dear {realname},
Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link :
""").format(realname=user["realname"]) + web.ctx.home + "/register?reset=" + reset_hash)
msg = _("An email has been sent to you to reset your password.")
except:
error = True
msg = _("Something went wrong while sending you reset email. Please contact the administrator.")
return msg, error | python | def lost_passwd(self, data):
""" Send a reset link to user to recover its password """
error = False
msg = ""
# Check input format
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
if email_re.match(data["recovery_email"]) is None:
error = True
msg = _("Invalid email format.")
if not error:
reset_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()
user = self.database.users.find_one_and_update({"email": data["recovery_email"]}, {"$set": {"reset": reset_hash}})
if user is None:
error = True
msg = _("This email address was not found in database.")
else:
try:
web.sendmail(web.config.smtp_sendername, data["recovery_email"], _("INGInious password recovery"),
_("""Dear {realname},
Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link :
""").format(realname=user["realname"]) + web.ctx.home + "/register?reset=" + reset_hash)
msg = _("An email has been sent to you to reset your password.")
except:
error = True
msg = _("Something went wrong while sending you reset email. Please contact the administrator.")
return msg, error | [
"def",
"lost_passwd",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"# Check input format",
"email_re",
"=",
"re",
".",
"compile",
"(",
"r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"",
"# dot-atom",
"r'|^\"([\\001... | Send a reset link to user to recover its password | [
"Send",
"a",
"reset",
"link",
"to",
"user",
"to",
"recover",
"its",
"password"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L119-L151 | train | 229,778 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.reset_passwd | def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
msg = _("Passwords don't match !")
if not error:
passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest()
user = self.database.users.find_one_and_update({"reset": data["reset_hash"]},
{"$set": {"password": passwd_hash},
"$unset": {"reset": True, "activate": True}})
if user is None:
error = True
msg = _("Invalid reset hash.")
else:
msg = _("Your password has been successfully changed.")
return msg, error | python | def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
msg = _("Passwords don't match !")
if not error:
passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest()
user = self.database.users.find_one_and_update({"reset": data["reset_hash"]},
{"$set": {"password": passwd_hash},
"$unset": {"reset": True, "activate": True}})
if user is None:
error = True
msg = _("Invalid reset hash.")
else:
msg = _("Your password has been successfully changed.")
return msg, error | [
"def",
"reset_passwd",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"# Check input format",
"if",
"len",
"(",
"data",
"[",
"\"passwd\"",
"]",
")",
"<",
"6",
":",
"error",
"=",
"True",
"msg",
"=",
"_",
"(",
"\"Passwor... | Reset the user password | [
"Reset",
"the",
"user",
"password"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L153-L177 | train | 229,779 |
UCL-INGI/INGInious | inginious/frontend/pages/register.py | RegistrationPage.POST | def POST(self):
""" Handles POST request """
if self.user_manager.session_logged_in() or not self.app.allow_registration:
raise web.notfound()
reset = None
msg = ""
error = False
data = web.input()
if "register" in data:
msg, error = self.register_user(data)
elif "lostpasswd" in data:
msg, error = self.lost_passwd(data)
elif "resetpasswd" in data:
msg, error, reset = self.get_reset_data(data)
if reset:
msg, error = self.reset_passwd(data)
if not error:
reset = None
return self.template_helper.get_renderer().register(reset, msg, error) | python | def POST(self):
""" Handles POST request """
if self.user_manager.session_logged_in() or not self.app.allow_registration:
raise web.notfound()
reset = None
msg = ""
error = False
data = web.input()
if "register" in data:
msg, error = self.register_user(data)
elif "lostpasswd" in data:
msg, error = self.lost_passwd(data)
elif "resetpasswd" in data:
msg, error, reset = self.get_reset_data(data)
if reset:
msg, error = self.reset_passwd(data)
if not error:
reset = None
return self.template_helper.get_renderer().register(reset, msg, error) | [
"def",
"POST",
"(",
"self",
")",
":",
"if",
"self",
".",
"user_manager",
".",
"session_logged_in",
"(",
")",
"or",
"not",
"self",
".",
"app",
".",
"allow_registration",
":",
"raise",
"web",
".",
"notfound",
"(",
")",
"reset",
"=",
"None",
"msg",
"=",
... | Handles POST request | [
"Handles",
"POST",
"request"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L179-L199 | train | 229,780 |
UCL-INGI/INGInious | inginious/common/task_factory.py | TaskFactory.get_readable_tasks | def get_readable_tasks(self, course):
""" Returns the list of all available tasks in a course """
course_fs = self._filesystem.from_subfolder(course.get_id())
tasks = [
task[0:len(task)-1] # remove trailing /
for task in course_fs.list(folders=True, files=False, recursive=False)
if self._task_file_exists(course_fs.from_subfolder(task))]
return tasks | python | def get_readable_tasks(self, course):
""" Returns the list of all available tasks in a course """
course_fs = self._filesystem.from_subfolder(course.get_id())
tasks = [
task[0:len(task)-1] # remove trailing /
for task in course_fs.list(folders=True, files=False, recursive=False)
if self._task_file_exists(course_fs.from_subfolder(task))]
return tasks | [
"def",
"get_readable_tasks",
"(",
"self",
",",
"course",
")",
":",
"course_fs",
"=",
"self",
".",
"_filesystem",
".",
"from_subfolder",
"(",
"course",
".",
"get_id",
"(",
")",
")",
"tasks",
"=",
"[",
"task",
"[",
"0",
":",
"len",
"(",
"task",
")",
"-... | Returns the list of all available tasks in a course | [
"Returns",
"the",
"list",
"of",
"all",
"available",
"tasks",
"in",
"a",
"course"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L122-L129 | train | 229,781 |
UCL-INGI/INGInious | inginious/common/task_factory.py | TaskFactory._task_file_exists | def _task_file_exists(self, task_fs):
""" Returns true if a task file exists in this directory """
for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]:
if task_fs.exists(filename):
return True
return False | python | def _task_file_exists(self, task_fs):
""" Returns true if a task file exists in this directory """
for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]:
if task_fs.exists(filename):
return True
return False | [
"def",
"_task_file_exists",
"(",
"self",
",",
"task_fs",
")",
":",
"for",
"filename",
"in",
"[",
"\"task.{}\"",
".",
"format",
"(",
"ext",
")",
"for",
"ext",
"in",
"self",
".",
"get_available_task_file_extensions",
"(",
")",
"]",
":",
"if",
"task_fs",
".",... | Returns true if a task file exists in this directory | [
"Returns",
"true",
"if",
"a",
"task",
"file",
"exists",
"in",
"this",
"directory"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L131-L136 | train | 229,782 |
UCL-INGI/INGInious | inginious/common/task_factory.py | TaskFactory.delete_all_possible_task_files | def delete_all_possible_task_files(self, courseid, taskid):
""" Deletes all possibles task files in directory, to allow to change the format """
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
if not id_checker(taskid):
raise InvalidNameException("Task with invalid name: " + taskid)
task_fs = self.get_task_fs(courseid, taskid)
for ext in self.get_available_task_file_extensions():
try:
task_fs.delete("task."+ext)
except:
pass | python | def delete_all_possible_task_files(self, courseid, taskid):
""" Deletes all possibles task files in directory, to allow to change the format """
if not id_checker(courseid):
raise InvalidNameException("Course with invalid name: " + courseid)
if not id_checker(taskid):
raise InvalidNameException("Task with invalid name: " + taskid)
task_fs = self.get_task_fs(courseid, taskid)
for ext in self.get_available_task_file_extensions():
try:
task_fs.delete("task."+ext)
except:
pass | [
"def",
"delete_all_possible_task_files",
"(",
"self",
",",
"courseid",
",",
"taskid",
")",
":",
"if",
"not",
"id_checker",
"(",
"courseid",
")",
":",
"raise",
"InvalidNameException",
"(",
"\"Course with invalid name: \"",
"+",
"courseid",
")",
"if",
"not",
"id_che... | Deletes all possibles task files in directory, to allow to change the format | [
"Deletes",
"all",
"possibles",
"task",
"files",
"in",
"directory",
"to",
"allow",
"to",
"change",
"the",
"format"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L138-L149 | train | 229,783 |
UCL-INGI/INGInious | inginious/frontend/plugins/auth/saml2_auth.py | prepare_request | def prepare_request(settings):
""" Prepare SAML request """
# Set the ACS url and binding method
settings["sp"]["assertionConsumerService"] = {
"url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
}
# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
data = web.input()
return {
'https': 'on' if web.ctx.protocol == 'https' else 'off',
'http_host': web.ctx.environ["SERVER_NAME"],
'server_port': web.ctx.environ["SERVER_PORT"],
'script_name': web.ctx.homepath,
'get_data': data.copy(),
'post_data': data.copy(),
# Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
# 'lowercase_urlencoding': True,
'query_string': web.ctx.query
} | python | def prepare_request(settings):
""" Prepare SAML request """
# Set the ACS url and binding method
settings["sp"]["assertionConsumerService"] = {
"url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
}
# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
data = web.input()
return {
'https': 'on' if web.ctx.protocol == 'https' else 'off',
'http_host': web.ctx.environ["SERVER_NAME"],
'server_port': web.ctx.environ["SERVER_PORT"],
'script_name': web.ctx.homepath,
'get_data': data.copy(),
'post_data': data.copy(),
# Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
# 'lowercase_urlencoding': True,
'query_string': web.ctx.query
} | [
"def",
"prepare_request",
"(",
"settings",
")",
":",
"# Set the ACS url and binding method",
"settings",
"[",
"\"sp\"",
"]",
"[",
"\"assertionConsumerService\"",
"]",
"=",
"{",
"\"url\"",
":",
"web",
".",
"ctx",
".",
"homedomain",
"+",
"web",
".",
"ctx",
".",
... | Prepare SAML request | [
"Prepare",
"SAML",
"request"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/saml2_auth.py#L98-L119 | train | 229,784 |
UCL-INGI/INGInious | inginious/common/filesystems/provider.py | FileSystemProvider._checkpath | def _checkpath(self, path):
""" Checks that a given path is valid. If it's not, raises NotFoundException """
if path.startswith("/") or ".." in path or path.strip() != path:
raise NotFoundException() | python | def _checkpath(self, path):
""" Checks that a given path is valid. If it's not, raises NotFoundException """
if path.startswith("/") or ".." in path or path.strip() != path:
raise NotFoundException() | [
"def",
"_checkpath",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
"or",
"\"..\"",
"in",
"path",
"or",
"path",
".",
"strip",
"(",
")",
"!=",
"path",
":",
"raise",
"NotFoundException",
"(",
")"
] | Checks that a given path is valid. If it's not, raises NotFoundException | [
"Checks",
"that",
"a",
"given",
"path",
"is",
"valid",
".",
"If",
"it",
"s",
"not",
"raises",
"NotFoundException"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/provider.py#L41-L44 | train | 229,785 |
UCL-INGI/INGInious | inginious/frontend/pages/api/courses.py | APICourses.API_GET | def API_GET(self, courseid=None): # pylint: disable=arguments-differ
"""
List courses available to the connected client. Returns a dict in the form
::
{
"courseid1":
{
"name": "Name of the course", #the name of the course
"require_password": False, #indicates if this course requires a password or not
"is_registered": False, #indicates if the user is registered to this course or not
"tasks": #only appears if is_registered is True
{
"taskid1": "name of task1",
"taskid2": "name of task2"
#...
},
"grade": 0.0 #the current grade in the course. Only appears if is_registered is True
}
#...
}
If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found.
"""
output = []
if courseid is None:
courses = self.course_factory.get_all_courses()
else:
try:
courses = {courseid: self.course_factory.get_course(courseid)}
except:
raise APINotFound("Course not found")
username = self.user_manager.session_username()
user_info = self.database.users.find_one({"username": username})
for courseid, course in courses.items():
if self.user_manager.course_is_open_to_user(course, username, False) or course.is_registration_possible(user_info):
data = {
"id": courseid,
"name": course.get_name(self.user_manager.session_language()),
"require_password": course.is_password_needed_for_registration(),
"is_registered": self.user_manager.course_is_open_to_user(course, username, False)
}
if self.user_manager.course_is_open_to_user(course, username, False):
data["tasks"] = {taskid: task.get_name(self.user_manager.session_language()) for taskid, task in course.get_tasks().items()}
data["grade"] = self.user_manager.get_course_cache(username, course)["grade"]
output.append(data)
return 200, output | python | def API_GET(self, courseid=None): # pylint: disable=arguments-differ
"""
List courses available to the connected client. Returns a dict in the form
::
{
"courseid1":
{
"name": "Name of the course", #the name of the course
"require_password": False, #indicates if this course requires a password or not
"is_registered": False, #indicates if the user is registered to this course or not
"tasks": #only appears if is_registered is True
{
"taskid1": "name of task1",
"taskid2": "name of task2"
#...
},
"grade": 0.0 #the current grade in the course. Only appears if is_registered is True
}
#...
}
If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found.
"""
output = []
if courseid is None:
courses = self.course_factory.get_all_courses()
else:
try:
courses = {courseid: self.course_factory.get_course(courseid)}
except:
raise APINotFound("Course not found")
username = self.user_manager.session_username()
user_info = self.database.users.find_one({"username": username})
for courseid, course in courses.items():
if self.user_manager.course_is_open_to_user(course, username, False) or course.is_registration_possible(user_info):
data = {
"id": courseid,
"name": course.get_name(self.user_manager.session_language()),
"require_password": course.is_password_needed_for_registration(),
"is_registered": self.user_manager.course_is_open_to_user(course, username, False)
}
if self.user_manager.course_is_open_to_user(course, username, False):
data["tasks"] = {taskid: task.get_name(self.user_manager.session_language()) for taskid, task in course.get_tasks().items()}
data["grade"] = self.user_manager.get_course_cache(username, course)["grade"]
output.append(data)
return 200, output | [
"def",
"API_GET",
"(",
"self",
",",
"courseid",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"output",
"=",
"[",
"]",
"if",
"courseid",
"is",
"None",
":",
"courses",
"=",
"self",
".",
"course_factory",
".",
"get_all_courses",
"(",
")",
"else"... | List courses available to the connected client. Returns a dict in the form
::
{
"courseid1":
{
"name": "Name of the course", #the name of the course
"require_password": False, #indicates if this course requires a password or not
"is_registered": False, #indicates if the user is registered to this course or not
"tasks": #only appears if is_registered is True
{
"taskid1": "name of task1",
"taskid2": "name of task2"
#...
},
"grade": 0.0 #the current grade in the course. Only appears if is_registered is True
}
#...
}
If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found. | [
"List",
"courses",
"available",
"to",
"the",
"connected",
"client",
".",
"Returns",
"a",
"dict",
"in",
"the",
"form"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/courses.py#L16-L67 | train | 229,786 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | _api_convert_output | def _api_convert_output(return_value):
""" Convert the output to what the client asks """
content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json')
if "text/json" in content_type:
web.header('Content-Type', 'text/json; charset=utf-8')
return json.dumps(return_value)
if "text/html" in content_type:
web.header('Content-Type', 'text/html; charset=utf-8')
dump = yaml.dump(return_value)
return "<pre>" + web.websafe(dump) + "</pre>"
if "text/yaml" in content_type or \
"text/x-yaml" in content_type or \
"application/yaml" in content_type or \
"application/x-yaml" in content_type:
web.header('Content-Type', 'text/yaml; charset=utf-8')
dump = yaml.dump(return_value)
return dump
web.header('Content-Type', 'text/json; charset=utf-8')
return json.dumps(return_value) | python | def _api_convert_output(return_value):
""" Convert the output to what the client asks """
content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json')
if "text/json" in content_type:
web.header('Content-Type', 'text/json; charset=utf-8')
return json.dumps(return_value)
if "text/html" in content_type:
web.header('Content-Type', 'text/html; charset=utf-8')
dump = yaml.dump(return_value)
return "<pre>" + web.websafe(dump) + "</pre>"
if "text/yaml" in content_type or \
"text/x-yaml" in content_type or \
"application/yaml" in content_type or \
"application/x-yaml" in content_type:
web.header('Content-Type', 'text/yaml; charset=utf-8')
dump = yaml.dump(return_value)
return dump
web.header('Content-Type', 'text/json; charset=utf-8')
return json.dumps(return_value) | [
"def",
"_api_convert_output",
"(",
"return_value",
")",
":",
"content_type",
"=",
"web",
".",
"ctx",
".",
"environ",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"'text/json'",
")",
"if",
"\"text/json\"",
"in",
"content_type",
":",
"web",
".",
"header",
"(",
"'Co... | Convert the output to what the client asks | [
"Convert",
"the",
"output",
"to",
"what",
"the",
"client",
"asks"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L163-L182 | train | 229,787 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | APIPage._handle_api | def _handle_api(self, handler, handler_args, handler_kwargs):
""" Handle call to subclasses and convert the output to an appropriate value """
try:
status_code, return_value = handler(*handler_args, **handler_kwargs)
except APIError as error:
return error.send()
web.ctx.status = _convert_http_status(status_code)
return _api_convert_output(return_value) | python | def _handle_api(self, handler, handler_args, handler_kwargs):
""" Handle call to subclasses and convert the output to an appropriate value """
try:
status_code, return_value = handler(*handler_args, **handler_kwargs)
except APIError as error:
return error.send()
web.ctx.status = _convert_http_status(status_code)
return _api_convert_output(return_value) | [
"def",
"_handle_api",
"(",
"self",
",",
"handler",
",",
"handler_args",
",",
"handler_kwargs",
")",
":",
"try",
":",
"status_code",
",",
"return_value",
"=",
"handler",
"(",
"*",
"handler_args",
",",
"*",
"*",
"handler_kwargs",
")",
"except",
"APIError",
"as... | Handle call to subclasses and convert the output to an appropriate value | [
"Handle",
"call",
"to",
"subclasses",
"and",
"convert",
"the",
"output",
"to",
"an",
"appropriate",
"value"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L47-L55 | train | 229,788 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | APIPage._guess_available_methods | def _guess_available_methods(self):
""" Guess the method implemented by the subclass"""
available_methods = []
for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]:
self_method = getattr(type(self), "API_{}".format(m))
super_method = getattr(APIPage, "API_{}".format(m))
if self_method != super_method:
available_methods.append(m)
return available_methods | python | def _guess_available_methods(self):
""" Guess the method implemented by the subclass"""
available_methods = []
for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]:
self_method = getattr(type(self), "API_{}".format(m))
super_method = getattr(APIPage, "API_{}".format(m))
if self_method != super_method:
available_methods.append(m)
return available_methods | [
"def",
"_guess_available_methods",
"(",
"self",
")",
":",
"available_methods",
"=",
"[",
"]",
"for",
"m",
"in",
"[",
"\"GET\"",
",",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"DELETE\"",
",",
"\"PATCH\"",
",",
"\"HEAD\"",
",",
"\"OPTIONS\"",
"]",
":",
"self_method"... | Guess the method implemented by the subclass | [
"Guess",
"the",
"method",
"implemented",
"by",
"the",
"subclass"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L57-L65 | train | 229,789 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | APIAuthenticatedPage._verify_authentication | def _verify_authentication(self, handler, args, kwargs):
""" Verify that the user is authenticated """
if not self.user_manager.session_logged_in():
raise APIForbidden()
return handler(*args, **kwargs) | python | def _verify_authentication(self, handler, args, kwargs):
""" Verify that the user is authenticated """
if not self.user_manager.session_logged_in():
raise APIForbidden()
return handler(*args, **kwargs) | [
"def",
"_verify_authentication",
"(",
"self",
",",
"handler",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"user_manager",
".",
"session_logged_in",
"(",
")",
":",
"raise",
"APIForbidden",
"(",
")",
"return",
"handler",
"(",
"*",
"args",... | Verify that the user is authenticated | [
"Verify",
"that",
"the",
"user",
"is",
"authenticated"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L109-L113 | train | 229,790 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | APIError.send | def send(self):
""" Send the API Exception to the client """
web.ctx.status = _convert_http_status(self.status_code)
return _api_convert_output(self.return_value) | python | def send(self):
""" Send the API Exception to the client """
web.ctx.status = _convert_http_status(self.status_code)
return _api_convert_output(self.return_value) | [
"def",
"send",
"(",
"self",
")",
":",
"web",
".",
"ctx",
".",
"status",
"=",
"_convert_http_status",
"(",
"self",
".",
"status_code",
")",
"return",
"_api_convert_output",
"(",
"self",
".",
"return_value",
")"
] | Send the API Exception to the client | [
"Send",
"the",
"API",
"Exception",
"to",
"the",
"client"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L124-L127 | train | 229,791 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager._job_done_callback | def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True):
""" Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the
job """
submission = self.get_submission(submissionid, False)
submission = self.get_input_from_submission(submission)
data = {
"status": ("done" if result[0] == "success" or result[0] == "failed" else "error"),
# error only if error was made by INGInious
"result": result[0],
"grade": grade,
"text": result[1],
"tests": tests,
"problems": problems,
"archive": (self._gridfs.put(archive) if archive is not None else None),
"custom": custom,
"state": state,
"stdout": stdout,
"stderr": stderr
}
unset_obj = {
"jobid": "",
"ssh_host": "",
"ssh_port": "",
"ssh_password": ""
}
# Save submission to database
submission = self._database.submissions.find_one_and_update(
{"_id": submission["_id"]},
{"$set": data, "$unset": unset_obj},
return_document=ReturnDocument.AFTER
)
self._hook_manager.call_hook("submission_done", submission=submission, archive=archive, newsub=newsub)
for username in submission["username"]:
self._user_manager.update_user_stats(username, task, submission, result[0], grade, state, newsub)
if "outcome_service_url" in submission and "outcome_result_id" in submission and "outcome_consumer_key" in submission:
for username in submission["username"]:
self._lti_outcome_manager.add(username,
submission["courseid"],
submission["taskid"],
submission["outcome_consumer_key"],
submission["outcome_service_url"],
submission["outcome_result_id"]) | python | def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True):
""" Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the
job """
submission = self.get_submission(submissionid, False)
submission = self.get_input_from_submission(submission)
data = {
"status": ("done" if result[0] == "success" or result[0] == "failed" else "error"),
# error only if error was made by INGInious
"result": result[0],
"grade": grade,
"text": result[1],
"tests": tests,
"problems": problems,
"archive": (self._gridfs.put(archive) if archive is not None else None),
"custom": custom,
"state": state,
"stdout": stdout,
"stderr": stderr
}
unset_obj = {
"jobid": "",
"ssh_host": "",
"ssh_port": "",
"ssh_password": ""
}
# Save submission to database
submission = self._database.submissions.find_one_and_update(
{"_id": submission["_id"]},
{"$set": data, "$unset": unset_obj},
return_document=ReturnDocument.AFTER
)
self._hook_manager.call_hook("submission_done", submission=submission, archive=archive, newsub=newsub)
for username in submission["username"]:
self._user_manager.update_user_stats(username, task, submission, result[0], grade, state, newsub)
if "outcome_service_url" in submission and "outcome_result_id" in submission and "outcome_consumer_key" in submission:
for username in submission["username"]:
self._lti_outcome_manager.add(username,
submission["courseid"],
submission["taskid"],
submission["outcome_consumer_key"],
submission["outcome_service_url"],
submission["outcome_result_id"]) | [
"def",
"_job_done_callback",
"(",
"self",
",",
"submissionid",
",",
"task",
",",
"result",
",",
"grade",
",",
"problems",
",",
"tests",
",",
"custom",
",",
"state",
",",
"archive",
",",
"stdout",
",",
"stderr",
",",
"newsub",
"=",
"True",
")",
":",
"su... | Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the
job | [
"Callback",
"called",
"by",
"Client",
"when",
"a",
"job",
"is",
"done",
".",
"Updates",
"the",
"submission",
"in",
"the",
"database",
"with",
"the",
"data",
"returned",
"after",
"the",
"completion",
"of",
"the",
"job"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L46-L93 | train | 229,792 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager._before_submission_insertion | def _before_submission_insertion(self, task, inputdata, debug, obj):
"""
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the
database. Should be overridden in subclasses.
:param task: Task related to the submission
:param inputdata: input of the student
:param debug: True, False or "ssh". See add_job.
:param obj: the new document that will be inserted
"""
username = self._user_manager.session_username()
if task.is_group_task() and not self._user_manager.has_staff_rights_on_course(task.get_course(), username):
group = self._database.aggregations.find_one(
{"courseid": task.get_course_id(), "groups.students": username},
{"groups": {"$elemMatch": {"students": username}}})
obj.update({"username": group["groups"][0]["students"]})
else:
obj.update({"username": [username]})
lti_info = self._user_manager.session_lti_info()
if lti_info is not None and task.get_course().lti_send_back_grade():
outcome_service_url = lti_info["outcome_service_url"]
outcome_result_id = lti_info["outcome_result_id"]
outcome_consumer_key = lti_info["consumer_key"]
# safety check
if outcome_result_id is None or outcome_service_url is None:
self._logger.error("outcome_result_id or outcome_service_url is None, but grade needs to be sent back to TC! Ignoring.")
return
obj.update({"outcome_service_url": outcome_service_url,
"outcome_result_id": outcome_result_id,
"outcome_consumer_key": outcome_consumer_key}) | python | def _before_submission_insertion(self, task, inputdata, debug, obj):
"""
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the
database. Should be overridden in subclasses.
:param task: Task related to the submission
:param inputdata: input of the student
:param debug: True, False or "ssh". See add_job.
:param obj: the new document that will be inserted
"""
username = self._user_manager.session_username()
if task.is_group_task() and not self._user_manager.has_staff_rights_on_course(task.get_course(), username):
group = self._database.aggregations.find_one(
{"courseid": task.get_course_id(), "groups.students": username},
{"groups": {"$elemMatch": {"students": username}}})
obj.update({"username": group["groups"][0]["students"]})
else:
obj.update({"username": [username]})
lti_info = self._user_manager.session_lti_info()
if lti_info is not None and task.get_course().lti_send_back_grade():
outcome_service_url = lti_info["outcome_service_url"]
outcome_result_id = lti_info["outcome_result_id"]
outcome_consumer_key = lti_info["consumer_key"]
# safety check
if outcome_result_id is None or outcome_service_url is None:
self._logger.error("outcome_result_id or outcome_service_url is None, but grade needs to be sent back to TC! Ignoring.")
return
obj.update({"outcome_service_url": outcome_service_url,
"outcome_result_id": outcome_result_id,
"outcome_consumer_key": outcome_consumer_key}) | [
"def",
"_before_submission_insertion",
"(",
"self",
",",
"task",
",",
"inputdata",
",",
"debug",
",",
"obj",
")",
":",
"username",
"=",
"self",
".",
"_user_manager",
".",
"session_username",
"(",
")",
"if",
"task",
".",
"is_group_task",
"(",
")",
"and",
"n... | Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the
database. Should be overridden in subclasses.
:param task: Task related to the submission
:param inputdata: input of the student
:param debug: True, False or "ssh". See add_job.
:param obj: the new document that will be inserted | [
"Called",
"before",
"any",
"new",
"submission",
"is",
"inserted",
"into",
"the",
"database",
".",
"Allows",
"you",
"to",
"modify",
"obj",
"the",
"new",
"document",
"that",
"will",
"be",
"inserted",
"into",
"the",
"database",
".",
"Should",
"be",
"overridden"... | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L95-L129 | train | 229,793 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager.get_submission | def get_submission(self, submissionid, user_check=True):
""" Get a submission from the database """
sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)})
if user_check and not self.user_is_submission_owner(sub):
return None
return sub | python | def get_submission(self, submissionid, user_check=True):
""" Get a submission from the database """
sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)})
if user_check and not self.user_is_submission_owner(sub):
return None
return sub | [
"def",
"get_submission",
"(",
"self",
",",
"submissionid",
",",
"user_check",
"=",
"True",
")",
":",
"sub",
"=",
"self",
".",
"_database",
".",
"submissions",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"ObjectId",
"(",
"submissionid",
")",
"}",
")",
"if",
... | Get a submission from the database | [
"Get",
"a",
"submission",
"from",
"the",
"database"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L208-L213 | train | 229,794 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager._delete_exceeding_submissions | def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1):
""" Deletes exceeding submissions from the database, to keep the database relatively small """
if max_submissions_bound <= 0:
max_submissions = task.get_stored_submissions()
elif task.get_stored_submissions() <= 0:
max_submissions = max_submissions_bound
else:
max_submissions = min(max_submissions_bound, task.get_stored_submissions())
if max_submissions <= 0:
return []
tasks = list(self._database.submissions.find(
{"username": username, "courseid": task.get_course_id(), "taskid": task.get_id()},
projection=["_id", "status", "result", "grade", "submitted_on"],
sort=[('submitted_on', pymongo.ASCENDING)]))
# List the entries to keep
to_keep = set([])
if task.get_evaluate() == 'best':
# Find the best "status"="done" and "result"="success"
idx_best = -1
for idx, val in enumerate(tasks):
if val["status"] == "done":
if idx_best == -1 or tasks[idx_best]["grade"] < val["grade"]:
idx_best = idx
# Always keep the best submission
if idx_best != -1:
to_keep.add(tasks[idx_best]["_id"])
elif task.get_evaluate() == 'student':
user_task = self._database.user_tasks.find_one({
"courseid": task.get_course_id(),
"taskid": task.get_id(),
"username": username
})
submissionid = user_task.get('submissionid', None)
if submissionid:
to_keep.add(submissionid)
# Always keep running submissions
for val in tasks:
if val["status"] == "waiting":
to_keep.add(val["_id"])
while len(to_keep) < max_submissions and len(tasks) > 0:
to_keep.add(tasks.pop()["_id"])
to_delete = {val["_id"] for val in tasks}.difference(to_keep)
self._database.submissions.delete_many({"_id": {"$in": list(to_delete)}})
return list(map(str, to_delete)) | python | def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1):
""" Deletes exceeding submissions from the database, to keep the database relatively small """
if max_submissions_bound <= 0:
max_submissions = task.get_stored_submissions()
elif task.get_stored_submissions() <= 0:
max_submissions = max_submissions_bound
else:
max_submissions = min(max_submissions_bound, task.get_stored_submissions())
if max_submissions <= 0:
return []
tasks = list(self._database.submissions.find(
{"username": username, "courseid": task.get_course_id(), "taskid": task.get_id()},
projection=["_id", "status", "result", "grade", "submitted_on"],
sort=[('submitted_on', pymongo.ASCENDING)]))
# List the entries to keep
to_keep = set([])
if task.get_evaluate() == 'best':
# Find the best "status"="done" and "result"="success"
idx_best = -1
for idx, val in enumerate(tasks):
if val["status"] == "done":
if idx_best == -1 or tasks[idx_best]["grade"] < val["grade"]:
idx_best = idx
# Always keep the best submission
if idx_best != -1:
to_keep.add(tasks[idx_best]["_id"])
elif task.get_evaluate() == 'student':
user_task = self._database.user_tasks.find_one({
"courseid": task.get_course_id(),
"taskid": task.get_id(),
"username": username
})
submissionid = user_task.get('submissionid', None)
if submissionid:
to_keep.add(submissionid)
# Always keep running submissions
for val in tasks:
if val["status"] == "waiting":
to_keep.add(val["_id"])
while len(to_keep) < max_submissions and len(tasks) > 0:
to_keep.add(tasks.pop()["_id"])
to_delete = {val["_id"] for val in tasks}.difference(to_keep)
self._database.submissions.delete_many({"_id": {"$in": list(to_delete)}})
return list(map(str, to_delete)) | [
"def",
"_delete_exceeding_submissions",
"(",
"self",
",",
"username",
",",
"task",
",",
"max_submissions_bound",
"=",
"-",
"1",
")",
":",
"if",
"max_submissions_bound",
"<=",
"0",
":",
"max_submissions",
"=",
"task",
".",
"get_stored_submissions",
"(",
")",
"eli... | Deletes exceeding submissions from the database, to keep the database relatively small | [
"Deletes",
"exceeding",
"submissions",
"from",
"the",
"database",
"to",
"keep",
"the",
"database",
"relatively",
"small"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L284-L337 | train | 229,795 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager.is_done | def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissionid_or_submission
else:
submission = self.get_submission(submissionid_or_submission, False)
if user_check and not self.user_is_submission_owner(submission):
return None
return submission["status"] == "done" or submission["status"] == "error" | python | def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissionid_or_submission
else:
submission = self.get_submission(submissionid_or_submission, False)
if user_check and not self.user_is_submission_owner(submission):
return None
return submission["status"] == "done" or submission["status"] == "error" | [
"def",
"is_done",
"(",
"self",
",",
"submissionid_or_submission",
",",
"user_check",
"=",
"True",
")",
":",
"# TODO: not a very nice way to avoid too many database call. Should be refactored.",
"if",
"isinstance",
"(",
"submissionid_or_submission",
",",
"dict",
")",
":",
"s... | Tells if a submission is done and its result is available | [
"Tells",
"if",
"a",
"submission",
"is",
"done",
"and",
"its",
"result",
"is",
"available"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L379-L388 | train | 229,796 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager.user_is_submission_owner | def user_is_submission_owner(self, submission):
""" Returns true if the current user is the owner of this jobid, false else """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to verify if he owns a jobid")
return self._user_manager.session_username() in submission["username"] | python | def user_is_submission_owner(self, submission):
""" Returns true if the current user is the owner of this jobid, false else """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to verify if he owns a jobid")
return self._user_manager.session_username() in submission["username"] | [
"def",
"user_is_submission_owner",
"(",
"self",
",",
"submission",
")",
":",
"if",
"not",
"self",
".",
"_user_manager",
".",
"session_logged_in",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"A user must be logged in to verify if he owns a jobid\"",
")",
"return",
"sel... | Returns true if the current user is the owner of this jobid, false else | [
"Returns",
"true",
"if",
"the",
"current",
"user",
"is",
"the",
"owner",
"of",
"this",
"jobid",
"false",
"else"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L404-L409 | train | 229,797 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager.get_user_submissions | def get_user_submissions(self, task):
""" Get all the user's submissions for a given task """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to get his submissions")
cursor = self._database.submissions.find({"username": self._user_manager.session_username(),
"taskid": task.get_id(), "courseid": task.get_course_id()})
cursor.sort([("submitted_on", -1)])
return list(cursor) | python | def get_user_submissions(self, task):
""" Get all the user's submissions for a given task """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to get his submissions")
cursor = self._database.submissions.find({"username": self._user_manager.session_username(),
"taskid": task.get_id(), "courseid": task.get_course_id()})
cursor.sort([("submitted_on", -1)])
return list(cursor) | [
"def",
"get_user_submissions",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"_user_manager",
".",
"session_logged_in",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"A user must be logged in to get his submissions\"",
")",
"cursor",
"=",
"self",
"."... | Get all the user's submissions for a given task | [
"Get",
"all",
"the",
"user",
"s",
"submissions",
"for",
"a",
"given",
"task"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L411-L419 | train | 229,798 |
UCL-INGI/INGInious | inginious/frontend/submission_manager.py | WebAppSubmissionManager.get_user_last_submissions | def get_user_last_submissions(self, limit=5, request=None):
""" Get last submissions of a user """
if request is None:
request = {}
request.update({"username": self._user_manager.session_username()})
# Before, submissions were first sorted by submission date, then grouped
# and then resorted by submission date before limiting. Actually, grouping
# and pushing, keeping the max date, followed by result filtering is much more
# efficient
data = self._database.submissions.aggregate([
{"$match": request},
{"$group": {"_id": {"courseid": "$courseid", "taskid": "$taskid"},
"submitted_on": {"$max": "$submitted_on"},
"submissions": {"$push": {
"_id": "$_id",
"result": "$result",
"status" : "$status",
"courseid": "$courseid",
"taskid": "$taskid",
"submitted_on": "$submitted_on"
}},
}},
{"$project": {
"submitted_on": 1,
"submissions": {
# This could be replaced by $filter if mongo v3.2 is set as dependency
"$setDifference": [
{"$map": {
"input": "$submissions",
"as": "submission",
"in": {
"$cond": [{"$eq": ["$submitted_on", "$$submission.submitted_on"]}, "$$submission", False]
}
}},
[False]
]
}
}},
{"$sort": {"submitted_on": pymongo.DESCENDING}},
{"$limit": limit}
])
return [item["submissions"][0] for item in data] | python | def get_user_last_submissions(self, limit=5, request=None):
""" Get last submissions of a user """
if request is None:
request = {}
request.update({"username": self._user_manager.session_username()})
# Before, submissions were first sorted by submission date, then grouped
# and then resorted by submission date before limiting. Actually, grouping
# and pushing, keeping the max date, followed by result filtering is much more
# efficient
data = self._database.submissions.aggregate([
{"$match": request},
{"$group": {"_id": {"courseid": "$courseid", "taskid": "$taskid"},
"submitted_on": {"$max": "$submitted_on"},
"submissions": {"$push": {
"_id": "$_id",
"result": "$result",
"status" : "$status",
"courseid": "$courseid",
"taskid": "$taskid",
"submitted_on": "$submitted_on"
}},
}},
{"$project": {
"submitted_on": 1,
"submissions": {
# This could be replaced by $filter if mongo v3.2 is set as dependency
"$setDifference": [
{"$map": {
"input": "$submissions",
"as": "submission",
"in": {
"$cond": [{"$eq": ["$submitted_on", "$$submission.submitted_on"]}, "$$submission", False]
}
}},
[False]
]
}
}},
{"$sort": {"submitted_on": pymongo.DESCENDING}},
{"$limit": limit}
])
return [item["submissions"][0] for item in data] | [
"def",
"get_user_last_submissions",
"(",
"self",
",",
"limit",
"=",
"5",
",",
"request",
"=",
"None",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"{",
"}",
"request",
".",
"update",
"(",
"{",
"\"username\"",
":",
"self",
".",
"_user_m... | Get last submissions of a user | [
"Get",
"last",
"submissions",
"of",
"a",
"user"
] | cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L421-L465 | train | 229,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.