partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
QasmSimulatorPy._add_qasm_reset
|
Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _add_qasm_reset(self, qubit):
"""Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / np.sqrt(probability), 0], [0, 0]]
self._add_unitary_single(update, qubit)
else:
update = [[0, 1 / np.sqrt(probability)], [0, 0]]
self._add_unitary_single(update, qubit)
|
def _add_qasm_reset(self, qubit):
"""Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / np.sqrt(probability), 0], [0, 0]]
self._add_unitary_single(update, qubit)
else:
update = [[0, 1 / np.sqrt(probability)], [0, 0]]
self._add_unitary_single(update, qubit)
|
[
"Apply",
"a",
"reset",
"instruction",
"to",
"a",
"qubit",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L251-L269
|
[
"def",
"_add_qasm_reset",
"(",
"self",
",",
"qubit",
")",
":",
"# get measure outcome",
"outcome",
",",
"probability",
"=",
"self",
".",
"_get_measure_outcome",
"(",
"qubit",
")",
"# update quantum state",
"if",
"outcome",
"==",
"'0'",
":",
"update",
"=",
"[",
"[",
"1",
"/",
"np",
".",
"sqrt",
"(",
"probability",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
"]",
"self",
".",
"_add_unitary_single",
"(",
"update",
",",
"qubit",
")",
"else",
":",
"update",
"=",
"[",
"[",
"0",
",",
"1",
"/",
"np",
".",
"sqrt",
"(",
"probability",
")",
"]",
",",
"[",
"0",
",",
"0",
"]",
"]",
"self",
".",
"_add_unitary_single",
"(",
"update",
",",
"qubit",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._validate_initial_statevector
|
Validate an initial statevector
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _validate_initial_statevector(self):
"""Validate an initial statevector"""
# If initial statevector isn't set we don't need to validate
if self._initial_statevector is None:
return
# Check statevector is correct length for number of qubits
length = len(self._initial_statevector)
required_dim = 2 ** self._number_of_qubits
if length != required_dim:
raise BasicAerError('initial statevector is incorrect length: ' +
'{} != {}'.format(length, required_dim))
|
def _validate_initial_statevector(self):
"""Validate an initial statevector"""
# If initial statevector isn't set we don't need to validate
if self._initial_statevector is None:
return
# Check statevector is correct length for number of qubits
length = len(self._initial_statevector)
required_dim = 2 ** self._number_of_qubits
if length != required_dim:
raise BasicAerError('initial statevector is incorrect length: ' +
'{} != {}'.format(length, required_dim))
|
[
"Validate",
"an",
"initial",
"statevector"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L271-L281
|
[
"def",
"_validate_initial_statevector",
"(",
"self",
")",
":",
"# If initial statevector isn't set we don't need to validate",
"if",
"self",
".",
"_initial_statevector",
"is",
"None",
":",
"return",
"# Check statevector is correct length for number of qubits",
"length",
"=",
"len",
"(",
"self",
".",
"_initial_statevector",
")",
"required_dim",
"=",
"2",
"**",
"self",
".",
"_number_of_qubits",
"if",
"length",
"!=",
"required_dim",
":",
"raise",
"BasicAerError",
"(",
"'initial statevector is incorrect length: '",
"+",
"'{} != {}'",
".",
"format",
"(",
"length",
",",
"required_dim",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._set_options
|
Set the backend options for all experiments in a qobj
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_statevector' in backend_options:
self._initial_statevector = np.array(backend_options['initial_statevector'],
dtype=complex)
elif hasattr(qobj_config, 'initial_statevector'):
self._initial_statevector = np.array(qobj_config.initial_statevector,
dtype=complex)
if self._initial_statevector is not None:
# Check the initial statevector is normalized
norm = np.linalg.norm(self._initial_statevector)
if round(norm, 12) != 1:
raise BasicAerError('initial statevector is not normalized: ' +
'norm {} != 1'.format(norm))
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
|
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_statevector' in backend_options:
self._initial_statevector = np.array(backend_options['initial_statevector'],
dtype=complex)
elif hasattr(qobj_config, 'initial_statevector'):
self._initial_statevector = np.array(qobj_config.initial_statevector,
dtype=complex)
if self._initial_statevector is not None:
# Check the initial statevector is normalized
norm = np.linalg.norm(self._initial_statevector)
if round(norm, 12) != 1:
raise BasicAerError('initial statevector is not normalized: ' +
'norm {} != 1'.format(norm))
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
|
[
"Set",
"the",
"backend",
"options",
"for",
"all",
"experiments",
"in",
"a",
"qobj"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L283-L310
|
[
"def",
"_set_options",
"(",
"self",
",",
"qobj_config",
"=",
"None",
",",
"backend_options",
"=",
"None",
")",
":",
"# Reset default options",
"self",
".",
"_initial_statevector",
"=",
"self",
".",
"DEFAULT_OPTIONS",
"[",
"\"initial_statevector\"",
"]",
"self",
".",
"_chop_threshold",
"=",
"self",
".",
"DEFAULT_OPTIONS",
"[",
"\"chop_threshold\"",
"]",
"if",
"backend_options",
"is",
"None",
":",
"backend_options",
"=",
"{",
"}",
"# Check for custom initial statevector in backend_options first,",
"# then config second",
"if",
"'initial_statevector'",
"in",
"backend_options",
":",
"self",
".",
"_initial_statevector",
"=",
"np",
".",
"array",
"(",
"backend_options",
"[",
"'initial_statevector'",
"]",
",",
"dtype",
"=",
"complex",
")",
"elif",
"hasattr",
"(",
"qobj_config",
",",
"'initial_statevector'",
")",
":",
"self",
".",
"_initial_statevector",
"=",
"np",
".",
"array",
"(",
"qobj_config",
".",
"initial_statevector",
",",
"dtype",
"=",
"complex",
")",
"if",
"self",
".",
"_initial_statevector",
"is",
"not",
"None",
":",
"# Check the initial statevector is normalized",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"_initial_statevector",
")",
"if",
"round",
"(",
"norm",
",",
"12",
")",
"!=",
"1",
":",
"raise",
"BasicAerError",
"(",
"'initial statevector is not normalized: '",
"+",
"'norm {} != 1'",
".",
"format",
"(",
"norm",
")",
")",
"# Check for custom chop threshold",
"# Replace with custom options",
"if",
"'chop_threshold'",
"in",
"backend_options",
":",
"self",
".",
"_chop_threshold",
"=",
"backend_options",
"[",
"'chop_threshold'",
"]",
"elif",
"hasattr",
"(",
"qobj_config",
",",
"'chop_threshold'",
")",
":",
"self",
".",
"_chop_threshold",
"=",
"qobj_config",
".",
"chop_threshold"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._initialize_statevector
|
Set the initial statevector for simulation
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _initialize_statevector(self):
"""Set the initial statevector for simulation"""
if self._initial_statevector is None:
# Set to default state of all qubits in |0>
self._statevector = np.zeros(2 ** self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
else:
self._statevector = self._initial_statevector.copy()
# Reshape to rank-N tensor
self._statevector = np.reshape(self._statevector,
self._number_of_qubits * [2])
|
def _initialize_statevector(self):
"""Set the initial statevector for simulation"""
if self._initial_statevector is None:
# Set to default state of all qubits in |0>
self._statevector = np.zeros(2 ** self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
else:
self._statevector = self._initial_statevector.copy()
# Reshape to rank-N tensor
self._statevector = np.reshape(self._statevector,
self._number_of_qubits * [2])
|
[
"Set",
"the",
"initial",
"statevector",
"for",
"simulation"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L312-L323
|
[
"def",
"_initialize_statevector",
"(",
"self",
")",
":",
"if",
"self",
".",
"_initial_statevector",
"is",
"None",
":",
"# Set to default state of all qubits in |0>",
"self",
".",
"_statevector",
"=",
"np",
".",
"zeros",
"(",
"2",
"**",
"self",
".",
"_number_of_qubits",
",",
"dtype",
"=",
"complex",
")",
"self",
".",
"_statevector",
"[",
"0",
"]",
"=",
"1",
"else",
":",
"self",
".",
"_statevector",
"=",
"self",
".",
"_initial_statevector",
".",
"copy",
"(",
")",
"# Reshape to rank-N tensor",
"self",
".",
"_statevector",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_statevector",
",",
"self",
".",
"_number_of_qubits",
"*",
"[",
"2",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._get_statevector
|
Return the current statevector in JSON Result spec format
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._chop_threshold] = 0.0
return vec
|
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._chop_threshold] = 0.0
return vec
|
[
"Return",
"the",
"current",
"statevector",
"in",
"JSON",
"Result",
"spec",
"format"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L325-L332
|
[
"def",
"_get_statevector",
"(",
"self",
")",
":",
"vec",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_statevector",
",",
"2",
"**",
"self",
".",
"_number_of_qubits",
")",
"# Expand complex numbers",
"vec",
"=",
"np",
".",
"stack",
"(",
"[",
"vec",
".",
"real",
",",
"vec",
".",
"imag",
"]",
",",
"axis",
"=",
"1",
")",
"# Truncate small values",
"vec",
"[",
"abs",
"(",
"vec",
")",
"<",
"self",
".",
"_chop_threshold",
"]",
"=",
"0.0",
"return",
"vec"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._validate_measure_sampling
|
Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
"""
# If shots=1 we should disable measure sampling.
# This is also required for statevector simulator to return the
# correct final statevector without silently dropping final measurements.
if self._shots <= 1:
self._sample_measure = False
return
# Check for config flag
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
# If flag isn't found do a simple test to see if a circuit contains
# no reset instructions, and no gates instructions after
# the first measure.
else:
measure_flag = False
for instruction in experiment.instructions:
# If circuit contains reset operations we cannot sample
if instruction.name == "reset":
self._sample_measure = False
return
# If circuit contains a measure option then we can
# sample only if all following operations are measures
if measure_flag:
# If we find a non-measure instruction
# we cannot do measure sampling
if instruction.name not in ["measure", "barrier", "id", "u0"]:
self._sample_measure = False
return
elif instruction.name == "measure":
measure_flag = True
# If we made it to the end of the circuit without returning
# measure sampling is allowed
self._sample_measure = True
|
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
"""
# If shots=1 we should disable measure sampling.
# This is also required for statevector simulator to return the
# correct final statevector without silently dropping final measurements.
if self._shots <= 1:
self._sample_measure = False
return
# Check for config flag
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
# If flag isn't found do a simple test to see if a circuit contains
# no reset instructions, and no gates instructions after
# the first measure.
else:
measure_flag = False
for instruction in experiment.instructions:
# If circuit contains reset operations we cannot sample
if instruction.name == "reset":
self._sample_measure = False
return
# If circuit contains a measure option then we can
# sample only if all following operations are measures
if measure_flag:
# If we find a non-measure instruction
# we cannot do measure sampling
if instruction.name not in ["measure", "barrier", "id", "u0"]:
self._sample_measure = False
return
elif instruction.name == "measure":
measure_flag = True
# If we made it to the end of the circuit without returning
# measure sampling is allowed
self._sample_measure = True
|
[
"Determine",
"if",
"measure",
"sampling",
"is",
"allowed",
"for",
"an",
"experiment"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L334-L372
|
[
"def",
"_validate_measure_sampling",
"(",
"self",
",",
"experiment",
")",
":",
"# If shots=1 we should disable measure sampling.",
"# This is also required for statevector simulator to return the",
"# correct final statevector without silently dropping final measurements.",
"if",
"self",
".",
"_shots",
"<=",
"1",
":",
"self",
".",
"_sample_measure",
"=",
"False",
"return",
"# Check for config flag",
"if",
"hasattr",
"(",
"experiment",
".",
"config",
",",
"'allows_measure_sampling'",
")",
":",
"self",
".",
"_sample_measure",
"=",
"experiment",
".",
"config",
".",
"allows_measure_sampling",
"# If flag isn't found do a simple test to see if a circuit contains",
"# no reset instructions, and no gates instructions after",
"# the first measure.",
"else",
":",
"measure_flag",
"=",
"False",
"for",
"instruction",
"in",
"experiment",
".",
"instructions",
":",
"# If circuit contains reset operations we cannot sample",
"if",
"instruction",
".",
"name",
"==",
"\"reset\"",
":",
"self",
".",
"_sample_measure",
"=",
"False",
"return",
"# If circuit contains a measure option then we can",
"# sample only if all following operations are measures",
"if",
"measure_flag",
":",
"# If we find a non-measure instruction",
"# we cannot do measure sampling",
"if",
"instruction",
".",
"name",
"not",
"in",
"[",
"\"measure\"",
",",
"\"barrier\"",
",",
"\"id\"",
",",
"\"u0\"",
"]",
":",
"self",
".",
"_sample_measure",
"=",
"False",
"return",
"elif",
"instruction",
".",
"name",
"==",
"\"measure\"",
":",
"measure_flag",
"=",
"True",
"# If we made it to the end of the circuit without returning",
"# measure sampling is allowed",
"self",
".",
"_sample_measure",
"=",
"True"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy.run
|
Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
BasicAerJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the qobj.
Example::
backend_options = {
"initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
}
|
qiskit/providers/basicaer/qasm_simulator.py
|
def run(self, qobj, backend_options=None):
"""Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
BasicAerJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the qobj.
Example::
backend_options = {
"initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
}
"""
self._set_options(qobj_config=qobj.config,
backend_options=backend_options)
job_id = str(uuid.uuid4())
job = BasicAerJob(self, job_id, self._run_job, qobj)
job.submit()
return job
|
def run(self, qobj, backend_options=None):
"""Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
BasicAerJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the qobj.
Example::
backend_options = {
"initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
}
"""
self._set_options(qobj_config=qobj.config,
backend_options=backend_options)
job_id = str(uuid.uuid4())
job = BasicAerJob(self, job_id, self._run_job, qobj)
job.submit()
return job
|
[
"Run",
"qobj",
"asynchronously",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L374-L404
|
[
"def",
"run",
"(",
"self",
",",
"qobj",
",",
"backend_options",
"=",
"None",
")",
":",
"self",
".",
"_set_options",
"(",
"qobj_config",
"=",
"qobj",
".",
"config",
",",
"backend_options",
"=",
"backend_options",
")",
"job_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"job",
"=",
"BasicAerJob",
"(",
"self",
",",
"job_id",
",",
"self",
".",
"_run_job",
",",
"qobj",
")",
"job",
".",
"submit",
"(",
")",
"return",
"job"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._run_job
|
Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _run_job(self, job_id, qobj):
"""Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._memory = getattr(qobj.config, 'memory', False)
self._qobj_config = qobj.config
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
|
def _run_job(self, job_id, qobj):
"""Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._memory = getattr(qobj.config, 'memory', False)
self._qobj_config = qobj.config
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
|
[
"Run",
"experiments",
"in",
"qobj"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L406-L435
|
[
"def",
"_run_job",
"(",
"self",
",",
"job_id",
",",
"qobj",
")",
":",
"self",
".",
"_validate",
"(",
"qobj",
")",
"result_list",
"=",
"[",
"]",
"self",
".",
"_shots",
"=",
"qobj",
".",
"config",
".",
"shots",
"self",
".",
"_memory",
"=",
"getattr",
"(",
"qobj",
".",
"config",
",",
"'memory'",
",",
"False",
")",
"self",
".",
"_qobj_config",
"=",
"qobj",
".",
"config",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"experiment",
"in",
"qobj",
".",
"experiments",
":",
"result_list",
".",
"append",
"(",
"self",
".",
"run_experiment",
"(",
"experiment",
")",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"{",
"'backend_name'",
":",
"self",
".",
"name",
"(",
")",
",",
"'backend_version'",
":",
"self",
".",
"_configuration",
".",
"backend_version",
",",
"'qobj_id'",
":",
"qobj",
".",
"qobj_id",
",",
"'job_id'",
":",
"job_id",
",",
"'results'",
":",
"result_list",
",",
"'status'",
":",
"'COMPLETED'",
",",
"'success'",
":",
"True",
",",
"'time_taken'",
":",
"(",
"end",
"-",
"start",
")",
",",
"'header'",
":",
"qobj",
".",
"header",
".",
"as_dict",
"(",
")",
"}",
"return",
"Result",
".",
"from_dict",
"(",
"result",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy.run_experiment
|
Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"counts": {'0x9: 5, ...},
"memory": ['0x9', '0xF', '0x1D', ..., '0x9']
},
"status": status string for the simulation
"success": boolean
"time_taken": simulation time of this single experiment
}
Raises:
BasicAerError: if an error occurred.
|
qiskit/providers/basicaer/qasm_simulator.py
|
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"counts": {'0x9: 5, ...},
"memory": ['0x9', '0xF', '0x1D', ..., '0x9']
},
"status": status string for the simulation
"success": boolean
"time_taken": simulation time of this single experiment
}
Raises:
BasicAerError: if an error occurred.
"""
start = time.time()
self._number_of_qubits = experiment.config.n_qubits
self._number_of_cmembits = experiment.config.memory_slots
self._statevector = 0
self._classical_memory = 0
self._classical_register = 0
self._sample_measure = False
# Validate the dimension of initial statevector if set
self._validate_initial_statevector()
# Get the seed looking in circuit, qobj, and then random.
if hasattr(experiment.config, 'seed'):
seed = experiment.config.seed
elif hasattr(self._qobj_config, 'seed'):
seed = self._qobj_config.seed
else:
# For compatibility on Windows force dyte to be int32
# and set the maximum value to be (2 ** 31) - 1
seed = np.random.randint(2147483647, dtype='int32')
self._local_random.seed(seed=seed)
# Check if measure sampling is supported for current circuit
self._validate_measure_sampling(experiment)
# List of final counts for all shots
memory = []
# Check if we can sample measurements, if so we only perform 1 shot
# and sample all outcomes from the final state vector
if self._sample_measure:
shots = 1
# Store (qubit, cmembit) pairs for all measure ops in circuit to
# be sampled
measure_sample_ops = []
else:
shots = self._shots
for _ in range(shots):
self._initialize_statevector()
# Initialize classical memory to all 0
self._classical_memory = 0
self._classical_register = 0
for operation in experiment.instructions:
conditional = getattr(operation, 'conditional', None)
if isinstance(conditional, int):
conditional_bit_set = (self._classical_register >> conditional) & 1
if not conditional_bit_set:
continue
elif conditional is not None:
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_memory & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cmembit = operation.memory[0]
cregbit = operation.register[0] if hasattr(operation, 'register') else None
if self._sample_measure:
# If sampling measurements record the qubit and cmembit
# for this measurement for later sampling
measure_sample_ops.append((qubit, cmembit))
else:
# If not sampling perform measurement as normal
self._add_qasm_measure(qubit, cmembit, cregbit)
elif operation.name == 'bfunc':
mask = int(operation.mask, 16)
relation = operation.relation
val = int(operation.val, 16)
cregbit = operation.register
cmembit = operation.memory if hasattr(operation, 'memory') else None
compared = (self._classical_register & mask) - val
if relation == '==':
outcome = (compared == 0)
elif relation == '!=':
outcome = (compared != 0)
elif relation == '<':
outcome = (compared < 0)
elif relation == '<=':
outcome = (compared <= 0)
elif relation == '>':
outcome = (compared > 0)
elif relation == '>=':
outcome = (compared >= 0)
else:
raise BasicAerError('Invalid boolean function relation.')
# Store outcome in register and optionally memory slot
regbit = 1 << cregbit
self._classical_register = \
(self._classical_register & (~regbit)) | (int(outcome) << cregbit)
if cmembit is not None:
membit = 1 << cmembit
self._classical_memory = \
(self._classical_memory & (~membit)) | (int(outcome) << cmembit)
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise BasicAerError(err_msg.format(backend, operation.name))
# Add final creg data to memory list
if self._number_of_cmembits > 0:
if self._sample_measure:
# If sampling we generate all shot samples from the final statevector
memory = self._add_sample_measure(measure_sample_ops, self._shots)
else:
# Turn classical_memory (int) into bit string and pad zero for unused cmembits
outcome = bin(self._classical_memory)[2:]
memory.append(hex(int(outcome, 2)))
# Add data
data = {'counts': dict(Counter(memory))}
# Optionally add memory list
if self._memory:
data['memory'] = memory
# Optionally add final statevector
if self.SHOW_FINAL_STATE:
data['statevector'] = self._get_statevector()
# Remove empty counts and memory for statevector simulator
if not data['counts']:
data.pop('counts')
if 'memory' in data and not data['memory']:
data.pop('memory')
end = time.time()
return {'name': experiment.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
|
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"counts": {'0x9: 5, ...},
"memory": ['0x9', '0xF', '0x1D', ..., '0x9']
},
"status": status string for the simulation
"success": boolean
"time_taken": simulation time of this single experiment
}
Raises:
BasicAerError: if an error occurred.
"""
start = time.time()
self._number_of_qubits = experiment.config.n_qubits
self._number_of_cmembits = experiment.config.memory_slots
self._statevector = 0
self._classical_memory = 0
self._classical_register = 0
self._sample_measure = False
# Validate the dimension of initial statevector if set
self._validate_initial_statevector()
# Get the seed looking in circuit, qobj, and then random.
if hasattr(experiment.config, 'seed'):
seed = experiment.config.seed
elif hasattr(self._qobj_config, 'seed'):
seed = self._qobj_config.seed
else:
# For compatibility on Windows force dyte to be int32
# and set the maximum value to be (2 ** 31) - 1
seed = np.random.randint(2147483647, dtype='int32')
self._local_random.seed(seed=seed)
# Check if measure sampling is supported for current circuit
self._validate_measure_sampling(experiment)
# List of final counts for all shots
memory = []
# Check if we can sample measurements, if so we only perform 1 shot
# and sample all outcomes from the final state vector
if self._sample_measure:
shots = 1
# Store (qubit, cmembit) pairs for all measure ops in circuit to
# be sampled
measure_sample_ops = []
else:
shots = self._shots
for _ in range(shots):
self._initialize_statevector()
# Initialize classical memory to all 0
self._classical_memory = 0
self._classical_register = 0
for operation in experiment.instructions:
conditional = getattr(operation, 'conditional', None)
if isinstance(conditional, int):
conditional_bit_set = (self._classical_register >> conditional) & 1
if not conditional_bit_set:
continue
elif conditional is not None:
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_memory & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cmembit = operation.memory[0]
cregbit = operation.register[0] if hasattr(operation, 'register') else None
if self._sample_measure:
# If sampling measurements record the qubit and cmembit
# for this measurement for later sampling
measure_sample_ops.append((qubit, cmembit))
else:
# If not sampling perform measurement as normal
self._add_qasm_measure(qubit, cmembit, cregbit)
elif operation.name == 'bfunc':
mask = int(operation.mask, 16)
relation = operation.relation
val = int(operation.val, 16)
cregbit = operation.register
cmembit = operation.memory if hasattr(operation, 'memory') else None
compared = (self._classical_register & mask) - val
if relation == '==':
outcome = (compared == 0)
elif relation == '!=':
outcome = (compared != 0)
elif relation == '<':
outcome = (compared < 0)
elif relation == '<=':
outcome = (compared <= 0)
elif relation == '>':
outcome = (compared > 0)
elif relation == '>=':
outcome = (compared >= 0)
else:
raise BasicAerError('Invalid boolean function relation.')
# Store outcome in register and optionally memory slot
regbit = 1 << cregbit
self._classical_register = \
(self._classical_register & (~regbit)) | (int(outcome) << cregbit)
if cmembit is not None:
membit = 1 << cmembit
self._classical_memory = \
(self._classical_memory & (~membit)) | (int(outcome) << cmembit)
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise BasicAerError(err_msg.format(backend, operation.name))
# Add final creg data to memory list
if self._number_of_cmembits > 0:
if self._sample_measure:
# If sampling we generate all shot samples from the final statevector
memory = self._add_sample_measure(measure_sample_ops, self._shots)
else:
# Turn classical_memory (int) into bit string and pad zero for unused cmembits
outcome = bin(self._classical_memory)[2:]
memory.append(hex(int(outcome, 2)))
# Add data
data = {'counts': dict(Counter(memory))}
# Optionally add memory list
if self._memory:
data['memory'] = memory
# Optionally add final statevector
if self.SHOW_FINAL_STATE:
data['statevector'] = self._get_statevector()
# Remove empty counts and memory for statevector simulator
if not data['counts']:
data.pop('counts')
if 'memory' in data and not data['memory']:
data.pop('memory')
end = time.time()
return {'name': experiment.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
|
[
"Run",
"an",
"experiment",
"(",
"circuit",
")",
"and",
"return",
"a",
"single",
"experiment",
"result",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L437-L620
|
[
"def",
"run_experiment",
"(",
"self",
",",
"experiment",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_number_of_qubits",
"=",
"experiment",
".",
"config",
".",
"n_qubits",
"self",
".",
"_number_of_cmembits",
"=",
"experiment",
".",
"config",
".",
"memory_slots",
"self",
".",
"_statevector",
"=",
"0",
"self",
".",
"_classical_memory",
"=",
"0",
"self",
".",
"_classical_register",
"=",
"0",
"self",
".",
"_sample_measure",
"=",
"False",
"# Validate the dimension of initial statevector if set",
"self",
".",
"_validate_initial_statevector",
"(",
")",
"# Get the seed looking in circuit, qobj, and then random.",
"if",
"hasattr",
"(",
"experiment",
".",
"config",
",",
"'seed'",
")",
":",
"seed",
"=",
"experiment",
".",
"config",
".",
"seed",
"elif",
"hasattr",
"(",
"self",
".",
"_qobj_config",
",",
"'seed'",
")",
":",
"seed",
"=",
"self",
".",
"_qobj_config",
".",
"seed",
"else",
":",
"# For compatibility on Windows force dyte to be int32",
"# and set the maximum value to be (2 ** 31) - 1",
"seed",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"2147483647",
",",
"dtype",
"=",
"'int32'",
")",
"self",
".",
"_local_random",
".",
"seed",
"(",
"seed",
"=",
"seed",
")",
"# Check if measure sampling is supported for current circuit",
"self",
".",
"_validate_measure_sampling",
"(",
"experiment",
")",
"# List of final counts for all shots",
"memory",
"=",
"[",
"]",
"# Check if we can sample measurements, if so we only perform 1 shot",
"# and sample all outcomes from the final state vector",
"if",
"self",
".",
"_sample_measure",
":",
"shots",
"=",
"1",
"# Store (qubit, cmembit) pairs for all measure ops in circuit to",
"# be sampled",
"measure_sample_ops",
"=",
"[",
"]",
"else",
":",
"shots",
"=",
"self",
".",
"_shots",
"for",
"_",
"in",
"range",
"(",
"shots",
")",
":",
"self",
".",
"_initialize_statevector",
"(",
")",
"# Initialize classical memory to all 0",
"self",
".",
"_classical_memory",
"=",
"0",
"self",
".",
"_classical_register",
"=",
"0",
"for",
"operation",
"in",
"experiment",
".",
"instructions",
":",
"conditional",
"=",
"getattr",
"(",
"operation",
",",
"'conditional'",
",",
"None",
")",
"if",
"isinstance",
"(",
"conditional",
",",
"int",
")",
":",
"conditional_bit_set",
"=",
"(",
"self",
".",
"_classical_register",
">>",
"conditional",
")",
"&",
"1",
"if",
"not",
"conditional_bit_set",
":",
"continue",
"elif",
"conditional",
"is",
"not",
"None",
":",
"mask",
"=",
"int",
"(",
"operation",
".",
"conditional",
".",
"mask",
",",
"16",
")",
"if",
"mask",
">",
"0",
":",
"value",
"=",
"self",
".",
"_classical_memory",
"&",
"mask",
"while",
"(",
"mask",
"&",
"0x1",
")",
"==",
"0",
":",
"mask",
">>=",
"1",
"value",
">>=",
"1",
"if",
"value",
"!=",
"int",
"(",
"operation",
".",
"conditional",
".",
"val",
",",
"16",
")",
":",
"continue",
"# Check if single gate",
"if",
"operation",
".",
"name",
"in",
"(",
"'U'",
",",
"'u1'",
",",
"'u2'",
",",
"'u3'",
")",
":",
"params",
"=",
"getattr",
"(",
"operation",
",",
"'params'",
",",
"None",
")",
"qubit",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"gate",
"=",
"single_gate_matrix",
"(",
"operation",
".",
"name",
",",
"params",
")",
"self",
".",
"_add_unitary_single",
"(",
"gate",
",",
"qubit",
")",
"# Check if CX gate",
"elif",
"operation",
".",
"name",
"in",
"(",
"'id'",
",",
"'u0'",
")",
":",
"pass",
"elif",
"operation",
".",
"name",
"in",
"(",
"'CX'",
",",
"'cx'",
")",
":",
"qubit0",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"qubit1",
"=",
"operation",
".",
"qubits",
"[",
"1",
"]",
"gate",
"=",
"cx_gate_matrix",
"(",
")",
"self",
".",
"_add_unitary_two",
"(",
"gate",
",",
"qubit0",
",",
"qubit1",
")",
"# Check if reset",
"elif",
"operation",
".",
"name",
"==",
"'reset'",
":",
"qubit",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"self",
".",
"_add_qasm_reset",
"(",
"qubit",
")",
"# Check if barrier",
"elif",
"operation",
".",
"name",
"==",
"'barrier'",
":",
"pass",
"# Check if measure",
"elif",
"operation",
".",
"name",
"==",
"'measure'",
":",
"qubit",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"cmembit",
"=",
"operation",
".",
"memory",
"[",
"0",
"]",
"cregbit",
"=",
"operation",
".",
"register",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"operation",
",",
"'register'",
")",
"else",
"None",
"if",
"self",
".",
"_sample_measure",
":",
"# If sampling measurements record the qubit and cmembit",
"# for this measurement for later sampling",
"measure_sample_ops",
".",
"append",
"(",
"(",
"qubit",
",",
"cmembit",
")",
")",
"else",
":",
"# If not sampling perform measurement as normal",
"self",
".",
"_add_qasm_measure",
"(",
"qubit",
",",
"cmembit",
",",
"cregbit",
")",
"elif",
"operation",
".",
"name",
"==",
"'bfunc'",
":",
"mask",
"=",
"int",
"(",
"operation",
".",
"mask",
",",
"16",
")",
"relation",
"=",
"operation",
".",
"relation",
"val",
"=",
"int",
"(",
"operation",
".",
"val",
",",
"16",
")",
"cregbit",
"=",
"operation",
".",
"register",
"cmembit",
"=",
"operation",
".",
"memory",
"if",
"hasattr",
"(",
"operation",
",",
"'memory'",
")",
"else",
"None",
"compared",
"=",
"(",
"self",
".",
"_classical_register",
"&",
"mask",
")",
"-",
"val",
"if",
"relation",
"==",
"'=='",
":",
"outcome",
"=",
"(",
"compared",
"==",
"0",
")",
"elif",
"relation",
"==",
"'!='",
":",
"outcome",
"=",
"(",
"compared",
"!=",
"0",
")",
"elif",
"relation",
"==",
"'<'",
":",
"outcome",
"=",
"(",
"compared",
"<",
"0",
")",
"elif",
"relation",
"==",
"'<='",
":",
"outcome",
"=",
"(",
"compared",
"<=",
"0",
")",
"elif",
"relation",
"==",
"'>'",
":",
"outcome",
"=",
"(",
"compared",
">",
"0",
")",
"elif",
"relation",
"==",
"'>='",
":",
"outcome",
"=",
"(",
"compared",
">=",
"0",
")",
"else",
":",
"raise",
"BasicAerError",
"(",
"'Invalid boolean function relation.'",
")",
"# Store outcome in register and optionally memory slot",
"regbit",
"=",
"1",
"<<",
"cregbit",
"self",
".",
"_classical_register",
"=",
"(",
"self",
".",
"_classical_register",
"&",
"(",
"~",
"regbit",
")",
")",
"|",
"(",
"int",
"(",
"outcome",
")",
"<<",
"cregbit",
")",
"if",
"cmembit",
"is",
"not",
"None",
":",
"membit",
"=",
"1",
"<<",
"cmembit",
"self",
".",
"_classical_memory",
"=",
"(",
"self",
".",
"_classical_memory",
"&",
"(",
"~",
"membit",
")",
")",
"|",
"(",
"int",
"(",
"outcome",
")",
"<<",
"cmembit",
")",
"else",
":",
"backend",
"=",
"self",
".",
"name",
"(",
")",
"err_msg",
"=",
"'{0} encountered unrecognized operation \"{1}\"'",
"raise",
"BasicAerError",
"(",
"err_msg",
".",
"format",
"(",
"backend",
",",
"operation",
".",
"name",
")",
")",
"# Add final creg data to memory list",
"if",
"self",
".",
"_number_of_cmembits",
">",
"0",
":",
"if",
"self",
".",
"_sample_measure",
":",
"# If sampling we generate all shot samples from the final statevector",
"memory",
"=",
"self",
".",
"_add_sample_measure",
"(",
"measure_sample_ops",
",",
"self",
".",
"_shots",
")",
"else",
":",
"# Turn classical_memory (int) into bit string and pad zero for unused cmembits",
"outcome",
"=",
"bin",
"(",
"self",
".",
"_classical_memory",
")",
"[",
"2",
":",
"]",
"memory",
".",
"append",
"(",
"hex",
"(",
"int",
"(",
"outcome",
",",
"2",
")",
")",
")",
"# Add data",
"data",
"=",
"{",
"'counts'",
":",
"dict",
"(",
"Counter",
"(",
"memory",
")",
")",
"}",
"# Optionally add memory list",
"if",
"self",
".",
"_memory",
":",
"data",
"[",
"'memory'",
"]",
"=",
"memory",
"# Optionally add final statevector",
"if",
"self",
".",
"SHOW_FINAL_STATE",
":",
"data",
"[",
"'statevector'",
"]",
"=",
"self",
".",
"_get_statevector",
"(",
")",
"# Remove empty counts and memory for statevector simulator",
"if",
"not",
"data",
"[",
"'counts'",
"]",
":",
"data",
".",
"pop",
"(",
"'counts'",
")",
"if",
"'memory'",
"in",
"data",
"and",
"not",
"data",
"[",
"'memory'",
"]",
":",
"data",
".",
"pop",
"(",
"'memory'",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"return",
"{",
"'name'",
":",
"experiment",
".",
"header",
".",
"name",
",",
"'seed'",
":",
"seed",
",",
"'shots'",
":",
"self",
".",
"_shots",
",",
"'data'",
":",
"data",
",",
"'status'",
":",
"'DONE'",
",",
"'success'",
":",
"True",
",",
"'time_taken'",
":",
"(",
"end",
"-",
"start",
")",
",",
"'header'",
":",
"experiment",
".",
"header",
".",
"as_dict",
"(",
")",
"}"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
QasmSimulatorPy._validate
|
Semantic validations of the qobj which cannot be done via schemas.
|
qiskit/providers/basicaer/qasm_simulator.py
|
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas."""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise BasicAerError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
for experiment in qobj.experiments:
name = experiment.header.name
if experiment.config.memory_slots == 0:
logger.warning('No classical registers in circuit "%s", '
'counts will be empty.', name)
elif 'measure' not in [op.name for op in experiment.instructions]:
logger.warning('No measurements in circuit "%s", '
'classical register will remain all zeros.', name)
|
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas."""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise BasicAerError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
for experiment in qobj.experiments:
name = experiment.header.name
if experiment.config.memory_slots == 0:
logger.warning('No classical registers in circuit "%s", '
'counts will be empty.', name)
elif 'measure' not in [op.name for op in experiment.instructions]:
logger.warning('No measurements in circuit "%s", '
'classical register will remain all zeros.', name)
|
[
"Semantic",
"validations",
"of",
"the",
"qobj",
"which",
"cannot",
"be",
"done",
"via",
"schemas",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L622-L637
|
[
"def",
"_validate",
"(",
"self",
",",
"qobj",
")",
":",
"n_qubits",
"=",
"qobj",
".",
"config",
".",
"n_qubits",
"max_qubits",
"=",
"self",
".",
"configuration",
"(",
")",
".",
"n_qubits",
"if",
"n_qubits",
">",
"max_qubits",
":",
"raise",
"BasicAerError",
"(",
"'Number of qubits {} '",
".",
"format",
"(",
"n_qubits",
")",
"+",
"'is greater than maximum ({}) '",
".",
"format",
"(",
"max_qubits",
")",
"+",
"'for \"{}\".'",
".",
"format",
"(",
"self",
".",
"name",
"(",
")",
")",
")",
"for",
"experiment",
"in",
"qobj",
".",
"experiments",
":",
"name",
"=",
"experiment",
".",
"header",
".",
"name",
"if",
"experiment",
".",
"config",
".",
"memory_slots",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"'No classical registers in circuit \"%s\", '",
"'counts will be empty.'",
",",
"name",
")",
"elif",
"'measure'",
"not",
"in",
"[",
"op",
".",
"name",
"for",
"op",
"in",
"experiment",
".",
"instructions",
"]",
":",
"logger",
".",
"warning",
"(",
"'No measurements in circuit \"%s\", '",
"'classical register will remain all zeros.'",
",",
"name",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._add_unitary_single
|
Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _add_unitary_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to
"""
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_matmul_index([qubit], self._number_of_qubits)
# Apply matrix multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no')
|
def _add_unitary_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to
"""
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_matmul_index([qubit], self._number_of_qubits)
# Apply matrix multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no')
|
[
"Apply",
"an",
"arbitrary",
"1",
"-",
"qubit",
"unitary",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L110-L123
|
[
"def",
"_add_unitary_single",
"(",
"self",
",",
"gate",
",",
"qubit",
")",
":",
"# Convert to complex rank-2 tensor",
"gate_tensor",
"=",
"np",
".",
"array",
"(",
"gate",
",",
"dtype",
"=",
"complex",
")",
"# Compute einsum index string for 1-qubit matrix multiplication",
"indexes",
"=",
"einsum_matmul_index",
"(",
"[",
"qubit",
"]",
",",
"self",
".",
"_number_of_qubits",
")",
"# Apply matrix multiplication",
"self",
".",
"_unitary",
"=",
"np",
".",
"einsum",
"(",
"indexes",
",",
"gate_tensor",
",",
"self",
".",
"_unitary",
",",
"dtype",
"=",
"complex",
",",
"casting",
"=",
"'no'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._add_unitary_two
|
Apply a two-qubit unitary matrix.
Args:
gate (matrix_like): a the two-qubit gate matrix
qubit0 (int): gate qubit-0
qubit1 (int): gate qubit-1
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _add_unitary_two(self, gate, qubit0, qubit1):
"""Apply a two-qubit unitary matrix.
Args:
gate (matrix_like): a the two-qubit gate matrix
qubit0 (int): gate qubit-0
qubit1 (int): gate qubit-1
"""
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Compute einsum index string for 2-qubit matrix multiplication
indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits)
# Apply matrix multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no')
|
def _add_unitary_two(self, gate, qubit0, qubit1):
"""Apply a two-qubit unitary matrix.
Args:
gate (matrix_like): a the two-qubit gate matrix
qubit0 (int): gate qubit-0
qubit1 (int): gate qubit-1
"""
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Compute einsum index string for 2-qubit matrix multiplication
indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits)
# Apply matrix multiplication
self._unitary = np.einsum(indexes, gate_tensor, self._unitary,
dtype=complex, casting='no')
|
[
"Apply",
"a",
"two",
"-",
"qubit",
"unitary",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L125-L142
|
[
"def",
"_add_unitary_two",
"(",
"self",
",",
"gate",
",",
"qubit0",
",",
"qubit1",
")",
":",
"# Convert to complex rank-4 tensor",
"gate_tensor",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"array",
"(",
"gate",
",",
"dtype",
"=",
"complex",
")",
",",
"4",
"*",
"[",
"2",
"]",
")",
"# Compute einsum index string for 2-qubit matrix multiplication",
"indexes",
"=",
"einsum_matmul_index",
"(",
"[",
"qubit0",
",",
"qubit1",
"]",
",",
"self",
".",
"_number_of_qubits",
")",
"# Apply matrix multiplication",
"self",
".",
"_unitary",
"=",
"np",
".",
"einsum",
"(",
"indexes",
",",
"gate_tensor",
",",
"self",
".",
"_unitary",
",",
"dtype",
"=",
"complex",
",",
"casting",
"=",
"'no'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._validate_initial_unitary
|
Validate an initial unitary matrix
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _validate_initial_unitary(self):
"""Validate an initial unitary matrix"""
# If initial unitary isn't set we don't need to validate
if self._initial_unitary is None:
return
# Check unitary is correct length for number of qubits
shape = np.shape(self._initial_unitary)
required_shape = (2 ** self._number_of_qubits,
2 ** self._number_of_qubits)
if shape != required_shape:
raise BasicAerError('initial unitary is incorrect shape: ' +
'{} != 2 ** {}'.format(shape, required_shape))
|
def _validate_initial_unitary(self):
"""Validate an initial unitary matrix"""
# If initial unitary isn't set we don't need to validate
if self._initial_unitary is None:
return
# Check unitary is correct length for number of qubits
shape = np.shape(self._initial_unitary)
required_shape = (2 ** self._number_of_qubits,
2 ** self._number_of_qubits)
if shape != required_shape:
raise BasicAerError('initial unitary is incorrect shape: ' +
'{} != 2 ** {}'.format(shape, required_shape))
|
[
"Validate",
"an",
"initial",
"unitary",
"matrix"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L144-L155
|
[
"def",
"_validate_initial_unitary",
"(",
"self",
")",
":",
"# If initial unitary isn't set we don't need to validate",
"if",
"self",
".",
"_initial_unitary",
"is",
"None",
":",
"return",
"# Check unitary is correct length for number of qubits",
"shape",
"=",
"np",
".",
"shape",
"(",
"self",
".",
"_initial_unitary",
")",
"required_shape",
"=",
"(",
"2",
"**",
"self",
".",
"_number_of_qubits",
",",
"2",
"**",
"self",
".",
"_number_of_qubits",
")",
"if",
"shape",
"!=",
"required_shape",
":",
"raise",
"BasicAerError",
"(",
"'initial unitary is incorrect shape: '",
"+",
"'{} != 2 ** {}'",
".",
"format",
"(",
"shape",
",",
"required_shape",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._set_options
|
Set the backend options for all experiments in a qobj
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_unitary = self.DEFAULT_OPTIONS["initial_unitary"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_unitary' in backend_options:
self._initial_unitary = np.array(backend_options['initial_unitary'],
dtype=complex)
elif hasattr(qobj_config, 'initial_unitary'):
self._initial_unitary = np.array(qobj_config.initial_unitary,
dtype=complex)
if self._initial_unitary is not None:
# Check the initial unitary is actually unitary
shape = np.shape(self._initial_unitary)
if len(shape) != 2 or shape[0] != shape[1]:
raise BasicAerError("initial unitary is not a square matrix")
iden = np.eye(len(self._initial_unitary))
u_dagger_u = np.dot(self._initial_unitary.T.conj(),
self._initial_unitary)
norm = np.linalg.norm(u_dagger_u - iden)
if round(norm, 10) != 0:
raise BasicAerError("initial unitary is not unitary")
# Check the initial statevector is normalized
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
|
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_unitary = self.DEFAULT_OPTIONS["initial_unitary"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_unitary' in backend_options:
self._initial_unitary = np.array(backend_options['initial_unitary'],
dtype=complex)
elif hasattr(qobj_config, 'initial_unitary'):
self._initial_unitary = np.array(qobj_config.initial_unitary,
dtype=complex)
if self._initial_unitary is not None:
# Check the initial unitary is actually unitary
shape = np.shape(self._initial_unitary)
if len(shape) != 2 or shape[0] != shape[1]:
raise BasicAerError("initial unitary is not a square matrix")
iden = np.eye(len(self._initial_unitary))
u_dagger_u = np.dot(self._initial_unitary.T.conj(),
self._initial_unitary)
norm = np.linalg.norm(u_dagger_u - iden)
if round(norm, 10) != 0:
raise BasicAerError("initial unitary is not unitary")
# Check the initial statevector is normalized
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
|
[
"Set",
"the",
"backend",
"options",
"for",
"all",
"experiments",
"in",
"a",
"qobj"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L157-L191
|
[
"def",
"_set_options",
"(",
"self",
",",
"qobj_config",
"=",
"None",
",",
"backend_options",
"=",
"None",
")",
":",
"# Reset default options",
"self",
".",
"_initial_unitary",
"=",
"self",
".",
"DEFAULT_OPTIONS",
"[",
"\"initial_unitary\"",
"]",
"self",
".",
"_chop_threshold",
"=",
"self",
".",
"DEFAULT_OPTIONS",
"[",
"\"chop_threshold\"",
"]",
"if",
"backend_options",
"is",
"None",
":",
"backend_options",
"=",
"{",
"}",
"# Check for custom initial statevector in backend_options first,",
"# then config second",
"if",
"'initial_unitary'",
"in",
"backend_options",
":",
"self",
".",
"_initial_unitary",
"=",
"np",
".",
"array",
"(",
"backend_options",
"[",
"'initial_unitary'",
"]",
",",
"dtype",
"=",
"complex",
")",
"elif",
"hasattr",
"(",
"qobj_config",
",",
"'initial_unitary'",
")",
":",
"self",
".",
"_initial_unitary",
"=",
"np",
".",
"array",
"(",
"qobj_config",
".",
"initial_unitary",
",",
"dtype",
"=",
"complex",
")",
"if",
"self",
".",
"_initial_unitary",
"is",
"not",
"None",
":",
"# Check the initial unitary is actually unitary",
"shape",
"=",
"np",
".",
"shape",
"(",
"self",
".",
"_initial_unitary",
")",
"if",
"len",
"(",
"shape",
")",
"!=",
"2",
"or",
"shape",
"[",
"0",
"]",
"!=",
"shape",
"[",
"1",
"]",
":",
"raise",
"BasicAerError",
"(",
"\"initial unitary is not a square matrix\"",
")",
"iden",
"=",
"np",
".",
"eye",
"(",
"len",
"(",
"self",
".",
"_initial_unitary",
")",
")",
"u_dagger_u",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"_initial_unitary",
".",
"T",
".",
"conj",
"(",
")",
",",
"self",
".",
"_initial_unitary",
")",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"u_dagger_u",
"-",
"iden",
")",
"if",
"round",
"(",
"norm",
",",
"10",
")",
"!=",
"0",
":",
"raise",
"BasicAerError",
"(",
"\"initial unitary is not unitary\"",
")",
"# Check the initial statevector is normalized",
"# Check for custom chop threshold",
"# Replace with custom options",
"if",
"'chop_threshold'",
"in",
"backend_options",
":",
"self",
".",
"_chop_threshold",
"=",
"backend_options",
"[",
"'chop_threshold'",
"]",
"elif",
"hasattr",
"(",
"qobj_config",
",",
"'chop_threshold'",
")",
":",
"self",
".",
"_chop_threshold",
"=",
"qobj_config",
".",
"chop_threshold"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._initialize_unitary
|
Set the initial unitary for simulation
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _initialize_unitary(self):
"""Set the initial unitary for simulation"""
self._validate_initial_unitary()
if self._initial_unitary is None:
# Set to identity matrix
self._unitary = np.eye(2 ** self._number_of_qubits,
dtype=complex)
else:
self._unitary = self._initial_unitary.copy()
# Reshape to rank-N tensor
self._unitary = np.reshape(self._unitary,
self._number_of_qubits * [2, 2])
|
def _initialize_unitary(self):
"""Set the initial unitary for simulation"""
self._validate_initial_unitary()
if self._initial_unitary is None:
# Set to identity matrix
self._unitary = np.eye(2 ** self._number_of_qubits,
dtype=complex)
else:
self._unitary = self._initial_unitary.copy()
# Reshape to rank-N tensor
self._unitary = np.reshape(self._unitary,
self._number_of_qubits * [2, 2])
|
[
"Set",
"the",
"initial",
"unitary",
"for",
"simulation"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L193-L204
|
[
"def",
"_initialize_unitary",
"(",
"self",
")",
":",
"self",
".",
"_validate_initial_unitary",
"(",
")",
"if",
"self",
".",
"_initial_unitary",
"is",
"None",
":",
"# Set to identity matrix",
"self",
".",
"_unitary",
"=",
"np",
".",
"eye",
"(",
"2",
"**",
"self",
".",
"_number_of_qubits",
",",
"dtype",
"=",
"complex",
")",
"else",
":",
"self",
".",
"_unitary",
"=",
"self",
".",
"_initial_unitary",
".",
"copy",
"(",
")",
"# Reshape to rank-N tensor",
"self",
".",
"_unitary",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_unitary",
",",
"self",
".",
"_number_of_qubits",
"*",
"[",
"2",
",",
"2",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._get_unitary
|
Return the current unitary in JSON Result spec format
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _get_unitary(self):
"""Return the current unitary in JSON Result spec format"""
unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits])
# Expand complex numbers
unitary = np.stack((unitary.real, unitary.imag), axis=-1)
# Truncate small values
unitary[abs(unitary) < self._chop_threshold] = 0.0
return unitary
|
def _get_unitary(self):
"""Return the current unitary in JSON Result spec format"""
unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits])
# Expand complex numbers
unitary = np.stack((unitary.real, unitary.imag), axis=-1)
# Truncate small values
unitary[abs(unitary) < self._chop_threshold] = 0.0
return unitary
|
[
"Return",
"the",
"current",
"unitary",
"in",
"JSON",
"Result",
"spec",
"format"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L206-L213
|
[
"def",
"_get_unitary",
"(",
"self",
")",
":",
"unitary",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"_unitary",
",",
"2",
"*",
"[",
"2",
"**",
"self",
".",
"_number_of_qubits",
"]",
")",
"# Expand complex numbers",
"unitary",
"=",
"np",
".",
"stack",
"(",
"(",
"unitary",
".",
"real",
",",
"unitary",
".",
"imag",
")",
",",
"axis",
"=",
"-",
"1",
")",
"# Truncate small values",
"unitary",
"[",
"abs",
"(",
"unitary",
")",
"<",
"self",
".",
"_chop_threshold",
"]",
"=",
"0.0",
"return",
"unitary"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._run_job
|
Run experiments in qobj.
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _run_job(self, job_id, qobj):
"""Run experiments in qobj.
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
|
def _run_job(self, job_id, qobj):
"""Run experiments in qobj.
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
|
[
"Run",
"experiments",
"in",
"qobj",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L257-L283
|
[
"def",
"_run_job",
"(",
"self",
",",
"job_id",
",",
"qobj",
")",
":",
"self",
".",
"_validate",
"(",
"qobj",
")",
"result_list",
"=",
"[",
"]",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"experiment",
"in",
"qobj",
".",
"experiments",
":",
"result_list",
".",
"append",
"(",
"self",
".",
"run_experiment",
"(",
"experiment",
")",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"{",
"'backend_name'",
":",
"self",
".",
"name",
"(",
")",
",",
"'backend_version'",
":",
"self",
".",
"_configuration",
".",
"backend_version",
",",
"'qobj_id'",
":",
"qobj",
".",
"qobj_id",
",",
"'job_id'",
":",
"job_id",
",",
"'results'",
":",
"result_list",
",",
"'status'",
":",
"'COMPLETED'",
",",
"'success'",
":",
"True",
",",
"'time_taken'",
":",
"(",
"end",
"-",
"start",
")",
",",
"'header'",
":",
"qobj",
".",
"header",
".",
"as_dict",
"(",
")",
"}",
"return",
"Result",
".",
"from_dict",
"(",
"result",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy.run_experiment
|
Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"unitary": [[[0.0, 0.0], [1.0, 0.0]],
[[1.0, 0.0], [0.0, 0.0]]]
},
"status": status string for the simulation
"success": boolean
"time taken": simulation time of this single experiment
}
Raises:
BasicAerError: if the number of qubits in the circuit is greater than 24.
Note that the practical qubit limit is much lower than 24.
|
qiskit/providers/basicaer/unitary_simulator.py
|
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"unitary": [[[0.0, 0.0], [1.0, 0.0]],
[[1.0, 0.0], [0.0, 0.0]]]
},
"status": status string for the simulation
"success": boolean
"time taken": simulation time of this single experiment
}
Raises:
BasicAerError: if the number of qubits in the circuit is greater than 24.
Note that the practical qubit limit is much lower than 24.
"""
start = time.time()
self._number_of_qubits = experiment.header.n_qubits
# Validate the dimension of initial unitary if set
self._validate_initial_unitary()
self._initialize_unitary()
for operation in experiment.instructions:
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
elif operation.name in ('id', 'u0'):
pass
# Check if CX gate
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if barrier
elif operation.name == 'barrier':
pass
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise BasicAerError(err_msg.format(backend, operation.name))
# Add final state to data
data = {'unitary': self._get_unitary()}
end = time.time()
return {'name': experiment.header.name,
'shots': 1,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
|
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"unitary": [[[0.0, 0.0], [1.0, 0.0]],
[[1.0, 0.0], [0.0, 0.0]]]
},
"status": status string for the simulation
"success": boolean
"time taken": simulation time of this single experiment
}
Raises:
BasicAerError: if the number of qubits in the circuit is greater than 24.
Note that the practical qubit limit is much lower than 24.
"""
start = time.time()
self._number_of_qubits = experiment.header.n_qubits
# Validate the dimension of initial unitary if set
self._validate_initial_unitary()
self._initialize_unitary()
for operation in experiment.instructions:
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
elif operation.name in ('id', 'u0'):
pass
# Check if CX gate
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if barrier
elif operation.name == 'barrier':
pass
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise BasicAerError(err_msg.format(backend, operation.name))
# Add final state to data
data = {'unitary': self._get_unitary()}
end = time.time()
return {'name': experiment.header.name,
'shots': 1,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
|
[
"Run",
"an",
"experiment",
"(",
"circuit",
")",
"and",
"return",
"a",
"single",
"experiment",
"result",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L285-L350
|
[
"def",
"run_experiment",
"(",
"self",
",",
"experiment",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_number_of_qubits",
"=",
"experiment",
".",
"header",
".",
"n_qubits",
"# Validate the dimension of initial unitary if set",
"self",
".",
"_validate_initial_unitary",
"(",
")",
"self",
".",
"_initialize_unitary",
"(",
")",
"for",
"operation",
"in",
"experiment",
".",
"instructions",
":",
"# Check if single gate",
"if",
"operation",
".",
"name",
"in",
"(",
"'U'",
",",
"'u1'",
",",
"'u2'",
",",
"'u3'",
")",
":",
"params",
"=",
"getattr",
"(",
"operation",
",",
"'params'",
",",
"None",
")",
"qubit",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"gate",
"=",
"single_gate_matrix",
"(",
"operation",
".",
"name",
",",
"params",
")",
"self",
".",
"_add_unitary_single",
"(",
"gate",
",",
"qubit",
")",
"elif",
"operation",
".",
"name",
"in",
"(",
"'id'",
",",
"'u0'",
")",
":",
"pass",
"# Check if CX gate",
"elif",
"operation",
".",
"name",
"in",
"(",
"'CX'",
",",
"'cx'",
")",
":",
"qubit0",
"=",
"operation",
".",
"qubits",
"[",
"0",
"]",
"qubit1",
"=",
"operation",
".",
"qubits",
"[",
"1",
"]",
"gate",
"=",
"cx_gate_matrix",
"(",
")",
"self",
".",
"_add_unitary_two",
"(",
"gate",
",",
"qubit0",
",",
"qubit1",
")",
"# Check if barrier",
"elif",
"operation",
".",
"name",
"==",
"'barrier'",
":",
"pass",
"else",
":",
"backend",
"=",
"self",
".",
"name",
"(",
")",
"err_msg",
"=",
"'{0} encountered unrecognized operation \"{1}\"'",
"raise",
"BasicAerError",
"(",
"err_msg",
".",
"format",
"(",
"backend",
",",
"operation",
".",
"name",
")",
")",
"# Add final state to data",
"data",
"=",
"{",
"'unitary'",
":",
"self",
".",
"_get_unitary",
"(",
")",
"}",
"end",
"=",
"time",
".",
"time",
"(",
")",
"return",
"{",
"'name'",
":",
"experiment",
".",
"header",
".",
"name",
",",
"'shots'",
":",
"1",
",",
"'data'",
":",
"data",
",",
"'status'",
":",
"'DONE'",
",",
"'success'",
":",
"True",
",",
"'time_taken'",
":",
"(",
"end",
"-",
"start",
")",
",",
"'header'",
":",
"experiment",
".",
"header",
".",
"as_dict",
"(",
")",
"}"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
UnitarySimulatorPy._validate
|
Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
|
qiskit/providers/basicaer/unitary_simulator.py
|
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise BasicAerError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
if hasattr(qobj.config, 'shots') and qobj.config.shots != 1:
logger.info('"%s" only supports 1 shot. Setting shots=1.',
self.name())
qobj.config.shots = 1
for experiment in qobj.experiments:
name = experiment.header.name
if getattr(experiment.config, 'shots', 1) != 1:
logger.info('"%s" only supports 1 shot. '
'Setting shots=1 for circuit "%s".',
self.name(), name)
experiment.config.shots = 1
for operation in experiment.instructions:
if operation.name in ['measure', 'reset']:
raise BasicAerError('Unsupported "%s" instruction "%s" ' +
'in circuit "%s" ', self.name(),
operation.name, name)
|
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise BasicAerError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
if hasattr(qobj.config, 'shots') and qobj.config.shots != 1:
logger.info('"%s" only supports 1 shot. Setting shots=1.',
self.name())
qobj.config.shots = 1
for experiment in qobj.experiments:
name = experiment.header.name
if getattr(experiment.config, 'shots', 1) != 1:
logger.info('"%s" only supports 1 shot. '
'Setting shots=1 for circuit "%s".',
self.name(), name)
experiment.config.shots = 1
for operation in experiment.instructions:
if operation.name in ['measure', 'reset']:
raise BasicAerError('Unsupported "%s" instruction "%s" ' +
'in circuit "%s" ', self.name(),
operation.name, name)
|
[
"Semantic",
"validations",
"of",
"the",
"qobj",
"which",
"cannot",
"be",
"done",
"via",
"schemas",
".",
"Some",
"of",
"these",
"may",
"later",
"move",
"to",
"backend",
"schemas",
".",
"1",
".",
"No",
"shots",
"2",
".",
"No",
"measurements",
"in",
"the",
"middle"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L352-L379
|
[
"def",
"_validate",
"(",
"self",
",",
"qobj",
")",
":",
"n_qubits",
"=",
"qobj",
".",
"config",
".",
"n_qubits",
"max_qubits",
"=",
"self",
".",
"configuration",
"(",
")",
".",
"n_qubits",
"if",
"n_qubits",
">",
"max_qubits",
":",
"raise",
"BasicAerError",
"(",
"'Number of qubits {} '",
".",
"format",
"(",
"n_qubits",
")",
"+",
"'is greater than maximum ({}) '",
".",
"format",
"(",
"max_qubits",
")",
"+",
"'for \"{}\".'",
".",
"format",
"(",
"self",
".",
"name",
"(",
")",
")",
")",
"if",
"hasattr",
"(",
"qobj",
".",
"config",
",",
"'shots'",
")",
"and",
"qobj",
".",
"config",
".",
"shots",
"!=",
"1",
":",
"logger",
".",
"info",
"(",
"'\"%s\" only supports 1 shot. Setting shots=1.'",
",",
"self",
".",
"name",
"(",
")",
")",
"qobj",
".",
"config",
".",
"shots",
"=",
"1",
"for",
"experiment",
"in",
"qobj",
".",
"experiments",
":",
"name",
"=",
"experiment",
".",
"header",
".",
"name",
"if",
"getattr",
"(",
"experiment",
".",
"config",
",",
"'shots'",
",",
"1",
")",
"!=",
"1",
":",
"logger",
".",
"info",
"(",
"'\"%s\" only supports 1 shot. '",
"'Setting shots=1 for circuit \"%s\".'",
",",
"self",
".",
"name",
"(",
")",
",",
"name",
")",
"experiment",
".",
"config",
".",
"shots",
"=",
"1",
"for",
"operation",
"in",
"experiment",
".",
"instructions",
":",
"if",
"operation",
".",
"name",
"in",
"[",
"'measure'",
",",
"'reset'",
"]",
":",
"raise",
"BasicAerError",
"(",
"'Unsupported \"%s\" instruction \"%s\" '",
"+",
"'in circuit \"%s\" '",
",",
"self",
".",
"name",
"(",
")",
",",
"operation",
".",
"name",
",",
"name",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_is_bit
|
Determine if obj is a bit
|
qiskit/circuit/decorators.py
|
def _is_bit(obj):
"""Determine if obj is a bit"""
# If there is a bit type this could be replaced by isinstance.
if isinstance(obj, tuple) and len(obj) == 2:
if isinstance(obj[0], Register) and isinstance(obj[1], int) and obj[1] < len(obj[0]):
return True
return False
|
def _is_bit(obj):
"""Determine if obj is a bit"""
# If there is a bit type this could be replaced by isinstance.
if isinstance(obj, tuple) and len(obj) == 2:
if isinstance(obj[0], Register) and isinstance(obj[1], int) and obj[1] < len(obj[0]):
return True
return False
|
[
"Determine",
"if",
"obj",
"is",
"a",
"bit"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/decorators.py#L21-L27
|
[
"def",
"_is_bit",
"(",
"obj",
")",
":",
"# If there is a bit type this could be replaced by isinstance.",
"if",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
"and",
"len",
"(",
"obj",
")",
"==",
"2",
":",
"if",
"isinstance",
"(",
"obj",
"[",
"0",
"]",
",",
"Register",
")",
"and",
"isinstance",
"(",
"obj",
"[",
"1",
"]",
",",
"int",
")",
"and",
"obj",
"[",
"1",
"]",
"<",
"len",
"(",
"obj",
"[",
"0",
"]",
")",
":",
"return",
"True",
"return",
"False"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_convert_to_bits
|
Recursively converts the integers, tuples and ranges in a_list
for a qu/clbit from the bits. E.g. bits[item_in_a_list]
|
qiskit/circuit/decorators.py
|
def _convert_to_bits(a_list, bits):
""" Recursively converts the integers, tuples and ranges in a_list
for a qu/clbit from the bits. E.g. bits[item_in_a_list]"""
new_list = []
for item in a_list:
if isinstance(item, (int, slice)):
# eg. circuit.h(2)
# eg. circuit.h(slice(0, 2))
try:
new_list.append(bits[item])
except IndexError:
raise QiskitError("The integer param is out of range")
elif isinstance(item, list):
# eg. circuit.h([0, 2])
new_list.append(_convert_to_bits(item, bits))
elif isinstance(item, range):
# eg. circuit.h(range(0, 2))
new_list.append(_convert_to_bits([index for index in item], bits))
else:
new_list.append(item)
return new_list
|
def _convert_to_bits(a_list, bits):
""" Recursively converts the integers, tuples and ranges in a_list
for a qu/clbit from the bits. E.g. bits[item_in_a_list]"""
new_list = []
for item in a_list:
if isinstance(item, (int, slice)):
# eg. circuit.h(2)
# eg. circuit.h(slice(0, 2))
try:
new_list.append(bits[item])
except IndexError:
raise QiskitError("The integer param is out of range")
elif isinstance(item, list):
# eg. circuit.h([0, 2])
new_list.append(_convert_to_bits(item, bits))
elif isinstance(item, range):
# eg. circuit.h(range(0, 2))
new_list.append(_convert_to_bits([index for index in item], bits))
else:
new_list.append(item)
return new_list
|
[
"Recursively",
"converts",
"the",
"integers",
"tuples",
"and",
"ranges",
"in",
"a_list",
"for",
"a",
"qu",
"/",
"clbit",
"from",
"the",
"bits",
".",
"E",
".",
"g",
".",
"bits",
"[",
"item_in_a_list",
"]"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/decorators.py#L30-L50
|
[
"def",
"_convert_to_bits",
"(",
"a_list",
",",
"bits",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"item",
"in",
"a_list",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"int",
",",
"slice",
")",
")",
":",
"# eg. circuit.h(2)",
"# eg. circuit.h(slice(0, 2))",
"try",
":",
"new_list",
".",
"append",
"(",
"bits",
"[",
"item",
"]",
")",
"except",
"IndexError",
":",
"raise",
"QiskitError",
"(",
"\"The integer param is out of range\"",
")",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"# eg. circuit.h([0, 2])",
"new_list",
".",
"append",
"(",
"_convert_to_bits",
"(",
"item",
",",
"bits",
")",
")",
"elif",
"isinstance",
"(",
"item",
",",
"range",
")",
":",
"# eg. circuit.h(range(0, 2))",
"new_list",
".",
"append",
"(",
"_convert_to_bits",
"(",
"[",
"index",
"for",
"index",
"in",
"item",
"]",
",",
"bits",
")",
")",
"else",
":",
"new_list",
".",
"append",
"(",
"item",
")",
"return",
"new_list"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_to_bits
|
Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc.
For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0])
|
qiskit/circuit/decorators.py
|
def _to_bits(nqbits, ncbits=0, func=None):
"""Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc.
For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) """
if func is None:
return functools.partial(_to_bits, nqbits, ncbits)
@functools.wraps(func)
def wrapper(self, *args):
qbits = self.qubits()
cbits = self.clbits()
nparams = len(args) - nqbits - ncbits
params = args[:nparams]
qb_args = args[nparams:nparams + nqbits]
cl_args = args[nparams + nqbits:]
args = list(params) + _convert_to_bits(qb_args, qbits) + _convert_to_bits(cl_args, cbits)
return func(self, *args)
return wrapper
|
def _to_bits(nqbits, ncbits=0, func=None):
"""Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc.
For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) """
if func is None:
return functools.partial(_to_bits, nqbits, ncbits)
@functools.wraps(func)
def wrapper(self, *args):
qbits = self.qubits()
cbits = self.clbits()
nparams = len(args) - nqbits - ncbits
params = args[:nparams]
qb_args = args[nparams:nparams + nqbits]
cl_args = args[nparams + nqbits:]
args = list(params) + _convert_to_bits(qb_args, qbits) + _convert_to_bits(cl_args, cbits)
return func(self, *args)
return wrapper
|
[
"Convert",
"gate",
"arguments",
"to",
"[",
"qu|cl",
"]",
"bits",
"from",
"integers",
"slices",
"ranges",
"etc",
".",
"For",
"example",
"circuit",
".",
"h",
"(",
"0",
")",
"-",
">",
"circuit",
".",
"h",
"(",
"QuantumRegister",
"(",
"2",
")",
"[",
"0",
"]",
")"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/decorators.py#L53-L73
|
[
"def",
"_to_bits",
"(",
"nqbits",
",",
"ncbits",
"=",
"0",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"functools",
".",
"partial",
"(",
"_to_bits",
",",
"nqbits",
",",
"ncbits",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
")",
":",
"qbits",
"=",
"self",
".",
"qubits",
"(",
")",
"cbits",
"=",
"self",
".",
"clbits",
"(",
")",
"nparams",
"=",
"len",
"(",
"args",
")",
"-",
"nqbits",
"-",
"ncbits",
"params",
"=",
"args",
"[",
":",
"nparams",
"]",
"qb_args",
"=",
"args",
"[",
"nparams",
":",
"nparams",
"+",
"nqbits",
"]",
"cl_args",
"=",
"args",
"[",
"nparams",
"+",
"nqbits",
":",
"]",
"args",
"=",
"list",
"(",
"params",
")",
"+",
"_convert_to_bits",
"(",
"qb_args",
",",
"qbits",
")",
"+",
"_convert_to_bits",
"(",
"cl_args",
",",
"cbits",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
")",
"return",
"wrapper"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_op_expand
|
Decorator for expanding an operation across a whole register or register subset.
Args:
n_bits (int): the number of register bit arguments the decorated function takes
func (function): used for decorators with keyword args
broadcastable (list(bool)): list of bool for which register args can be
broadcast from 1 bit to the max size of the rest of the args. Defaults
to all True if not specified.
Return:
type: partial function object
|
qiskit/circuit/decorators.py
|
def _op_expand(n_bits, func=None, broadcastable=None):
"""Decorator for expanding an operation across a whole register or register subset.
Args:
n_bits (int): the number of register bit arguments the decorated function takes
func (function): used for decorators with keyword args
broadcastable (list(bool)): list of bool for which register args can be
broadcast from 1 bit to the max size of the rest of the args. Defaults
to all True if not specified.
Return:
type: partial function object
"""
if func is None:
return functools.partial(_op_expand, n_bits, broadcastable=broadcastable)
@functools.wraps(func)
def wrapper(self, *args):
params = args[0:-n_bits] if len(args) > n_bits else tuple()
rargs = args[-n_bits:]
if broadcastable is None:
blist = [True] * len(rargs)
else:
blist = broadcastable
if not all([_is_bit(arg) for arg in rargs]):
rarg_size = [1] * n_bits
for iarg, arg in enumerate(rargs):
if isinstance(arg, Register):
rarg_size[iarg] = len(arg)
elif isinstance(arg, list) and all([_is_bit(bit) for bit in arg]):
rarg_size[iarg] = len(arg)
elif _is_bit(arg):
rarg_size[iarg] = 1
else:
raise QiskitError('operation arguments must be qubits/cbits')
broadcast_size = max(rarg_size)
expanded_rargs = []
for arg, broadcast in zip(rargs, blist):
if isinstance(arg, Register):
arg = [(arg, i) for i in range(len(arg))]
elif isinstance(arg, tuple):
arg = [arg]
# now we should have a list of qubits
if isinstance(arg, list) and len(arg) == 1 and broadcast:
arg = arg * broadcast_size
if len(arg) != broadcast_size:
raise QiskitError('register size error')
expanded_rargs.append(arg)
rargs = expanded_rargs
if all([isinstance(arg, list) for arg in rargs]):
if all(rargs):
instructions = InstructionSet()
for irargs in zip(*rargs):
instructions.add(func(self, *params, *irargs),
[i for i in irargs if isinstance(i[0], QuantumRegister)],
[i for i in irargs if isinstance(i[0], ClassicalRegister)])
return instructions
else:
raise QiskitError('empty control or target argument')
return func(self, *params, *rargs)
return wrapper
|
def _op_expand(n_bits, func=None, broadcastable=None):
"""Decorator for expanding an operation across a whole register or register subset.
Args:
n_bits (int): the number of register bit arguments the decorated function takes
func (function): used for decorators with keyword args
broadcastable (list(bool)): list of bool for which register args can be
broadcast from 1 bit to the max size of the rest of the args. Defaults
to all True if not specified.
Return:
type: partial function object
"""
if func is None:
return functools.partial(_op_expand, n_bits, broadcastable=broadcastable)
@functools.wraps(func)
def wrapper(self, *args):
params = args[0:-n_bits] if len(args) > n_bits else tuple()
rargs = args[-n_bits:]
if broadcastable is None:
blist = [True] * len(rargs)
else:
blist = broadcastable
if not all([_is_bit(arg) for arg in rargs]):
rarg_size = [1] * n_bits
for iarg, arg in enumerate(rargs):
if isinstance(arg, Register):
rarg_size[iarg] = len(arg)
elif isinstance(arg, list) and all([_is_bit(bit) for bit in arg]):
rarg_size[iarg] = len(arg)
elif _is_bit(arg):
rarg_size[iarg] = 1
else:
raise QiskitError('operation arguments must be qubits/cbits')
broadcast_size = max(rarg_size)
expanded_rargs = []
for arg, broadcast in zip(rargs, blist):
if isinstance(arg, Register):
arg = [(arg, i) for i in range(len(arg))]
elif isinstance(arg, tuple):
arg = [arg]
# now we should have a list of qubits
if isinstance(arg, list) and len(arg) == 1 and broadcast:
arg = arg * broadcast_size
if len(arg) != broadcast_size:
raise QiskitError('register size error')
expanded_rargs.append(arg)
rargs = expanded_rargs
if all([isinstance(arg, list) for arg in rargs]):
if all(rargs):
instructions = InstructionSet()
for irargs in zip(*rargs):
instructions.add(func(self, *params, *irargs),
[i for i in irargs if isinstance(i[0], QuantumRegister)],
[i for i in irargs if isinstance(i[0], ClassicalRegister)])
return instructions
else:
raise QiskitError('empty control or target argument')
return func(self, *params, *rargs)
return wrapper
|
[
"Decorator",
"for",
"expanding",
"an",
"operation",
"across",
"a",
"whole",
"register",
"or",
"register",
"subset",
".",
"Args",
":",
"n_bits",
"(",
"int",
")",
":",
"the",
"number",
"of",
"register",
"bit",
"arguments",
"the",
"decorated",
"function",
"takes",
"func",
"(",
"function",
")",
":",
"used",
"for",
"decorators",
"with",
"keyword",
"args",
"broadcastable",
"(",
"list",
"(",
"bool",
"))",
":",
"list",
"of",
"bool",
"for",
"which",
"register",
"args",
"can",
"be",
"broadcast",
"from",
"1",
"bit",
"to",
"the",
"max",
"size",
"of",
"the",
"rest",
"of",
"the",
"args",
".",
"Defaults",
"to",
"all",
"True",
"if",
"not",
"specified",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/decorators.py#L76-L138
|
[
"def",
"_op_expand",
"(",
"n_bits",
",",
"func",
"=",
"None",
",",
"broadcastable",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"functools",
".",
"partial",
"(",
"_op_expand",
",",
"n_bits",
",",
"broadcastable",
"=",
"broadcastable",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"args",
"[",
"0",
":",
"-",
"n_bits",
"]",
"if",
"len",
"(",
"args",
")",
">",
"n_bits",
"else",
"tuple",
"(",
")",
"rargs",
"=",
"args",
"[",
"-",
"n_bits",
":",
"]",
"if",
"broadcastable",
"is",
"None",
":",
"blist",
"=",
"[",
"True",
"]",
"*",
"len",
"(",
"rargs",
")",
"else",
":",
"blist",
"=",
"broadcastable",
"if",
"not",
"all",
"(",
"[",
"_is_bit",
"(",
"arg",
")",
"for",
"arg",
"in",
"rargs",
"]",
")",
":",
"rarg_size",
"=",
"[",
"1",
"]",
"*",
"n_bits",
"for",
"iarg",
",",
"arg",
"in",
"enumerate",
"(",
"rargs",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Register",
")",
":",
"rarg_size",
"[",
"iarg",
"]",
"=",
"len",
"(",
"arg",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"list",
")",
"and",
"all",
"(",
"[",
"_is_bit",
"(",
"bit",
")",
"for",
"bit",
"in",
"arg",
"]",
")",
":",
"rarg_size",
"[",
"iarg",
"]",
"=",
"len",
"(",
"arg",
")",
"elif",
"_is_bit",
"(",
"arg",
")",
":",
"rarg_size",
"[",
"iarg",
"]",
"=",
"1",
"else",
":",
"raise",
"QiskitError",
"(",
"'operation arguments must be qubits/cbits'",
")",
"broadcast_size",
"=",
"max",
"(",
"rarg_size",
")",
"expanded_rargs",
"=",
"[",
"]",
"for",
"arg",
",",
"broadcast",
"in",
"zip",
"(",
"rargs",
",",
"blist",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Register",
")",
":",
"arg",
"=",
"[",
"(",
"arg",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arg",
")",
")",
"]",
"elif",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
":",
"arg",
"=",
"[",
"arg",
"]",
"# now we should have a list of qubits",
"if",
"isinstance",
"(",
"arg",
",",
"list",
")",
"and",
"len",
"(",
"arg",
")",
"==",
"1",
"and",
"broadcast",
":",
"arg",
"=",
"arg",
"*",
"broadcast_size",
"if",
"len",
"(",
"arg",
")",
"!=",
"broadcast_size",
":",
"raise",
"QiskitError",
"(",
"'register size error'",
")",
"expanded_rargs",
".",
"append",
"(",
"arg",
")",
"rargs",
"=",
"expanded_rargs",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"arg",
",",
"list",
")",
"for",
"arg",
"in",
"rargs",
"]",
")",
":",
"if",
"all",
"(",
"rargs",
")",
":",
"instructions",
"=",
"InstructionSet",
"(",
")",
"for",
"irargs",
"in",
"zip",
"(",
"*",
"rargs",
")",
":",
"instructions",
".",
"add",
"(",
"func",
"(",
"self",
",",
"*",
"params",
",",
"*",
"irargs",
")",
",",
"[",
"i",
"for",
"i",
"in",
"irargs",
"if",
"isinstance",
"(",
"i",
"[",
"0",
"]",
",",
"QuantumRegister",
")",
"]",
",",
"[",
"i",
"for",
"i",
"in",
"irargs",
"if",
"isinstance",
"(",
"i",
"[",
"0",
"]",
",",
"ClassicalRegister",
")",
"]",
")",
"return",
"instructions",
"else",
":",
"raise",
"QiskitError",
"(",
"'empty control or target argument'",
")",
"return",
"func",
"(",
"self",
",",
"*",
"params",
",",
"*",
"rargs",
")",
"return",
"wrapper"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
U1Gate.to_matrix
|
Return a Numpy.array for the U3 gate.
|
qiskit/extensions/standard/u1.py
|
def to_matrix(self):
"""Return a Numpy.array for the U3 gate."""
lam = self.params[0]
lam = float(lam)
return numpy.array([[1, 0], [0, numpy.exp(1j * lam)]], dtype=complex)
|
def to_matrix(self):
"""Return a Numpy.array for the U3 gate."""
lam = self.params[0]
lam = float(lam)
return numpy.array([[1, 0], [0, numpy.exp(1j * lam)]], dtype=complex)
|
[
"Return",
"a",
"Numpy",
".",
"array",
"for",
"the",
"U3",
"gate",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/u1.py#L43-L47
|
[
"def",
"to_matrix",
"(",
"self",
")",
":",
"lam",
"=",
"self",
".",
"params",
"[",
"0",
"]",
"lam",
"=",
"float",
"(",
"lam",
")",
"return",
"numpy",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
"]",
",",
"[",
"0",
",",
"numpy",
".",
"exp",
"(",
"1j",
"*",
"lam",
")",
"]",
"]",
",",
"dtype",
"=",
"complex",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TrivialLayout.run
|
Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
|
qiskit/transpiler/passes/mapping/trivial_layout.py
|
def run(self, dag):
"""
Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_dag_qubits > self.coupling_map.size():
raise TranspilerError('Number of qubits greater than device.')
self.property_set['layout'] = Layout.generate_trivial_layout(*dag.qregs.values())
|
def run(self, dag):
"""
Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_dag_qubits > self.coupling_map.size():
raise TranspilerError('Number of qubits greater than device.')
self.property_set['layout'] = Layout.generate_trivial_layout(*dag.qregs.values())
|
[
"Pick",
"a",
"layout",
"by",
"assigning",
"n",
"circuit",
"qubits",
"to",
"device",
"qubits",
"0",
"..",
"n",
"-",
"1",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/trivial_layout.py#L40-L53
|
[
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"num_dag_qubits",
"=",
"sum",
"(",
"[",
"qreg",
".",
"size",
"for",
"qreg",
"in",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
"]",
")",
"if",
"num_dag_qubits",
">",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
":",
"raise",
"TranspilerError",
"(",
"'Number of qubits greater than device.'",
")",
"self",
".",
"property_set",
"[",
"'layout'",
"]",
"=",
"Layout",
".",
"generate_trivial_layout",
"(",
"*",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Interval.has_overlap
|
Check if self has overlap with `interval`.
Args:
interval: interval to be examined
Returns:
bool: True if self has overlap with `interval` otherwise False
|
qiskit/pulse/timeslots.py
|
def has_overlap(self, interval: 'Interval') -> bool:
"""Check if self has overlap with `interval`.
Args:
interval: interval to be examined
Returns:
bool: True if self has overlap with `interval` otherwise False
"""
if self.begin < interval.end and interval.begin < self.end:
return True
return False
|
def has_overlap(self, interval: 'Interval') -> bool:
"""Check if self has overlap with `interval`.
Args:
interval: interval to be examined
Returns:
bool: True if self has overlap with `interval` otherwise False
"""
if self.begin < interval.end and interval.begin < self.end:
return True
return False
|
[
"Check",
"if",
"self",
"has",
"overlap",
"with",
"interval",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L59-L70
|
[
"def",
"has_overlap",
"(",
"self",
",",
"interval",
":",
"'Interval'",
")",
"->",
"bool",
":",
"if",
"self",
".",
"begin",
"<",
"interval",
".",
"end",
"and",
"interval",
".",
"begin",
"<",
"self",
".",
"end",
":",
"return",
"True",
"return",
"False"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Interval.shift
|
Return a new interval shifted by `time` from self
Args:
time: time to be shifted
Returns:
Interval: interval shifted by `time`
|
qiskit/pulse/timeslots.py
|
def shift(self, time: int) -> 'Interval':
"""Return a new interval shifted by `time` from self
Args:
time: time to be shifted
Returns:
Interval: interval shifted by `time`
"""
return Interval(self._begin + time, self._end + time)
|
def shift(self, time: int) -> 'Interval':
"""Return a new interval shifted by `time` from self
Args:
time: time to be shifted
Returns:
Interval: interval shifted by `time`
"""
return Interval(self._begin + time, self._end + time)
|
[
"Return",
"a",
"new",
"interval",
"shifted",
"by",
"time",
"from",
"self"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L72-L81
|
[
"def",
"shift",
"(",
"self",
",",
"time",
":",
"int",
")",
"->",
"'Interval'",
":",
"return",
"Interval",
"(",
"self",
".",
"_begin",
"+",
"time",
",",
"self",
".",
"_end",
"+",
"time",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Timeslot.shift
|
Return a new Timeslot shifted by `time`.
Args:
time: time to be shifted
|
qiskit/pulse/timeslots.py
|
def shift(self, time: int) -> 'Timeslot':
"""Return a new Timeslot shifted by `time`.
Args:
time: time to be shifted
"""
return Timeslot(self.interval.shift(time), self.channel)
|
def shift(self, time: int) -> 'Timeslot':
"""Return a new Timeslot shifted by `time`.
Args:
time: time to be shifted
"""
return Timeslot(self.interval.shift(time), self.channel)
|
[
"Return",
"a",
"new",
"Timeslot",
"shifted",
"by",
"time",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L114-L120
|
[
"def",
"shift",
"(",
"self",
",",
"time",
":",
"int",
")",
"->",
"'Timeslot'",
":",
"return",
"Timeslot",
"(",
"self",
".",
"interval",
".",
"shift",
"(",
"time",
")",
",",
"self",
".",
"channel",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TimeslotCollection.ch_start_time
|
Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time.
|
qiskit/pulse/timeslots.py
|
def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return min((interval.begin for interval in intervals))
return 0
|
def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return min((interval.begin for interval in intervals))
return 0
|
[
"Return",
"earliest",
"start",
"time",
"in",
"this",
"collection",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L179-L189
|
[
"def",
"ch_start_time",
"(",
"self",
",",
"*",
"channels",
":",
"List",
"[",
"Channel",
"]",
")",
"->",
"int",
":",
"intervals",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"(",
"self",
".",
"_table",
"[",
"chan",
"]",
"for",
"chan",
"in",
"channels",
"if",
"chan",
"in",
"self",
".",
"_table",
")",
")",
")",
"if",
"intervals",
":",
"return",
"min",
"(",
"(",
"interval",
".",
"begin",
"for",
"interval",
"in",
"intervals",
")",
")",
"return",
"0"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TimeslotCollection.ch_stop_time
|
Return maximum time of timeslots over all channels.
Args:
*channels: Channels over which to obtain stop time.
|
qiskit/pulse/timeslots.py
|
def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum time of timeslots over all channels.
Args:
*channels: Channels over which to obtain stop time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return max((interval.end for interval in intervals))
return 0
|
def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum time of timeslots over all channels.
Args:
*channels: Channels over which to obtain stop time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
if chan in self._table)))
if intervals:
return max((interval.end for interval in intervals))
return 0
|
[
"Return",
"maximum",
"time",
"of",
"timeslots",
"over",
"all",
"channels",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L191-L201
|
[
"def",
"ch_stop_time",
"(",
"self",
",",
"*",
"channels",
":",
"List",
"[",
"Channel",
"]",
")",
"->",
"int",
":",
"intervals",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"(",
"self",
".",
"_table",
"[",
"chan",
"]",
"for",
"chan",
"in",
"channels",
"if",
"chan",
"in",
"self",
".",
"_table",
")",
")",
")",
"if",
"intervals",
":",
"return",
"max",
"(",
"(",
"interval",
".",
"end",
"for",
"interval",
"in",
"intervals",
")",
")",
"return",
"0"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TimeslotCollection.is_mergeable_with
|
Return if self is mergeable with `timeslots`.
Args:
timeslots: TimeslotCollection to be checked
|
qiskit/pulse/timeslots.py
|
def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool:
"""Return if self is mergeable with `timeslots`.
Args:
timeslots: TimeslotCollection to be checked
"""
for slot in timeslots.timeslots:
for interval in self._table[slot.channel]:
if slot.interval.has_overlap(interval):
return False
return True
|
def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool:
"""Return if self is mergeable with `timeslots`.
Args:
timeslots: TimeslotCollection to be checked
"""
for slot in timeslots.timeslots:
for interval in self._table[slot.channel]:
if slot.interval.has_overlap(interval):
return False
return True
|
[
"Return",
"if",
"self",
"is",
"mergeable",
"with",
"timeslots",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L211-L221
|
[
"def",
"is_mergeable_with",
"(",
"self",
",",
"timeslots",
":",
"'TimeslotCollection'",
")",
"->",
"bool",
":",
"for",
"slot",
"in",
"timeslots",
".",
"timeslots",
":",
"for",
"interval",
"in",
"self",
".",
"_table",
"[",
"slot",
".",
"channel",
"]",
":",
"if",
"slot",
".",
"interval",
".",
"has_overlap",
"(",
"interval",
")",
":",
"return",
"False",
"return",
"True"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TimeslotCollection.merged
|
Return a new TimeslotCollection merged with a specified `timeslots`
Args:
timeslots: TimeslotCollection to be merged
|
qiskit/pulse/timeslots.py
|
def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection':
"""Return a new TimeslotCollection merged with a specified `timeslots`
Args:
timeslots: TimeslotCollection to be merged
"""
slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots]
slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots])
return TimeslotCollection(*slots)
|
def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection':
"""Return a new TimeslotCollection merged with a specified `timeslots`
Args:
timeslots: TimeslotCollection to be merged
"""
slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots]
slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots])
return TimeslotCollection(*slots)
|
[
"Return",
"a",
"new",
"TimeslotCollection",
"merged",
"with",
"a",
"specified",
"timeslots"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L223-L231
|
[
"def",
"merged",
"(",
"self",
",",
"timeslots",
":",
"'TimeslotCollection'",
")",
"->",
"'TimeslotCollection'",
":",
"slots",
"=",
"[",
"Timeslot",
"(",
"slot",
".",
"interval",
",",
"slot",
".",
"channel",
")",
"for",
"slot",
"in",
"self",
".",
"timeslots",
"]",
"slots",
".",
"extend",
"(",
"[",
"Timeslot",
"(",
"slot",
".",
"interval",
",",
"slot",
".",
"channel",
")",
"for",
"slot",
"in",
"timeslots",
".",
"timeslots",
"]",
")",
"return",
"TimeslotCollection",
"(",
"*",
"slots",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
TimeslotCollection.shift
|
Return a new TimeslotCollection shifted by `time`.
Args:
time: time to be shifted by
|
qiskit/pulse/timeslots.py
|
def shift(self, time: int) -> 'TimeslotCollection':
"""Return a new TimeslotCollection shifted by `time`.
Args:
time: time to be shifted by
"""
slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots]
return TimeslotCollection(*slots)
|
def shift(self, time: int) -> 'TimeslotCollection':
"""Return a new TimeslotCollection shifted by `time`.
Args:
time: time to be shifted by
"""
slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots]
return TimeslotCollection(*slots)
|
[
"Return",
"a",
"new",
"TimeslotCollection",
"shifted",
"by",
"time",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L233-L240
|
[
"def",
"shift",
"(",
"self",
",",
"time",
":",
"int",
")",
"->",
"'TimeslotCollection'",
":",
"slots",
"=",
"[",
"Timeslot",
"(",
"slot",
".",
"interval",
".",
"shift",
"(",
"time",
")",
",",
"slot",
".",
"channel",
")",
"for",
"slot",
"in",
"self",
".",
"timeslots",
"]",
"return",
"TimeslotCollection",
"(",
"*",
"slots",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
External.real
|
Return the correspond floating point number.
|
qiskit/qasm/node/external.py
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
op = self.children[0].name
expr = self.children[1]
dispatch = {
'sin': sympy.sin,
'cos': sympy.cos,
'tan': sympy.tan,
'asin': sympy.asin,
'acos': sympy.acos,
'atan': sympy.atan,
'exp': sympy.exp,
'ln': sympy.log,
'sqrt': sympy.sqrt
}
if op in dispatch:
arg = expr.real(nested_scope)
return dispatch[op](arg)
else:
raise NodeException("internal error: undefined external")
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
op = self.children[0].name
expr = self.children[1]
dispatch = {
'sin': sympy.sin,
'cos': sympy.cos,
'tan': sympy.tan,
'asin': sympy.asin,
'acos': sympy.acos,
'atan': sympy.atan,
'exp': sympy.exp,
'ln': sympy.log,
'sqrt': sympy.sqrt
}
if op in dispatch:
arg = expr.real(nested_scope)
return dispatch[op](arg)
else:
raise NodeException("internal error: undefined external")
|
[
"Return",
"the",
"correspond",
"floating",
"point",
"number",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/external.py#L39-L58
|
[
"def",
"real",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"op",
"=",
"self",
".",
"children",
"[",
"0",
"]",
".",
"name",
"expr",
"=",
"self",
".",
"children",
"[",
"1",
"]",
"dispatch",
"=",
"{",
"'sin'",
":",
"sympy",
".",
"sin",
",",
"'cos'",
":",
"sympy",
".",
"cos",
",",
"'tan'",
":",
"sympy",
".",
"tan",
",",
"'asin'",
":",
"sympy",
".",
"asin",
",",
"'acos'",
":",
"sympy",
".",
"acos",
",",
"'atan'",
":",
"sympy",
".",
"atan",
",",
"'exp'",
":",
"sympy",
".",
"exp",
",",
"'ln'",
":",
"sympy",
".",
"log",
",",
"'sqrt'",
":",
"sympy",
".",
"sqrt",
"}",
"if",
"op",
"in",
"dispatch",
":",
"arg",
"=",
"expr",
".",
"real",
"(",
"nested_scope",
")",
"return",
"dispatch",
"[",
"op",
"]",
"(",
"arg",
")",
"else",
":",
"raise",
"NodeException",
"(",
"\"internal error: undefined external\"",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
CIFailureReporter.report
|
Report on GitHub that the specified branch is failing to build at
the specified commit. The method will open an issue indicating that
the branch is failing. If there is an issue already open, it will add a
comment avoiding to report twice about the same failure.
Args:
branch (str): branch name to report about.
commit (str): commit hash at which the build fails.
infourl (str): URL with extra info about the failure such as the
build logs.
|
tools/report_ci_failure.py
|
def report(self, branch, commit, infourl=None):
"""Report on GitHub that the specified branch is failing to build at
the specified commit. The method will open an issue indicating that
the branch is failing. If there is an issue already open, it will add a
comment avoiding to report twice about the same failure.
Args:
branch (str): branch name to report about.
commit (str): commit hash at which the build fails.
infourl (str): URL with extra info about the failure such as the
build logs.
"""
issue_number = self._get_report_issue_number()
if issue_number:
self._report_as_comment(issue_number, branch, commit, infourl)
else:
self._report_as_issue(branch, commit, infourl)
|
def report(self, branch, commit, infourl=None):
"""Report on GitHub that the specified branch is failing to build at
the specified commit. The method will open an issue indicating that
the branch is failing. If there is an issue already open, it will add a
comment avoiding to report twice about the same failure.
Args:
branch (str): branch name to report about.
commit (str): commit hash at which the build fails.
infourl (str): URL with extra info about the failure such as the
build logs.
"""
issue_number = self._get_report_issue_number()
if issue_number:
self._report_as_comment(issue_number, branch, commit, infourl)
else:
self._report_as_issue(branch, commit, infourl)
|
[
"Report",
"on",
"GitHub",
"that",
"the",
"specified",
"branch",
"is",
"failing",
"to",
"build",
"at",
"the",
"specified",
"commit",
".",
"The",
"method",
"will",
"open",
"an",
"issue",
"indicating",
"that",
"the",
"branch",
"is",
"failing",
".",
"If",
"there",
"is",
"an",
"issue",
"already",
"open",
"it",
"will",
"add",
"a",
"comment",
"avoiding",
"to",
"report",
"twice",
"about",
"the",
"same",
"failure",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/tools/report_ci_failure.py#L33-L49
|
[
"def",
"report",
"(",
"self",
",",
"branch",
",",
"commit",
",",
"infourl",
"=",
"None",
")",
":",
"issue_number",
"=",
"self",
".",
"_get_report_issue_number",
"(",
")",
"if",
"issue_number",
":",
"self",
".",
"_report_as_comment",
"(",
"issue_number",
",",
"branch",
",",
"commit",
",",
"infourl",
")",
"else",
":",
"self",
".",
"_report_as_issue",
"(",
"branch",
",",
"commit",
",",
"infourl",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
process_data
|
Sort rho data
|
qiskit/visualization/interactive/iplot_paulivec.py
|
def process_data(rho):
""" Sort rho data """
result = dict()
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
for position, label in enumerate(labels):
result[label] = values[position]
return result
|
def process_data(rho):
""" Sort rho data """
result = dict()
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
for position, label in enumerate(labels):
result[label] = values[position]
return result
|
[
"Sort",
"rho",
"data"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_paulivec.py#L25-L36
|
[
"def",
"process_data",
"(",
"rho",
")",
":",
"result",
"=",
"dict",
"(",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"labels",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"to_label",
"(",
")",
",",
"pauli_group",
"(",
"num",
")",
")",
")",
"values",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"np",
".",
"real",
"(",
"np",
".",
"trace",
"(",
"np",
".",
"dot",
"(",
"x",
".",
"to_matrix",
"(",
")",
",",
"rho",
")",
")",
")",
",",
"pauli_group",
"(",
"num",
")",
")",
")",
"for",
"position",
",",
"label",
"in",
"enumerate",
"(",
"labels",
")",
":",
"result",
"[",
"label",
"]",
"=",
"values",
"[",
"position",
"]",
"return",
"result"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
iplot_state_paulivec
|
Create a paulivec representation.
Graphical representation of the input array.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
slider (bool): activate slider
show_legend (bool): show legend of graph content
|
qiskit/visualization/interactive/iplot_paulivec.py
|
def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):
""" Create a paulivec representation.
Graphical representation of the input array.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
slider (bool): activate slider
show_legend (bool): show legend of graph content
"""
# HTML
html_template = Template("""
<p>
<div id="paulivec_$divNumber"></div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
qVisualizations.plotState("paulivec_$divNumber",
"paulivec",
$executions,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
# set default figure size if none given
if figsize is None:
figsize = (7, 5)
options = {'width': figsize[0], 'height': figsize[1],
'slider': int(slider), 'show_legend': int(show_legend)}
# Process data and execute
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
data_to_plot = []
rho_data = process_data(rho)
data_to_plot.append(dict(
data=rho_data
))
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'divNumber': div_number,
'executions': data_to_plot,
'options': options
})
display(HTML(html + javascript))
|
def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):
""" Create a paulivec representation.
Graphical representation of the input array.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
slider (bool): activate slider
show_legend (bool): show legend of graph content
"""
# HTML
html_template = Template("""
<p>
<div id="paulivec_$divNumber"></div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
qVisualizations.plotState("paulivec_$divNumber",
"paulivec",
$executions,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
# set default figure size if none given
if figsize is None:
figsize = (7, 5)
options = {'width': figsize[0], 'height': figsize[1],
'slider': int(slider), 'show_legend': int(show_legend)}
# Process data and execute
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
data_to_plot = []
rho_data = process_data(rho)
data_to_plot.append(dict(
data=rho_data
))
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'divNumber': div_number,
'executions': data_to_plot,
'options': options
})
display(HTML(html + javascript))
|
[
"Create",
"a",
"paulivec",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_paulivec.py#L39-L103
|
[
"def",
"iplot_state_paulivec",
"(",
"rho",
",",
"figsize",
"=",
"None",
",",
"slider",
"=",
"False",
",",
"show_legend",
"=",
"False",
")",
":",
"# HTML",
"html_template",
"=",
"Template",
"(",
"\"\"\"\n <p>\n <div id=\"paulivec_$divNumber\"></div>\n </p>\n \"\"\"",
")",
"# JavaScript",
"javascript_template",
"=",
"Template",
"(",
"\"\"\"\n <script>\n requirejs.config({\n paths: {\n qVisualization: \"https://qvisualization.mybluemix.net/q-visualizations\"\n }\n });\n\n require([\"qVisualization\"], function(qVisualizations) {\n qVisualizations.plotState(\"paulivec_$divNumber\",\n \"paulivec\",\n $executions,\n $options);\n });\n </script>\n \"\"\"",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"# set default figure size if none given",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"7",
",",
"5",
")",
"options",
"=",
"{",
"'width'",
":",
"figsize",
"[",
"0",
"]",
",",
"'height'",
":",
"figsize",
"[",
"1",
"]",
",",
"'slider'",
":",
"int",
"(",
"slider",
")",
",",
"'show_legend'",
":",
"int",
"(",
"show_legend",
")",
"}",
"# Process data and execute",
"div_number",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
"div_number",
"=",
"re",
".",
"sub",
"(",
"'[.]'",
",",
"''",
",",
"div_number",
")",
"data_to_plot",
"=",
"[",
"]",
"rho_data",
"=",
"process_data",
"(",
"rho",
")",
"data_to_plot",
".",
"append",
"(",
"dict",
"(",
"data",
"=",
"rho_data",
")",
")",
"html",
"=",
"html_template",
".",
"substitute",
"(",
"{",
"'divNumber'",
":",
"div_number",
"}",
")",
"javascript",
"=",
"javascript_template",
".",
"substitute",
"(",
"{",
"'divNumber'",
":",
"div_number",
",",
"'executions'",
":",
"data_to_plot",
",",
"'options'",
":",
"options",
"}",
")",
"display",
"(",
"HTML",
"(",
"html",
"+",
"javascript",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
iplot_state
|
Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in pixels.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
|
qiskit/visualization/interactive/iplot_state.py
|
def iplot_state(quantum_state, method='city', figsize=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in pixels.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
warnings.warn("iplot_state is deprecated, and will be removed in \
the 0.9 release. Use the iplot_state_ * functions \
instead.",
DeprecationWarning)
rho = _validate_input_state(quantum_state)
if method == "city":
iplot_state_city(rho, figsize=figsize)
elif method == "paulivec":
iplot_state_paulivec(rho, figsize=figsize)
elif method == "qsphere":
iplot_state_qsphere(rho, figsize=figsize)
elif method == "bloch":
iplot_bloch_multivector(rho, figsize=figsize)
elif method == "hinton":
iplot_state_hinton(rho, figsize=figsize)
else:
raise VisualizationError('Invalid plot state method.')
|
def iplot_state(quantum_state, method='city', figsize=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in pixels.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
warnings.warn("iplot_state is deprecated, and will be removed in \
the 0.9 release. Use the iplot_state_ * functions \
instead.",
DeprecationWarning)
rho = _validate_input_state(quantum_state)
if method == "city":
iplot_state_city(rho, figsize=figsize)
elif method == "paulivec":
iplot_state_paulivec(rho, figsize=figsize)
elif method == "qsphere":
iplot_state_qsphere(rho, figsize=figsize)
elif method == "bloch":
iplot_bloch_multivector(rho, figsize=figsize)
elif method == "hinton":
iplot_state_hinton(rho, figsize=figsize)
else:
raise VisualizationError('Invalid plot state method.')
|
[
"Plot",
"the",
"quantum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_state.py#L21-L50
|
[
"def",
"iplot_state",
"(",
"quantum_state",
",",
"method",
"=",
"'city'",
",",
"figsize",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"iplot_state is deprecated, and will be removed in \\\n the 0.9 release. Use the iplot_state_ * functions \\\n instead.\"",
",",
"DeprecationWarning",
")",
"rho",
"=",
"_validate_input_state",
"(",
"quantum_state",
")",
"if",
"method",
"==",
"\"city\"",
":",
"iplot_state_city",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"paulivec\"",
":",
"iplot_state_paulivec",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"qsphere\"",
":",
"iplot_state_qsphere",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"bloch\"",
":",
"iplot_bloch_multivector",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"hinton\"",
":",
"iplot_state_hinton",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"else",
":",
"raise",
"VisualizationError",
"(",
"'Invalid plot state method.'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
rzz
|
Apply RZZ to circuit.
|
qiskit/extensions/standard/rzz.py
|
def rzz(self, theta, qubit1, qubit2):
"""Apply RZZ to circuit."""
return self.append(RZZGate(theta), [qubit1, qubit2], [])
|
def rzz(self, theta, qubit1, qubit2):
"""Apply RZZ to circuit."""
return self.append(RZZGate(theta), [qubit1, qubit2], [])
|
[
"Apply",
"RZZ",
"to",
"circuit",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/rzz.py#L49-L51
|
[
"def",
"rzz",
"(",
"self",
",",
"theta",
",",
"qubit1",
",",
"qubit2",
")",
":",
"return",
"self",
".",
"append",
"(",
"RZZGate",
"(",
"theta",
")",
",",
"[",
"qubit1",
",",
"qubit2",
"]",
",",
"[",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
cswap
|
Apply Fredkin to circuit.
|
qiskit/extensions/standard/cswap.py
|
def cswap(self, ctl, tgt1, tgt2):
"""Apply Fredkin to circuit."""
return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])
|
def cswap(self, ctl, tgt1, tgt2):
"""Apply Fredkin to circuit."""
return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])
|
[
"Apply",
"Fredkin",
"to",
"circuit",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/cswap.py#L53-L55
|
[
"def",
"cswap",
"(",
"self",
",",
"ctl",
",",
"tgt1",
",",
"tgt2",
")",
":",
"return",
"self",
".",
"append",
"(",
"FredkinGate",
"(",
")",
",",
"[",
"ctl",
",",
"tgt1",
",",
"tgt2",
"]",
",",
"[",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
FredkinGate._define
|
gate cswap a,b,c
{ cx c,b;
ccx a,b,c;
cx c,b;
}
|
qiskit/extensions/standard/cswap.py
|
def _define(self):
"""
gate cswap a,b,c
{ cx c,b;
ccx a,b,c;
cx c,b;
}
"""
definition = []
q = QuantumRegister(3, "q")
rule = [
(CnotGate(), [q[2], q[1]], []),
(ToffoliGate(), [q[0], q[1], q[2]], []),
(CnotGate(), [q[2], q[1]], [])
]
for inst in rule:
definition.append(inst)
self.definition = definition
|
def _define(self):
"""
gate cswap a,b,c
{ cx c,b;
ccx a,b,c;
cx c,b;
}
"""
definition = []
q = QuantumRegister(3, "q")
rule = [
(CnotGate(), [q[2], q[1]], []),
(ToffoliGate(), [q[0], q[1], q[2]], []),
(CnotGate(), [q[2], q[1]], [])
]
for inst in rule:
definition.append(inst)
self.definition = definition
|
[
"gate",
"cswap",
"a",
"b",
"c",
"{",
"cx",
"c",
"b",
";",
"ccx",
"a",
"b",
"c",
";",
"cx",
"c",
"b",
";",
"}"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/cswap.py#L27-L44
|
[
"def",
"_define",
"(",
"self",
")",
":",
"definition",
"=",
"[",
"]",
"q",
"=",
"QuantumRegister",
"(",
"3",
",",
"\"q\"",
")",
"rule",
"=",
"[",
"(",
"CnotGate",
"(",
")",
",",
"[",
"q",
"[",
"2",
"]",
",",
"q",
"[",
"1",
"]",
"]",
",",
"[",
"]",
")",
",",
"(",
"ToffoliGate",
"(",
")",
",",
"[",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
",",
"q",
"[",
"2",
"]",
"]",
",",
"[",
"]",
")",
",",
"(",
"CnotGate",
"(",
")",
",",
"[",
"q",
"[",
"2",
"]",
",",
"q",
"[",
"1",
"]",
"]",
",",
"[",
"]",
")",
"]",
"for",
"inst",
"in",
"rule",
":",
"definition",
".",
"append",
"(",
"inst",
")",
"self",
".",
"definition",
"=",
"definition"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout._initialize_backend_prop
|
Extract readout and CNOT errors and compute swap costs.
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def _initialize_backend_prop(self):
"""
Extract readout and CNOT errors and compute swap costs.
"""
backend_prop = self.backend_prop
for ginfo in backend_prop.gates:
if ginfo.gate == 'cx':
for item in ginfo.parameters:
if item.name == 'gate_error':
g_reliab = 1.0 - item.value
break
else:
g_reliab = 1.0
swap_reliab = -math.log(pow(g_reliab, 3))
self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab)
self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab)
self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab
self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1]))
idx = 0
for q in backend_prop.qubits:
for nduv in q:
if nduv.name == 'readout_error':
self.readout_errors[idx] = 1.0 - nduv.value
self.available_hw_qubits.append(idx)
idx += 1
for edge in self.cx_errors:
self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\
self.readout_errors[edge[1]]
self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\
floyd_warshall_predecessor_and_distance(self.swap_graph, weight='weight')
for i in swap_costs_temp:
self.swap_costs[i] = {}
for j in swap_costs_temp[i]:
if (i, j) in self.cx_errors:
self.swap_costs[i][j] = self.cx_errors[(i, j)]
elif (j, i) in self.cx_errors:
self.swap_costs[i][j] = self.cx_errors[(j, i)]
else:
best_reliab = 0.0
for n in self.swap_graph.neighbors(j):
if (n, j) in self.cx_errors:
reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)]
else:
reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)]
if reliab > best_reliab:
best_reliab = reliab
self.swap_costs[i][j] = best_reliab
|
def _initialize_backend_prop(self):
"""
Extract readout and CNOT errors and compute swap costs.
"""
backend_prop = self.backend_prop
for ginfo in backend_prop.gates:
if ginfo.gate == 'cx':
for item in ginfo.parameters:
if item.name == 'gate_error':
g_reliab = 1.0 - item.value
break
else:
g_reliab = 1.0
swap_reliab = -math.log(pow(g_reliab, 3))
self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab)
self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab)
self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab
self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1]))
idx = 0
for q in backend_prop.qubits:
for nduv in q:
if nduv.name == 'readout_error':
self.readout_errors[idx] = 1.0 - nduv.value
self.available_hw_qubits.append(idx)
idx += 1
for edge in self.cx_errors:
self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\
self.readout_errors[edge[1]]
self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\
floyd_warshall_predecessor_and_distance(self.swap_graph, weight='weight')
for i in swap_costs_temp:
self.swap_costs[i] = {}
for j in swap_costs_temp[i]:
if (i, j) in self.cx_errors:
self.swap_costs[i][j] = self.cx_errors[(i, j)]
elif (j, i) in self.cx_errors:
self.swap_costs[i][j] = self.cx_errors[(j, i)]
else:
best_reliab = 0.0
for n in self.swap_graph.neighbors(j):
if (n, j) in self.cx_errors:
reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)]
else:
reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)]
if reliab > best_reliab:
best_reliab = reliab
self.swap_costs[i][j] = best_reliab
|
[
"Extract",
"readout",
"and",
"CNOT",
"errors",
"and",
"compute",
"swap",
"costs",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L79-L125
|
[
"def",
"_initialize_backend_prop",
"(",
"self",
")",
":",
"backend_prop",
"=",
"self",
".",
"backend_prop",
"for",
"ginfo",
"in",
"backend_prop",
".",
"gates",
":",
"if",
"ginfo",
".",
"gate",
"==",
"'cx'",
":",
"for",
"item",
"in",
"ginfo",
".",
"parameters",
":",
"if",
"item",
".",
"name",
"==",
"'gate_error'",
":",
"g_reliab",
"=",
"1.0",
"-",
"item",
".",
"value",
"break",
"else",
":",
"g_reliab",
"=",
"1.0",
"swap_reliab",
"=",
"-",
"math",
".",
"log",
"(",
"pow",
"(",
"g_reliab",
",",
"3",
")",
")",
"self",
".",
"swap_graph",
".",
"add_edge",
"(",
"ginfo",
".",
"qubits",
"[",
"0",
"]",
",",
"ginfo",
".",
"qubits",
"[",
"1",
"]",
",",
"weight",
"=",
"swap_reliab",
")",
"self",
".",
"swap_graph",
".",
"add_edge",
"(",
"ginfo",
".",
"qubits",
"[",
"1",
"]",
",",
"ginfo",
".",
"qubits",
"[",
"0",
"]",
",",
"weight",
"=",
"swap_reliab",
")",
"self",
".",
"cx_errors",
"[",
"(",
"ginfo",
".",
"qubits",
"[",
"0",
"]",
",",
"ginfo",
".",
"qubits",
"[",
"1",
"]",
")",
"]",
"=",
"g_reliab",
"self",
".",
"gate_list",
".",
"append",
"(",
"(",
"ginfo",
".",
"qubits",
"[",
"0",
"]",
",",
"ginfo",
".",
"qubits",
"[",
"1",
"]",
")",
")",
"idx",
"=",
"0",
"for",
"q",
"in",
"backend_prop",
".",
"qubits",
":",
"for",
"nduv",
"in",
"q",
":",
"if",
"nduv",
".",
"name",
"==",
"'readout_error'",
":",
"self",
".",
"readout_errors",
"[",
"idx",
"]",
"=",
"1.0",
"-",
"nduv",
".",
"value",
"self",
".",
"available_hw_qubits",
".",
"append",
"(",
"idx",
")",
"idx",
"+=",
"1",
"for",
"edge",
"in",
"self",
".",
"cx_errors",
":",
"self",
".",
"gate_cost",
"[",
"edge",
"]",
"=",
"self",
".",
"cx_errors",
"[",
"edge",
"]",
"*",
"self",
".",
"readout_errors",
"[",
"edge",
"[",
"0",
"]",
"]",
"*",
"self",
".",
"readout_errors",
"[",
"edge",
"[",
"1",
"]",
"]",
"self",
".",
"swap_paths",
",",
"swap_costs_temp",
"=",
"nx",
".",
"algorithms",
".",
"shortest_paths",
".",
"dense",
".",
"floyd_warshall_predecessor_and_distance",
"(",
"self",
".",
"swap_graph",
",",
"weight",
"=",
"'weight'",
")",
"for",
"i",
"in",
"swap_costs_temp",
":",
"self",
".",
"swap_costs",
"[",
"i",
"]",
"=",
"{",
"}",
"for",
"j",
"in",
"swap_costs_temp",
"[",
"i",
"]",
":",
"if",
"(",
"i",
",",
"j",
")",
"in",
"self",
".",
"cx_errors",
":",
"self",
".",
"swap_costs",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"self",
".",
"cx_errors",
"[",
"(",
"i",
",",
"j",
")",
"]",
"elif",
"(",
"j",
",",
"i",
")",
"in",
"self",
".",
"cx_errors",
":",
"self",
".",
"swap_costs",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"self",
".",
"cx_errors",
"[",
"(",
"j",
",",
"i",
")",
"]",
"else",
":",
"best_reliab",
"=",
"0.0",
"for",
"n",
"in",
"self",
".",
"swap_graph",
".",
"neighbors",
"(",
"j",
")",
":",
"if",
"(",
"n",
",",
"j",
")",
"in",
"self",
".",
"cx_errors",
":",
"reliab",
"=",
"math",
".",
"exp",
"(",
"-",
"swap_costs_temp",
"[",
"i",
"]",
"[",
"n",
"]",
")",
"*",
"self",
".",
"cx_errors",
"[",
"(",
"n",
",",
"j",
")",
"]",
"else",
":",
"reliab",
"=",
"math",
".",
"exp",
"(",
"-",
"swap_costs_temp",
"[",
"i",
"]",
"[",
"n",
"]",
")",
"*",
"self",
".",
"cx_errors",
"[",
"(",
"j",
",",
"n",
")",
"]",
"if",
"reliab",
">",
"best_reliab",
":",
"best_reliab",
"=",
"reliab",
"self",
".",
"swap_costs",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"best_reliab"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout._create_program_graph
|
Program graph has virtual qubits as nodes.
Two nodes have an edge if the corresponding virtual qubits
participate in a 2-qubit gate. The edge is weighted by the
number of CNOTs between the pair.
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def _create_program_graph(self, dag):
"""
Program graph has virtual qubits as nodes.
Two nodes have an edge if the corresponding virtual qubits
participate in a 2-qubit gate. The edge is weighted by the
number of CNOTs between the pair.
"""
idx = 0
for q in dag.qubits():
self.qarg_to_id[q[0].name + str(q[1])] = idx
idx += 1
for gate in dag.twoQ_gates():
qid1 = self._qarg_to_id(gate.qargs[0])
qid2 = self._qarg_to_id(gate.qargs[1])
min_q = min(qid1, qid2)
max_q = max(qid1, qid2)
edge_weight = 1
if self.prog_graph.has_edge(min_q, max_q):
edge_weight = self.prog_graph[min_q][max_q]['weight'] + 1
self.prog_graph.add_edge(min_q, max_q, weight=edge_weight)
return idx
|
def _create_program_graph(self, dag):
"""
Program graph has virtual qubits as nodes.
Two nodes have an edge if the corresponding virtual qubits
participate in a 2-qubit gate. The edge is weighted by the
number of CNOTs between the pair.
"""
idx = 0
for q in dag.qubits():
self.qarg_to_id[q[0].name + str(q[1])] = idx
idx += 1
for gate in dag.twoQ_gates():
qid1 = self._qarg_to_id(gate.qargs[0])
qid2 = self._qarg_to_id(gate.qargs[1])
min_q = min(qid1, qid2)
max_q = max(qid1, qid2)
edge_weight = 1
if self.prog_graph.has_edge(min_q, max_q):
edge_weight = self.prog_graph[min_q][max_q]['weight'] + 1
self.prog_graph.add_edge(min_q, max_q, weight=edge_weight)
return idx
|
[
"Program",
"graph",
"has",
"virtual",
"qubits",
"as",
"nodes",
".",
"Two",
"nodes",
"have",
"an",
"edge",
"if",
"the",
"corresponding",
"virtual",
"qubits",
"participate",
"in",
"a",
"2",
"-",
"qubit",
"gate",
".",
"The",
"edge",
"is",
"weighted",
"by",
"the",
"number",
"of",
"CNOTs",
"between",
"the",
"pair",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L133-L153
|
[
"def",
"_create_program_graph",
"(",
"self",
",",
"dag",
")",
":",
"idx",
"=",
"0",
"for",
"q",
"in",
"dag",
".",
"qubits",
"(",
")",
":",
"self",
".",
"qarg_to_id",
"[",
"q",
"[",
"0",
"]",
".",
"name",
"+",
"str",
"(",
"q",
"[",
"1",
"]",
")",
"]",
"=",
"idx",
"idx",
"+=",
"1",
"for",
"gate",
"in",
"dag",
".",
"twoQ_gates",
"(",
")",
":",
"qid1",
"=",
"self",
".",
"_qarg_to_id",
"(",
"gate",
".",
"qargs",
"[",
"0",
"]",
")",
"qid2",
"=",
"self",
".",
"_qarg_to_id",
"(",
"gate",
".",
"qargs",
"[",
"1",
"]",
")",
"min_q",
"=",
"min",
"(",
"qid1",
",",
"qid2",
")",
"max_q",
"=",
"max",
"(",
"qid1",
",",
"qid2",
")",
"edge_weight",
"=",
"1",
"if",
"self",
".",
"prog_graph",
".",
"has_edge",
"(",
"min_q",
",",
"max_q",
")",
":",
"edge_weight",
"=",
"self",
".",
"prog_graph",
"[",
"min_q",
"]",
"[",
"max_q",
"]",
"[",
"'weight'",
"]",
"+",
"1",
"self",
".",
"prog_graph",
".",
"add_edge",
"(",
"min_q",
",",
"max_q",
",",
"weight",
"=",
"edge_weight",
")",
"return",
"idx"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout._select_next_edge
|
If there is an edge with one endpoint mapped, return it.
Else return in the first edge
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def _select_next_edge(self):
"""
If there is an edge with one endpoint mapped, return it.
Else return in the first edge
"""
for edge in self.pending_program_edges:
q1_mapped = edge[0] in self.prog2hw
q2_mapped = edge[1] in self.prog2hw
assert not (q1_mapped and q2_mapped)
if q1_mapped or q2_mapped:
return edge
return self.pending_program_edges[0]
|
def _select_next_edge(self):
"""
If there is an edge with one endpoint mapped, return it.
Else return in the first edge
"""
for edge in self.pending_program_edges:
q1_mapped = edge[0] in self.prog2hw
q2_mapped = edge[1] in self.prog2hw
assert not (q1_mapped and q2_mapped)
if q1_mapped or q2_mapped:
return edge
return self.pending_program_edges[0]
|
[
"If",
"there",
"is",
"an",
"edge",
"with",
"one",
"endpoint",
"mapped",
"return",
"it",
".",
"Else",
"return",
"in",
"the",
"first",
"edge"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L155-L166
|
[
"def",
"_select_next_edge",
"(",
"self",
")",
":",
"for",
"edge",
"in",
"self",
".",
"pending_program_edges",
":",
"q1_mapped",
"=",
"edge",
"[",
"0",
"]",
"in",
"self",
".",
"prog2hw",
"q2_mapped",
"=",
"edge",
"[",
"1",
"]",
"in",
"self",
".",
"prog2hw",
"assert",
"not",
"(",
"q1_mapped",
"and",
"q2_mapped",
")",
"if",
"q1_mapped",
"or",
"q2_mapped",
":",
"return",
"edge",
"return",
"self",
".",
"pending_program_edges",
"[",
"0",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout._select_best_remaining_cx
|
Select best remaining CNOT in the hardware for the next program edge.
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def _select_best_remaining_cx(self):
"""
Select best remaining CNOT in the hardware for the next program edge.
"""
candidates = []
for gate in self.gate_list:
chk1 = gate[0] in self.available_hw_qubits
chk2 = gate[1] in self.available_hw_qubits
if chk1 and chk2:
candidates.append(gate)
best_reliab = 0
best_item = None
for item in candidates:
if self.gate_cost[item] > best_reliab:
best_reliab = self.gate_cost[item]
best_item = item
return best_item
|
def _select_best_remaining_cx(self):
"""
Select best remaining CNOT in the hardware for the next program edge.
"""
candidates = []
for gate in self.gate_list:
chk1 = gate[0] in self.available_hw_qubits
chk2 = gate[1] in self.available_hw_qubits
if chk1 and chk2:
candidates.append(gate)
best_reliab = 0
best_item = None
for item in candidates:
if self.gate_cost[item] > best_reliab:
best_reliab = self.gate_cost[item]
best_item = item
return best_item
|
[
"Select",
"best",
"remaining",
"CNOT",
"in",
"the",
"hardware",
"for",
"the",
"next",
"program",
"edge",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L168-L184
|
[
"def",
"_select_best_remaining_cx",
"(",
"self",
")",
":",
"candidates",
"=",
"[",
"]",
"for",
"gate",
"in",
"self",
".",
"gate_list",
":",
"chk1",
"=",
"gate",
"[",
"0",
"]",
"in",
"self",
".",
"available_hw_qubits",
"chk2",
"=",
"gate",
"[",
"1",
"]",
"in",
"self",
".",
"available_hw_qubits",
"if",
"chk1",
"and",
"chk2",
":",
"candidates",
".",
"append",
"(",
"gate",
")",
"best_reliab",
"=",
"0",
"best_item",
"=",
"None",
"for",
"item",
"in",
"candidates",
":",
"if",
"self",
".",
"gate_cost",
"[",
"item",
"]",
">",
"best_reliab",
":",
"best_reliab",
"=",
"self",
".",
"gate_cost",
"[",
"item",
"]",
"best_item",
"=",
"item",
"return",
"best_item"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout._select_best_remaining_qubit
|
Select the best remaining hardware qubit for the next program qubit.
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def _select_best_remaining_qubit(self, prog_qubit):
"""
Select the best remaining hardware qubit for the next program qubit.
"""
reliab_store = {}
for hw_qubit in self.available_hw_qubits:
reliab = 1
for n in self.prog_graph.neighbors(prog_qubit):
if n in self.prog2hw:
reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]
reliab *= self.readout_errors[hw_qubit]
reliab_store[hw_qubit] = reliab
max_reliab = 0
best_hw_qubit = None
for hw_qubit in reliab_store:
if reliab_store[hw_qubit] > max_reliab:
max_reliab = reliab_store[hw_qubit]
best_hw_qubit = hw_qubit
return best_hw_qubit
|
def _select_best_remaining_qubit(self, prog_qubit):
"""
Select the best remaining hardware qubit for the next program qubit.
"""
reliab_store = {}
for hw_qubit in self.available_hw_qubits:
reliab = 1
for n in self.prog_graph.neighbors(prog_qubit):
if n in self.prog2hw:
reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]
reliab *= self.readout_errors[hw_qubit]
reliab_store[hw_qubit] = reliab
max_reliab = 0
best_hw_qubit = None
for hw_qubit in reliab_store:
if reliab_store[hw_qubit] > max_reliab:
max_reliab = reliab_store[hw_qubit]
best_hw_qubit = hw_qubit
return best_hw_qubit
|
[
"Select",
"the",
"best",
"remaining",
"hardware",
"qubit",
"for",
"the",
"next",
"program",
"qubit",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L186-L204
|
[
"def",
"_select_best_remaining_qubit",
"(",
"self",
",",
"prog_qubit",
")",
":",
"reliab_store",
"=",
"{",
"}",
"for",
"hw_qubit",
"in",
"self",
".",
"available_hw_qubits",
":",
"reliab",
"=",
"1",
"for",
"n",
"in",
"self",
".",
"prog_graph",
".",
"neighbors",
"(",
"prog_qubit",
")",
":",
"if",
"n",
"in",
"self",
".",
"prog2hw",
":",
"reliab",
"*=",
"self",
".",
"swap_costs",
"[",
"self",
".",
"prog2hw",
"[",
"n",
"]",
"]",
"[",
"hw_qubit",
"]",
"reliab",
"*=",
"self",
".",
"readout_errors",
"[",
"hw_qubit",
"]",
"reliab_store",
"[",
"hw_qubit",
"]",
"=",
"reliab",
"max_reliab",
"=",
"0",
"best_hw_qubit",
"=",
"None",
"for",
"hw_qubit",
"in",
"reliab_store",
":",
"if",
"reliab_store",
"[",
"hw_qubit",
"]",
">",
"max_reliab",
":",
"max_reliab",
"=",
"reliab_store",
"[",
"hw_qubit",
"]",
"best_hw_qubit",
"=",
"hw_qubit",
"return",
"best_hw_qubit"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
NoiseAdaptiveLayout.run
|
Main run method for the noise adaptive layout.
|
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
|
def run(self, dag):
"""Main run method for the noise adaptive layout."""
self._initialize_backend_prop()
num_qubits = self._create_program_graph(dag)
if num_qubits > len(self.swap_graph):
raise TranspilerError('Number of qubits greater than device.')
for end1, end2, _ in sorted(self.prog_graph.edges(data=True),
key=lambda x: x[2]['weight'], reverse=True):
self.pending_program_edges.append((end1, end2))
while self.pending_program_edges:
edge = self._select_next_edge()
q1_mapped = edge[0] in self.prog2hw
q2_mapped = edge[1] in self.prog2hw
if (not q1_mapped) and (not q2_mapped):
best_hw_edge = self._select_best_remaining_cx()
self.prog2hw[edge[0]] = best_hw_edge[0]
self.prog2hw[edge[1]] = best_hw_edge[1]
self.available_hw_qubits.remove(best_hw_edge[0])
self.available_hw_qubits.remove(best_hw_edge[1])
elif not q1_mapped:
best_hw_qubit = self._select_best_remaining_qubit(edge[0])
self.prog2hw[edge[0]] = best_hw_qubit
self.available_hw_qubits.remove(best_hw_qubit)
else:
best_hw_qubit = self._select_best_remaining_qubit(edge[1])
self.prog2hw[edge[1]] = best_hw_qubit
self.available_hw_qubits.remove(best_hw_qubit)
new_edges = [x for x in self.pending_program_edges
if not (x[0] in self.prog2hw and x[1] in self.prog2hw)]
self.pending_program_edges = new_edges
for qid in self.qarg_to_id.values():
if qid not in self.prog2hw:
self.prog2hw[qid] = self.available_hw_qubits[0]
self.available_hw_qubits.remove(self.prog2hw[qid])
layout = Layout()
for q in dag.qubits():
pid = self._qarg_to_id(q)
hwid = self.prog2hw[pid]
layout[(q[0], q[1])] = hwid
self.property_set['layout'] = layout
|
def run(self, dag):
"""Main run method for the noise adaptive layout."""
self._initialize_backend_prop()
num_qubits = self._create_program_graph(dag)
if num_qubits > len(self.swap_graph):
raise TranspilerError('Number of qubits greater than device.')
for end1, end2, _ in sorted(self.prog_graph.edges(data=True),
key=lambda x: x[2]['weight'], reverse=True):
self.pending_program_edges.append((end1, end2))
while self.pending_program_edges:
edge = self._select_next_edge()
q1_mapped = edge[0] in self.prog2hw
q2_mapped = edge[1] in self.prog2hw
if (not q1_mapped) and (not q2_mapped):
best_hw_edge = self._select_best_remaining_cx()
self.prog2hw[edge[0]] = best_hw_edge[0]
self.prog2hw[edge[1]] = best_hw_edge[1]
self.available_hw_qubits.remove(best_hw_edge[0])
self.available_hw_qubits.remove(best_hw_edge[1])
elif not q1_mapped:
best_hw_qubit = self._select_best_remaining_qubit(edge[0])
self.prog2hw[edge[0]] = best_hw_qubit
self.available_hw_qubits.remove(best_hw_qubit)
else:
best_hw_qubit = self._select_best_remaining_qubit(edge[1])
self.prog2hw[edge[1]] = best_hw_qubit
self.available_hw_qubits.remove(best_hw_qubit)
new_edges = [x for x in self.pending_program_edges
if not (x[0] in self.prog2hw and x[1] in self.prog2hw)]
self.pending_program_edges = new_edges
for qid in self.qarg_to_id.values():
if qid not in self.prog2hw:
self.prog2hw[qid] = self.available_hw_qubits[0]
self.available_hw_qubits.remove(self.prog2hw[qid])
layout = Layout()
for q in dag.qubits():
pid = self._qarg_to_id(q)
hwid = self.prog2hw[pid]
layout[(q[0], q[1])] = hwid
self.property_set['layout'] = layout
|
[
"Main",
"run",
"method",
"for",
"the",
"noise",
"adaptive",
"layout",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L206-L245
|
[
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"self",
".",
"_initialize_backend_prop",
"(",
")",
"num_qubits",
"=",
"self",
".",
"_create_program_graph",
"(",
"dag",
")",
"if",
"num_qubits",
">",
"len",
"(",
"self",
".",
"swap_graph",
")",
":",
"raise",
"TranspilerError",
"(",
"'Number of qubits greater than device.'",
")",
"for",
"end1",
",",
"end2",
",",
"_",
"in",
"sorted",
"(",
"self",
".",
"prog_graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"2",
"]",
"[",
"'weight'",
"]",
",",
"reverse",
"=",
"True",
")",
":",
"self",
".",
"pending_program_edges",
".",
"append",
"(",
"(",
"end1",
",",
"end2",
")",
")",
"while",
"self",
".",
"pending_program_edges",
":",
"edge",
"=",
"self",
".",
"_select_next_edge",
"(",
")",
"q1_mapped",
"=",
"edge",
"[",
"0",
"]",
"in",
"self",
".",
"prog2hw",
"q2_mapped",
"=",
"edge",
"[",
"1",
"]",
"in",
"self",
".",
"prog2hw",
"if",
"(",
"not",
"q1_mapped",
")",
"and",
"(",
"not",
"q2_mapped",
")",
":",
"best_hw_edge",
"=",
"self",
".",
"_select_best_remaining_cx",
"(",
")",
"self",
".",
"prog2hw",
"[",
"edge",
"[",
"0",
"]",
"]",
"=",
"best_hw_edge",
"[",
"0",
"]",
"self",
".",
"prog2hw",
"[",
"edge",
"[",
"1",
"]",
"]",
"=",
"best_hw_edge",
"[",
"1",
"]",
"self",
".",
"available_hw_qubits",
".",
"remove",
"(",
"best_hw_edge",
"[",
"0",
"]",
")",
"self",
".",
"available_hw_qubits",
".",
"remove",
"(",
"best_hw_edge",
"[",
"1",
"]",
")",
"elif",
"not",
"q1_mapped",
":",
"best_hw_qubit",
"=",
"self",
".",
"_select_best_remaining_qubit",
"(",
"edge",
"[",
"0",
"]",
")",
"self",
".",
"prog2hw",
"[",
"edge",
"[",
"0",
"]",
"]",
"=",
"best_hw_qubit",
"self",
".",
"available_hw_qubits",
".",
"remove",
"(",
"best_hw_qubit",
")",
"else",
":",
"best_hw_qubit",
"=",
"self",
".",
"_select_best_remaining_qubit",
"(",
"edge",
"[",
"1",
"]",
")",
"self",
".",
"prog2hw",
"[",
"edge",
"[",
"1",
"]",
"]",
"=",
"best_hw_qubit",
"self",
".",
"available_hw_qubits",
".",
"remove",
"(",
"best_hw_qubit",
")",
"new_edges",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"pending_program_edges",
"if",
"not",
"(",
"x",
"[",
"0",
"]",
"in",
"self",
".",
"prog2hw",
"and",
"x",
"[",
"1",
"]",
"in",
"self",
".",
"prog2hw",
")",
"]",
"self",
".",
"pending_program_edges",
"=",
"new_edges",
"for",
"qid",
"in",
"self",
".",
"qarg_to_id",
".",
"values",
"(",
")",
":",
"if",
"qid",
"not",
"in",
"self",
".",
"prog2hw",
":",
"self",
".",
"prog2hw",
"[",
"qid",
"]",
"=",
"self",
".",
"available_hw_qubits",
"[",
"0",
"]",
"self",
".",
"available_hw_qubits",
".",
"remove",
"(",
"self",
".",
"prog2hw",
"[",
"qid",
"]",
")",
"layout",
"=",
"Layout",
"(",
")",
"for",
"q",
"in",
"dag",
".",
"qubits",
"(",
")",
":",
"pid",
"=",
"self",
".",
"_qarg_to_id",
"(",
"q",
")",
"hwid",
"=",
"self",
".",
"prog2hw",
"[",
"pid",
"]",
"layout",
"[",
"(",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
")",
"]",
"=",
"hwid",
"self",
".",
"property_set",
"[",
"'layout'",
"]",
"=",
"layout"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
CompositeGate.instruction_list
|
Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
|
qiskit/circuit/compositegate.py
|
def instruction_list(self):
"""Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
"""
instruction_list = []
for instruction in self.data:
if isinstance(instruction, CompositeGate):
instruction_list.extend(instruction.instruction_list())
else:
instruction_list.append(instruction)
return instruction_list
|
def instruction_list(self):
"""Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
"""
instruction_list = []
for instruction in self.data:
if isinstance(instruction, CompositeGate):
instruction_list.extend(instruction.instruction_list())
else:
instruction_list.append(instruction)
return instruction_list
|
[
"Return",
"a",
"list",
"of",
"instructions",
"for",
"this",
"CompositeGate",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/compositegate.py#L34-L46
|
[
"def",
"instruction_list",
"(",
"self",
")",
":",
"instruction_list",
"=",
"[",
"]",
"for",
"instruction",
"in",
"self",
".",
"data",
":",
"if",
"isinstance",
"(",
"instruction",
",",
"CompositeGate",
")",
":",
"instruction_list",
".",
"extend",
"(",
"instruction",
".",
"instruction_list",
"(",
")",
")",
"else",
":",
"instruction_list",
".",
"append",
"(",
"instruction",
")",
"return",
"instruction_list"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
CompositeGate.inverse
|
Invert this gate.
|
qiskit/circuit/compositegate.py
|
def inverse(self):
"""Invert this gate."""
self.data = [gate.inverse() for gate in reversed(self.data)]
self.inverse_flag = not self.inverse_flag
return self
|
def inverse(self):
"""Invert this gate."""
self.data = [gate.inverse() for gate in reversed(self.data)]
self.inverse_flag = not self.inverse_flag
return self
|
[
"Invert",
"this",
"gate",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/compositegate.py#L70-L74
|
[
"def",
"inverse",
"(",
"self",
")",
":",
"self",
".",
"data",
"=",
"[",
"gate",
".",
"inverse",
"(",
")",
"for",
"gate",
"in",
"reversed",
"(",
"self",
".",
"data",
")",
"]",
"self",
".",
"inverse_flag",
"=",
"not",
"self",
".",
"inverse_flag",
"return",
"self"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
CompositeGate.q_if
|
Add controls to this gate.
|
qiskit/circuit/compositegate.py
|
def q_if(self, *qregs):
"""Add controls to this gate."""
self.data = [gate.q_if(qregs) for gate in self.data]
return self
|
def q_if(self, *qregs):
"""Add controls to this gate."""
self.data = [gate.q_if(qregs) for gate in self.data]
return self
|
[
"Add",
"controls",
"to",
"this",
"gate",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/compositegate.py#L76-L79
|
[
"def",
"q_if",
"(",
"self",
",",
"*",
"qregs",
")",
":",
"self",
".",
"data",
"=",
"[",
"gate",
".",
"q_if",
"(",
"qregs",
")",
"for",
"gate",
"in",
"self",
".",
"data",
"]",
"return",
"self"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
CompositeGate.c_if
|
Add classical control register.
|
qiskit/circuit/compositegate.py
|
def c_if(self, classical, val):
"""Add classical control register."""
self.data = [gate.c_if(classical, val) for gate in self.data]
return self
|
def c_if(self, classical, val):
"""Add classical control register."""
self.data = [gate.c_if(classical, val) for gate in self.data]
return self
|
[
"Add",
"classical",
"control",
"register",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/compositegate.py#L81-L84
|
[
"def",
"c_if",
"(",
"self",
",",
"classical",
",",
"val",
")",
":",
"self",
".",
"data",
"=",
"[",
"gate",
".",
"c_if",
"(",
"classical",
",",
"val",
")",
"for",
"gate",
"in",
"self",
".",
"data",
"]",
"return",
"self"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.is_unitary
|
Return True if operator is a unitary matrix.
|
qiskit/quantum_info/operators/operator.py
|
def is_unitary(self, atol=None, rtol=None):
"""Return True if operator is a unitary matrix."""
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
return is_unitary_matrix(self._data, rtol=rtol, atol=atol)
|
def is_unitary(self, atol=None, rtol=None):
"""Return True if operator is a unitary matrix."""
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
return is_unitary_matrix(self._data, rtol=rtol, atol=atol)
|
[
"Return",
"True",
"if",
"operator",
"is",
"a",
"unitary",
"matrix",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L89-L95
|
[
"def",
"is_unitary",
"(",
"self",
",",
"atol",
"=",
"None",
",",
"rtol",
"=",
"None",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"self",
".",
"_atol",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"self",
".",
"_rtol",
"return",
"is_unitary_matrix",
"(",
"self",
".",
"_data",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.conjugate
|
Return the conjugate of the operator.
|
qiskit/quantum_info/operators/operator.py
|
def conjugate(self):
"""Return the conjugate of the operator."""
return Operator(
np.conj(self.data), self.input_dims(), self.output_dims())
|
def conjugate(self):
"""Return the conjugate of the operator."""
return Operator(
np.conj(self.data), self.input_dims(), self.output_dims())
|
[
"Return",
"the",
"conjugate",
"of",
"the",
"operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L106-L109
|
[
"def",
"conjugate",
"(",
"self",
")",
":",
"return",
"Operator",
"(",
"np",
".",
"conj",
"(",
"self",
".",
"data",
")",
",",
"self",
".",
"input_dims",
"(",
")",
",",
"self",
".",
"output_dims",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.transpose
|
Return the transpose of the operator.
|
qiskit/quantum_info/operators/operator.py
|
def transpose(self):
"""Return the transpose of the operator."""
return Operator(
np.transpose(self.data), self.input_dims(), self.output_dims())
|
def transpose(self):
"""Return the transpose of the operator."""
return Operator(
np.transpose(self.data), self.input_dims(), self.output_dims())
|
[
"Return",
"the",
"transpose",
"of",
"the",
"operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L111-L114
|
[
"def",
"transpose",
"(",
"self",
")",
":",
"return",
"Operator",
"(",
"np",
".",
"transpose",
"(",
"self",
".",
"data",
")",
",",
"self",
".",
"input_dims",
"(",
")",
",",
"self",
".",
"output_dims",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.power
|
Return the matrix power of the operator.
Args:
n (int): the power to raise the matrix to.
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions of the operator
are not equal, or the power is not a positive integer.
|
qiskit/quantum_info/operators/operator.py
|
def power(self, n):
"""Return the matrix power of the operator.
Args:
n (int): the power to raise the matrix to.
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions of the operator
are not equal, or the power is not a positive integer.
"""
if not isinstance(n, int):
raise QiskitError("Can only take integer powers of Operator.")
if self.input_dims() != self.output_dims():
raise QiskitError("Can only power with input_dims = output_dims.")
# Override base class power so we can implement more efficiently
# using Numpy.matrix_power
return Operator(
np.linalg.matrix_power(self.data, n), self.input_dims(),
self.output_dims())
|
def power(self, n):
"""Return the matrix power of the operator.
Args:
n (int): the power to raise the matrix to.
Returns:
BaseOperator: the n-times composed operator.
Raises:
QiskitError: if the input and output dimensions of the operator
are not equal, or the power is not a positive integer.
"""
if not isinstance(n, int):
raise QiskitError("Can only take integer powers of Operator.")
if self.input_dims() != self.output_dims():
raise QiskitError("Can only power with input_dims = output_dims.")
# Override base class power so we can implement more efficiently
# using Numpy.matrix_power
return Operator(
np.linalg.matrix_power(self.data, n), self.input_dims(),
self.output_dims())
|
[
"Return",
"the",
"matrix",
"power",
"of",
"the",
"operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L159-L180
|
[
"def",
"power",
"(",
"self",
",",
"n",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"raise",
"QiskitError",
"(",
"\"Can only take integer powers of Operator.\"",
")",
"if",
"self",
".",
"input_dims",
"(",
")",
"!=",
"self",
".",
"output_dims",
"(",
")",
":",
"raise",
"QiskitError",
"(",
"\"Can only power with input_dims = output_dims.\"",
")",
"# Override base class power so we can implement more efficiently",
"# using Numpy.matrix_power",
"return",
"Operator",
"(",
"np",
".",
"linalg",
".",
"matrix_power",
"(",
"self",
".",
"data",
",",
"n",
")",
",",
"self",
".",
"input_dims",
"(",
")",
",",
"self",
".",
"output_dims",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.add
|
Return the operator self + other.
Args:
other (Operator): an operator object.
Returns:
Operator: the operator self + other.
Raises:
QiskitError: if other is not an operator, or has incompatible
dimensions.
|
qiskit/quantum_info/operators/operator.py
|
def add(self, other):
"""Return the operator self + other.
Args:
other (Operator): an operator object.
Returns:
Operator: the operator self + other.
Raises:
QiskitError: if other is not an operator, or has incompatible
dimensions.
"""
if not isinstance(other, Operator):
other = Operator(other)
if self.dim != other.dim:
raise QiskitError("other operator has different dimensions.")
return Operator(self.data + other.data, self.input_dims(),
self.output_dims())
|
def add(self, other):
"""Return the operator self + other.
Args:
other (Operator): an operator object.
Returns:
Operator: the operator self + other.
Raises:
QiskitError: if other is not an operator, or has incompatible
dimensions.
"""
if not isinstance(other, Operator):
other = Operator(other)
if self.dim != other.dim:
raise QiskitError("other operator has different dimensions.")
return Operator(self.data + other.data, self.input_dims(),
self.output_dims())
|
[
"Return",
"the",
"operator",
"self",
"+",
"other",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L210-L228
|
[
"def",
"add",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Operator",
")",
":",
"other",
"=",
"Operator",
"(",
"other",
")",
"if",
"self",
".",
"dim",
"!=",
"other",
".",
"dim",
":",
"raise",
"QiskitError",
"(",
"\"other operator has different dimensions.\"",
")",
"return",
"Operator",
"(",
"self",
".",
"data",
"+",
"other",
".",
"data",
",",
"self",
".",
"input_dims",
"(",
")",
",",
"self",
".",
"output_dims",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator.multiply
|
Return the operator self + other.
Args:
other (complex): a complex number.
Returns:
Operator: the operator other * self.
Raises:
QiskitError: if other is not a valid complex number.
|
qiskit/quantum_info/operators/operator.py
|
def multiply(self, other):
"""Return the operator self + other.
Args:
other (complex): a complex number.
Returns:
Operator: the operator other * self.
Raises:
QiskitError: if other is not a valid complex number.
"""
if not isinstance(other, Number):
raise QiskitError("other is not a number")
return Operator(other * self.data, self.input_dims(),
self.output_dims())
|
def multiply(self, other):
"""Return the operator self + other.
Args:
other (complex): a complex number.
Returns:
Operator: the operator other * self.
Raises:
QiskitError: if other is not a valid complex number.
"""
if not isinstance(other, Number):
raise QiskitError("other is not a number")
return Operator(other * self.data, self.input_dims(),
self.output_dims())
|
[
"Return",
"the",
"operator",
"self",
"+",
"other",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L250-L265
|
[
"def",
"multiply",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Number",
")",
":",
"raise",
"QiskitError",
"(",
"\"other is not a number\"",
")",
"return",
"Operator",
"(",
"other",
"*",
"self",
".",
"data",
",",
"self",
".",
"input_dims",
"(",
")",
",",
"self",
".",
"output_dims",
"(",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._shape
|
Return the tensor shape of the matrix operator
|
qiskit/quantum_info/operators/operator.py
|
def _shape(self):
"""Return the tensor shape of the matrix operator"""
return tuple(reversed(self.output_dims())) + tuple(
reversed(self.input_dims()))
|
def _shape(self):
"""Return the tensor shape of the matrix operator"""
return tuple(reversed(self.output_dims())) + tuple(
reversed(self.input_dims()))
|
[
"Return",
"the",
"tensor",
"shape",
"of",
"the",
"matrix",
"operator"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L268-L271
|
[
"def",
"_shape",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"reversed",
"(",
"self",
".",
"output_dims",
"(",
")",
")",
")",
"+",
"tuple",
"(",
"reversed",
"(",
"self",
".",
"input_dims",
"(",
")",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._evolve
|
Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
|
qiskit/quantum_info/operators/operator.py
|
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
state = self._format_state(state)
if qargs is None:
if state.shape[0] != self._input_dim:
raise QiskitError(
"Operator input dimension is not equal to state dimension."
)
if state.ndim == 1:
# Return evolved statevector
return np.dot(self.data, state)
# Return evolved density matrix
return np.dot(
np.dot(self.data, state), np.transpose(np.conj(self.data)))
# Subsystem evolution
return self._evolve_subsystem(state, qargs)
|
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
state = self._format_state(state)
if qargs is None:
if state.shape[0] != self._input_dim:
raise QiskitError(
"Operator input dimension is not equal to state dimension."
)
if state.ndim == 1:
# Return evolved statevector
return np.dot(self.data, state)
# Return evolved density matrix
return np.dot(
np.dot(self.data, state), np.transpose(np.conj(self.data)))
# Subsystem evolution
return self._evolve_subsystem(state, qargs)
|
[
"Evolve",
"a",
"quantum",
"state",
"by",
"the",
"operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L273-L301
|
[
"def",
"_evolve",
"(",
"self",
",",
"state",
",",
"qargs",
"=",
"None",
")",
":",
"state",
"=",
"self",
".",
"_format_state",
"(",
"state",
")",
"if",
"qargs",
"is",
"None",
":",
"if",
"state",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"_input_dim",
":",
"raise",
"QiskitError",
"(",
"\"Operator input dimension is not equal to state dimension.\"",
")",
"if",
"state",
".",
"ndim",
"==",
"1",
":",
"# Return evolved statevector",
"return",
"np",
".",
"dot",
"(",
"self",
".",
"data",
",",
"state",
")",
"# Return evolved density matrix",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"data",
",",
"state",
")",
",",
"np",
".",
"transpose",
"(",
"np",
".",
"conj",
"(",
"self",
".",
"data",
")",
")",
")",
"# Subsystem evolution",
"return",
"self",
".",
"_evolve_subsystem",
"(",
"state",
",",
"qargs",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._evolve_subsystem
|
Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
|
qiskit/quantum_info/operators/operator.py
|
def _evolve_subsystem(self, state, qargs):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
mat = np.reshape(self.data, self._shape)
# Hack to assume state is a N-qubit state until a proper class for states
# is in place
state_size = len(state)
state_dims = self._automatic_dims(None, state_size)
if self.input_dims() != len(qargs) * (2,):
raise QiskitError(
"Operator input dimensions are not compatible with state subsystem dimensions."
)
if state.ndim == 1:
# Return evolved statevector
tensor = np.reshape(state, state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
tensor = self._einsum_matmul(tensor, mat, indices)
return np.reshape(tensor, state_size)
# Return evolved density matrix
tensor = np.reshape(state, 2 * state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
right_shift = len(state_dims)
# Left multiply by operator
tensor = self._einsum_matmul(tensor, mat, indices)
# Right multiply by adjoint operator
# We implement the transpose by doing left multiplication instead of right
# in the _einsum_matmul function
tensor = self._einsum_matmul(
tensor, np.conj(mat), indices, shift=right_shift)
return np.reshape(tensor, [state_size, state_size])
|
def _evolve_subsystem(self, state, qargs):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
mat = np.reshape(self.data, self._shape)
# Hack to assume state is a N-qubit state until a proper class for states
# is in place
state_size = len(state)
state_dims = self._automatic_dims(None, state_size)
if self.input_dims() != len(qargs) * (2,):
raise QiskitError(
"Operator input dimensions are not compatible with state subsystem dimensions."
)
if state.ndim == 1:
# Return evolved statevector
tensor = np.reshape(state, state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
tensor = self._einsum_matmul(tensor, mat, indices)
return np.reshape(tensor, state_size)
# Return evolved density matrix
tensor = np.reshape(state, 2 * state_dims)
indices = [len(state_dims) - 1 - qubit for qubit in qargs]
right_shift = len(state_dims)
# Left multiply by operator
tensor = self._einsum_matmul(tensor, mat, indices)
# Right multiply by adjoint operator
# We implement the transpose by doing left multiplication instead of right
# in the _einsum_matmul function
tensor = self._einsum_matmul(
tensor, np.conj(mat), indices, shift=right_shift)
return np.reshape(tensor, [state_size, state_size])
|
[
"Evolve",
"a",
"quantum",
"state",
"by",
"the",
"operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L359-L400
|
[
"def",
"_evolve_subsystem",
"(",
"self",
",",
"state",
",",
"qargs",
")",
":",
"mat",
"=",
"np",
".",
"reshape",
"(",
"self",
".",
"data",
",",
"self",
".",
"_shape",
")",
"# Hack to assume state is a N-qubit state until a proper class for states",
"# is in place",
"state_size",
"=",
"len",
"(",
"state",
")",
"state_dims",
"=",
"self",
".",
"_automatic_dims",
"(",
"None",
",",
"state_size",
")",
"if",
"self",
".",
"input_dims",
"(",
")",
"!=",
"len",
"(",
"qargs",
")",
"*",
"(",
"2",
",",
")",
":",
"raise",
"QiskitError",
"(",
"\"Operator input dimensions are not compatible with state subsystem dimensions.\"",
")",
"if",
"state",
".",
"ndim",
"==",
"1",
":",
"# Return evolved statevector",
"tensor",
"=",
"np",
".",
"reshape",
"(",
"state",
",",
"state_dims",
")",
"indices",
"=",
"[",
"len",
"(",
"state_dims",
")",
"-",
"1",
"-",
"qubit",
"for",
"qubit",
"in",
"qargs",
"]",
"tensor",
"=",
"self",
".",
"_einsum_matmul",
"(",
"tensor",
",",
"mat",
",",
"indices",
")",
"return",
"np",
".",
"reshape",
"(",
"tensor",
",",
"state_size",
")",
"# Return evolved density matrix",
"tensor",
"=",
"np",
".",
"reshape",
"(",
"state",
",",
"2",
"*",
"state_dims",
")",
"indices",
"=",
"[",
"len",
"(",
"state_dims",
")",
"-",
"1",
"-",
"qubit",
"for",
"qubit",
"in",
"qargs",
"]",
"right_shift",
"=",
"len",
"(",
"state_dims",
")",
"# Left multiply by operator",
"tensor",
"=",
"self",
".",
"_einsum_matmul",
"(",
"tensor",
",",
"mat",
",",
"indices",
")",
"# Right multiply by adjoint operator",
"# We implement the transpose by doing left multiplication instead of right",
"# in the _einsum_matmul function",
"tensor",
"=",
"self",
".",
"_einsum_matmul",
"(",
"tensor",
",",
"np",
".",
"conj",
"(",
"mat",
")",
",",
"indices",
",",
"shift",
"=",
"right_shift",
")",
"return",
"np",
".",
"reshape",
"(",
"tensor",
",",
"[",
"state_size",
",",
"state_size",
"]",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._format_state
|
Format input state so it is statevector or density matrix
|
qiskit/quantum_info/operators/operator.py
|
def _format_state(self, state):
"""Format input state so it is statevector or density matrix"""
state = np.array(state)
shape = state.shape
ndim = state.ndim
if ndim > 2:
raise QiskitError('Input state is not a vector or matrix.')
# Flatten column-vector to vector
if ndim == 2:
if shape[1] != 1 and shape[1] != shape[0]:
raise QiskitError('Input state is not a vector or matrix.')
if shape[1] == 1:
# flatten colum-vector to vector
state = np.reshape(state, shape[0])
return state
|
def _format_state(self, state):
"""Format input state so it is statevector or density matrix"""
state = np.array(state)
shape = state.shape
ndim = state.ndim
if ndim > 2:
raise QiskitError('Input state is not a vector or matrix.')
# Flatten column-vector to vector
if ndim == 2:
if shape[1] != 1 and shape[1] != shape[0]:
raise QiskitError('Input state is not a vector or matrix.')
if shape[1] == 1:
# flatten colum-vector to vector
state = np.reshape(state, shape[0])
return state
|
[
"Format",
"input",
"state",
"so",
"it",
"is",
"statevector",
"or",
"density",
"matrix"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L402-L416
|
[
"def",
"_format_state",
"(",
"self",
",",
"state",
")",
":",
"state",
"=",
"np",
".",
"array",
"(",
"state",
")",
"shape",
"=",
"state",
".",
"shape",
"ndim",
"=",
"state",
".",
"ndim",
"if",
"ndim",
">",
"2",
":",
"raise",
"QiskitError",
"(",
"'Input state is not a vector or matrix.'",
")",
"# Flatten column-vector to vector",
"if",
"ndim",
"==",
"2",
":",
"if",
"shape",
"[",
"1",
"]",
"!=",
"1",
"and",
"shape",
"[",
"1",
"]",
"!=",
"shape",
"[",
"0",
"]",
":",
"raise",
"QiskitError",
"(",
"'Input state is not a vector or matrix.'",
")",
"if",
"shape",
"[",
"1",
"]",
"==",
"1",
":",
"# flatten colum-vector to vector",
"state",
"=",
"np",
".",
"reshape",
"(",
"state",
",",
"shape",
"[",
"0",
"]",
")",
"return",
"state"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._instruction_to_operator
|
Convert a QuantumCircuit or Instruction to an Operator.
|
qiskit/quantum_info/operators/operator.py
|
def _instruction_to_operator(cls, instruction):
"""Convert a QuantumCircuit or Instruction to an Operator."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an identity operator of the correct size of the circuit
op = Operator(np.eye(2 ** instruction.num_qubits))
op._append_instruction(instruction)
return op
|
def _instruction_to_operator(cls, instruction):
"""Convert a QuantumCircuit or Instruction to an Operator."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an identity operator of the correct size of the circuit
op = Operator(np.eye(2 ** instruction.num_qubits))
op._append_instruction(instruction)
return op
|
[
"Convert",
"a",
"QuantumCircuit",
"or",
"Instruction",
"to",
"an",
"Operator",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L419-L427
|
[
"def",
"_instruction_to_operator",
"(",
"cls",
",",
"instruction",
")",
":",
"# Convert circuit to an instruction",
"if",
"isinstance",
"(",
"instruction",
",",
"QuantumCircuit",
")",
":",
"instruction",
"=",
"instruction",
".",
"to_instruction",
"(",
")",
"# Initialize an identity operator of the correct size of the circuit",
"op",
"=",
"Operator",
"(",
"np",
".",
"eye",
"(",
"2",
"**",
"instruction",
".",
"num_qubits",
")",
")",
"op",
".",
"_append_instruction",
"(",
"instruction",
")",
"return",
"op"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Operator._append_instruction
|
Update the current Operator by apply an instruction.
|
qiskit/quantum_info/operators/operator.py
|
def _append_instruction(self, obj, qargs=None):
"""Update the current Operator by apply an instruction."""
if isinstance(obj, Instruction):
mat = None
if hasattr(obj, 'to_matrix'):
# If instruction is a gate first we see if it has a
# `to_matrix` definition and if so use that.
try:
mat = obj.to_matrix()
except QiskitError:
pass
if mat is not None:
# Perform the composition and inplace update the current state
# of the operator
op = self.compose(mat, qargs=qargs)
self._data = op.data
else:
# If the instruction doesn't have a matrix defined we use its
# circuit decomposition definition if it exists, otherwise we
# cannot compose this gate and raise an error.
if obj.definition is None:
raise QiskitError('Cannot apply Instruction: {}'.format(obj.name))
for instr, qregs, cregs in obj.definition:
if cregs:
raise QiskitError(
'Cannot apply instruction with classical registers: {}'.format(
instr.name))
# Get the integer position of the flat register
new_qargs = [tup[1] for tup in qregs]
self._append_instruction(instr, qargs=new_qargs)
else:
raise QiskitError('Input is not an instruction.')
|
def _append_instruction(self, obj, qargs=None):
"""Update the current Operator by apply an instruction."""
if isinstance(obj, Instruction):
mat = None
if hasattr(obj, 'to_matrix'):
# If instruction is a gate first we see if it has a
# `to_matrix` definition and if so use that.
try:
mat = obj.to_matrix()
except QiskitError:
pass
if mat is not None:
# Perform the composition and inplace update the current state
# of the operator
op = self.compose(mat, qargs=qargs)
self._data = op.data
else:
# If the instruction doesn't have a matrix defined we use its
# circuit decomposition definition if it exists, otherwise we
# cannot compose this gate and raise an error.
if obj.definition is None:
raise QiskitError('Cannot apply Instruction: {}'.format(obj.name))
for instr, qregs, cregs in obj.definition:
if cregs:
raise QiskitError(
'Cannot apply instruction with classical registers: {}'.format(
instr.name))
# Get the integer position of the flat register
new_qargs = [tup[1] for tup in qregs]
self._append_instruction(instr, qargs=new_qargs)
else:
raise QiskitError('Input is not an instruction.')
|
[
"Update",
"the",
"current",
"Operator",
"by",
"apply",
"an",
"instruction",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L429-L460
|
[
"def",
"_append_instruction",
"(",
"self",
",",
"obj",
",",
"qargs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Instruction",
")",
":",
"mat",
"=",
"None",
"if",
"hasattr",
"(",
"obj",
",",
"'to_matrix'",
")",
":",
"# If instruction is a gate first we see if it has a",
"# `to_matrix` definition and if so use that.",
"try",
":",
"mat",
"=",
"obj",
".",
"to_matrix",
"(",
")",
"except",
"QiskitError",
":",
"pass",
"if",
"mat",
"is",
"not",
"None",
":",
"# Perform the composition and inplace update the current state",
"# of the operator",
"op",
"=",
"self",
".",
"compose",
"(",
"mat",
",",
"qargs",
"=",
"qargs",
")",
"self",
".",
"_data",
"=",
"op",
".",
"data",
"else",
":",
"# If the instruction doesn't have a matrix defined we use its",
"# circuit decomposition definition if it exists, otherwise we",
"# cannot compose this gate and raise an error.",
"if",
"obj",
".",
"definition",
"is",
"None",
":",
"raise",
"QiskitError",
"(",
"'Cannot apply Instruction: {}'",
".",
"format",
"(",
"obj",
".",
"name",
")",
")",
"for",
"instr",
",",
"qregs",
",",
"cregs",
"in",
"obj",
".",
"definition",
":",
"if",
"cregs",
":",
"raise",
"QiskitError",
"(",
"'Cannot apply instruction with classical registers: {}'",
".",
"format",
"(",
"instr",
".",
"name",
")",
")",
"# Get the integer position of the flat register",
"new_qargs",
"=",
"[",
"tup",
"[",
"1",
"]",
"for",
"tup",
"in",
"qregs",
"]",
"self",
".",
"_append_instruction",
"(",
"instr",
",",
"qargs",
"=",
"new_qargs",
")",
"else",
":",
"raise",
"QiskitError",
"(",
"'Input is not an instruction.'",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LegacySwap.run
|
Map a DAGCircuit onto a CouplingGraph using swap gates.
Args:
dag (DAGCircuit): input DAG circuit
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_map, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_map. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout.
Raises:
TranspilerError: if there was any error during the mapping or with the
parameters.
|
qiskit/transpiler/passes/mapping/legacy_swap.py
|
def run(self, dag):
"""Map a DAGCircuit onto a CouplingGraph using swap gates.
Args:
dag (DAGCircuit): input DAG circuit
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_map, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_map. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout.
Raises:
TranspilerError: if there was any error during the mapping or with the
parameters.
"""
if dag.width() > self.coupling_map.size():
raise TranspilerError("Not enough qubits in CouplingGraph")
# Schedule the input circuit
layerlist = list(dag.layers())
if self.initial_layout is None and self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
if self.initial_layout is not None:
# update initial_layout from a user given dict{(regname,idx): (regname,idx)}
# to an expected dict{(reg,idx): (reg,idx)}
virtual_qubits = self.initial_layout.get_virtual_bits()
self.initial_layout = {(v[0].name, v[1]): ('q', self.initial_layout[v]) for v in
virtual_qubits}
device_register = QuantumRegister(self.coupling_map.size(), 'q')
initial_layout = {(dag.qregs[k[0]], k[1]): (device_register, v[1])
for k, v in self.initial_layout.items()}
# Check the input layout
circ_qubits = dag.qubits()
coup_qubits = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in
self.coupling_map.physical_qubits]
qubit_subset = []
for k, v in initial_layout.items():
qubit_subset.append(v)
if k not in circ_qubits:
raise TranspilerError("initial_layout qubit %s[%d] not in input "
"DAGCircuit" % (k[0].name, k[1]))
if v not in coup_qubits:
raise TranspilerError("initial_layout qubit %s[%d] not in input "
"CouplingGraph" % (v[0].name, v[1]))
else:
# Supply a default layout
qubit_subset = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in
self.coupling_map.physical_qubits]
qubit_subset = qubit_subset[0:dag.width()]
initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)}
# Find swap circuit to preceed to each layer of input circuit
layout = initial_layout.copy()
# Construct an empty DAGCircuit with one qreg "q"
# and the same set of cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = dag.name
dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), "q"))
for creg in dag.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by swap_mapper_layer_update and the circuit
# we are building
identity_wire_map = {}
q = QuantumRegister(self.coupling_map.size(), 'q')
for j in range(self.coupling_map.size()):
identity_wire_map[(q, j)] = (q, j)
for creg in dag.cregs.values():
for j in range(creg.size):
identity_wire_map[(creg, j)] = (creg, j)
first_layer = True # True until first layer is output
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circ, best_d, best_layout, trivial_flag \
= self.layer_permutation(layer["partition"], layout, qubit_subset)
# If this fails, try one gate at a time in this layer
if not success_flag:
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circ, best_d, best_layout, trivial_flag \
= self.layer_permutation(serial_layer["partition"], layout, qubit_subset)
# Give up if we fail again
if not success_flag:
raise TranspilerError("swap_mapper failed: " +
"layer %d, sublayer %d" % (i, j))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
continue
# Update the record of qubit positions for each inner iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
self.swap_mapper_layer_update(j,
first_layer,
best_layout,
best_d,
best_circ,
serial_layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
self.swap_mapper_layer_update(i,
first_layer,
best_layout,
best_d,
best_circ,
layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
if first_layer:
layout = initial_layout
for i, layer in enumerate(layerlist):
dagcircuit_output.compose_back(layer["graph"], layout)
return dagcircuit_output
|
def run(self, dag):
"""Map a DAGCircuit onto a CouplingGraph using swap gates.
Args:
dag (DAGCircuit): input DAG circuit
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_map, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_map. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout.
Raises:
TranspilerError: if there was any error during the mapping or with the
parameters.
"""
if dag.width() > self.coupling_map.size():
raise TranspilerError("Not enough qubits in CouplingGraph")
# Schedule the input circuit
layerlist = list(dag.layers())
if self.initial_layout is None and self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
if self.initial_layout is not None:
# update initial_layout from a user given dict{(regname,idx): (regname,idx)}
# to an expected dict{(reg,idx): (reg,idx)}
virtual_qubits = self.initial_layout.get_virtual_bits()
self.initial_layout = {(v[0].name, v[1]): ('q', self.initial_layout[v]) for v in
virtual_qubits}
device_register = QuantumRegister(self.coupling_map.size(), 'q')
initial_layout = {(dag.qregs[k[0]], k[1]): (device_register, v[1])
for k, v in self.initial_layout.items()}
# Check the input layout
circ_qubits = dag.qubits()
coup_qubits = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in
self.coupling_map.physical_qubits]
qubit_subset = []
for k, v in initial_layout.items():
qubit_subset.append(v)
if k not in circ_qubits:
raise TranspilerError("initial_layout qubit %s[%d] not in input "
"DAGCircuit" % (k[0].name, k[1]))
if v not in coup_qubits:
raise TranspilerError("initial_layout qubit %s[%d] not in input "
"CouplingGraph" % (v[0].name, v[1]))
else:
# Supply a default layout
qubit_subset = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in
self.coupling_map.physical_qubits]
qubit_subset = qubit_subset[0:dag.width()]
initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)}
# Find swap circuit to preceed to each layer of input circuit
layout = initial_layout.copy()
# Construct an empty DAGCircuit with one qreg "q"
# and the same set of cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = dag.name
dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), "q"))
for creg in dag.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by swap_mapper_layer_update and the circuit
# we are building
identity_wire_map = {}
q = QuantumRegister(self.coupling_map.size(), 'q')
for j in range(self.coupling_map.size()):
identity_wire_map[(q, j)] = (q, j)
for creg in dag.cregs.values():
for j in range(creg.size):
identity_wire_map[(creg, j)] = (creg, j)
first_layer = True # True until first layer is output
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circ, best_d, best_layout, trivial_flag \
= self.layer_permutation(layer["partition"], layout, qubit_subset)
# If this fails, try one gate at a time in this layer
if not success_flag:
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circ, best_d, best_layout, trivial_flag \
= self.layer_permutation(serial_layer["partition"], layout, qubit_subset)
# Give up if we fail again
if not success_flag:
raise TranspilerError("swap_mapper failed: " +
"layer %d, sublayer %d" % (i, j))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
continue
# Update the record of qubit positions for each inner iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
self.swap_mapper_layer_update(j,
first_layer,
best_layout,
best_d,
best_circ,
serial_layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
self.swap_mapper_layer_update(i,
first_layer,
best_layout,
best_d,
best_circ,
layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
if first_layer:
layout = initial_layout
for i, layer in enumerate(layerlist):
dagcircuit_output.compose_back(layer["graph"], layout)
return dagcircuit_output
|
[
"Map",
"a",
"DAGCircuit",
"onto",
"a",
"CouplingGraph",
"using",
"swap",
"gates",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/legacy_swap.py#L53-L204
|
[
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"if",
"dag",
".",
"width",
"(",
")",
">",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
":",
"raise",
"TranspilerError",
"(",
"\"Not enough qubits in CouplingGraph\"",
")",
"# Schedule the input circuit",
"layerlist",
"=",
"list",
"(",
"dag",
".",
"layers",
"(",
")",
")",
"if",
"self",
".",
"initial_layout",
"is",
"None",
"and",
"self",
".",
"property_set",
"[",
"\"layout\"",
"]",
":",
"self",
".",
"initial_layout",
"=",
"self",
".",
"property_set",
"[",
"\"layout\"",
"]",
"if",
"self",
".",
"initial_layout",
"is",
"not",
"None",
":",
"# update initial_layout from a user given dict{(regname,idx): (regname,idx)}",
"# to an expected dict{(reg,idx): (reg,idx)}",
"virtual_qubits",
"=",
"self",
".",
"initial_layout",
".",
"get_virtual_bits",
"(",
")",
"self",
".",
"initial_layout",
"=",
"{",
"(",
"v",
"[",
"0",
"]",
".",
"name",
",",
"v",
"[",
"1",
"]",
")",
":",
"(",
"'q'",
",",
"self",
".",
"initial_layout",
"[",
"v",
"]",
")",
"for",
"v",
"in",
"virtual_qubits",
"}",
"device_register",
"=",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"'q'",
")",
"initial_layout",
"=",
"{",
"(",
"dag",
".",
"qregs",
"[",
"k",
"[",
"0",
"]",
"]",
",",
"k",
"[",
"1",
"]",
")",
":",
"(",
"device_register",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"initial_layout",
".",
"items",
"(",
")",
"}",
"# Check the input layout",
"circ_qubits",
"=",
"dag",
".",
"qubits",
"(",
")",
"coup_qubits",
"=",
"[",
"(",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"'q'",
")",
",",
"wire",
")",
"for",
"wire",
"in",
"self",
".",
"coupling_map",
".",
"physical_qubits",
"]",
"qubit_subset",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"initial_layout",
".",
"items",
"(",
")",
":",
"qubit_subset",
".",
"append",
"(",
"v",
")",
"if",
"k",
"not",
"in",
"circ_qubits",
":",
"raise",
"TranspilerError",
"(",
"\"initial_layout qubit %s[%d] not in input \"",
"\"DAGCircuit\"",
"%",
"(",
"k",
"[",
"0",
"]",
".",
"name",
",",
"k",
"[",
"1",
"]",
")",
")",
"if",
"v",
"not",
"in",
"coup_qubits",
":",
"raise",
"TranspilerError",
"(",
"\"initial_layout qubit %s[%d] not in input \"",
"\"CouplingGraph\"",
"%",
"(",
"v",
"[",
"0",
"]",
".",
"name",
",",
"v",
"[",
"1",
"]",
")",
")",
"else",
":",
"# Supply a default layout",
"qubit_subset",
"=",
"[",
"(",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"'q'",
")",
",",
"wire",
")",
"for",
"wire",
"in",
"self",
".",
"coupling_map",
".",
"physical_qubits",
"]",
"qubit_subset",
"=",
"qubit_subset",
"[",
"0",
":",
"dag",
".",
"width",
"(",
")",
"]",
"initial_layout",
"=",
"{",
"a",
":",
"b",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"dag",
".",
"qubits",
"(",
")",
",",
"qubit_subset",
")",
"}",
"# Find swap circuit to preceed to each layer of input circuit",
"layout",
"=",
"initial_layout",
".",
"copy",
"(",
")",
"# Construct an empty DAGCircuit with one qreg \"q\"",
"# and the same set of cregs as the input circuit",
"dagcircuit_output",
"=",
"DAGCircuit",
"(",
")",
"dagcircuit_output",
".",
"name",
"=",
"dag",
".",
"name",
"dagcircuit_output",
".",
"add_qreg",
"(",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"\"q\"",
")",
")",
"for",
"creg",
"in",
"dag",
".",
"cregs",
".",
"values",
"(",
")",
":",
"dagcircuit_output",
".",
"add_creg",
"(",
"creg",
")",
"# Make a trivial wire mapping between the subcircuits",
"# returned by swap_mapper_layer_update and the circuit",
"# we are building",
"identity_wire_map",
"=",
"{",
"}",
"q",
"=",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"'q'",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
")",
":",
"identity_wire_map",
"[",
"(",
"q",
",",
"j",
")",
"]",
"=",
"(",
"q",
",",
"j",
")",
"for",
"creg",
"in",
"dag",
".",
"cregs",
".",
"values",
"(",
")",
":",
"for",
"j",
"in",
"range",
"(",
"creg",
".",
"size",
")",
":",
"identity_wire_map",
"[",
"(",
"creg",
",",
"j",
")",
"]",
"=",
"(",
"creg",
",",
"j",
")",
"first_layer",
"=",
"True",
"# True until first layer is output",
"# Iterate over layers",
"for",
"i",
",",
"layer",
"in",
"enumerate",
"(",
"layerlist",
")",
":",
"# Attempt to find a permutation for this layer",
"success_flag",
",",
"best_circ",
",",
"best_d",
",",
"best_layout",
",",
"trivial_flag",
"=",
"self",
".",
"layer_permutation",
"(",
"layer",
"[",
"\"partition\"",
"]",
",",
"layout",
",",
"qubit_subset",
")",
"# If this fails, try one gate at a time in this layer",
"if",
"not",
"success_flag",
":",
"serial_layerlist",
"=",
"list",
"(",
"layer",
"[",
"\"graph\"",
"]",
".",
"serial_layers",
"(",
")",
")",
"# Go through each gate in the layer",
"for",
"j",
",",
"serial_layer",
"in",
"enumerate",
"(",
"serial_layerlist",
")",
":",
"success_flag",
",",
"best_circ",
",",
"best_d",
",",
"best_layout",
",",
"trivial_flag",
"=",
"self",
".",
"layer_permutation",
"(",
"serial_layer",
"[",
"\"partition\"",
"]",
",",
"layout",
",",
"qubit_subset",
")",
"# Give up if we fail again",
"if",
"not",
"success_flag",
":",
"raise",
"TranspilerError",
"(",
"\"swap_mapper failed: \"",
"+",
"\"layer %d, sublayer %d\"",
"%",
"(",
"i",
",",
"j",
")",
")",
"# If this layer is only single-qubit gates,",
"# and we have yet to see multi-qubit gates,",
"# continue to the next inner iteration",
"if",
"trivial_flag",
"and",
"first_layer",
":",
"continue",
"# Update the record of qubit positions for each inner iteration",
"layout",
"=",
"best_layout",
"# Update the QASM",
"dagcircuit_output",
".",
"compose_back",
"(",
"self",
".",
"swap_mapper_layer_update",
"(",
"j",
",",
"first_layer",
",",
"best_layout",
",",
"best_d",
",",
"best_circ",
",",
"serial_layerlist",
")",
",",
"identity_wire_map",
")",
"# Update initial layout",
"if",
"first_layer",
":",
"initial_layout",
"=",
"layout",
"first_layer",
"=",
"False",
"else",
":",
"# Update the record of qubit positions for each iteration",
"layout",
"=",
"best_layout",
"# Update the QASM",
"dagcircuit_output",
".",
"compose_back",
"(",
"self",
".",
"swap_mapper_layer_update",
"(",
"i",
",",
"first_layer",
",",
"best_layout",
",",
"best_d",
",",
"best_circ",
",",
"layerlist",
")",
",",
"identity_wire_map",
")",
"# Update initial layout",
"if",
"first_layer",
":",
"initial_layout",
"=",
"layout",
"first_layer",
"=",
"False",
"# If first_layer is still set, the circuit only has single-qubit gates",
"# so we can use the initial layout to output the entire circuit",
"if",
"first_layer",
":",
"layout",
"=",
"initial_layout",
"for",
"i",
",",
"layer",
"in",
"enumerate",
"(",
"layerlist",
")",
":",
"dagcircuit_output",
".",
"compose_back",
"(",
"layer",
"[",
"\"graph\"",
"]",
",",
"layout",
")",
"return",
"dagcircuit_output"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LegacySwap.layer_permutation
|
Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
The layout is a dict mapping qubits in the circuit to qubits in the
coupling graph and represents the current positions of the data.
The qubit_subset is the subset of qubits in the coupling graph that
we have chosen to map into.
The coupling is a CouplingGraph.
TRIALS is the number of attempts the randomized algorithm makes.
Returns: success_flag, best_circ, best_d, best_layout, trivial_flag
If success_flag is True, then best_circ contains a DAGCircuit with
the swap circuit, best_d contains the depth of the swap circuit, and
best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
|
qiskit/transpiler/passes/mapping/legacy_swap.py
|
def layer_permutation(self, layer_partition, layout, qubit_subset):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
The layout is a dict mapping qubits in the circuit to qubits in the
coupling graph and represents the current positions of the data.
The qubit_subset is the subset of qubits in the coupling graph that
we have chosen to map into.
The coupling is a CouplingGraph.
TRIALS is the number of attempts the randomized algorithm makes.
Returns: success_flag, best_circ, best_d, best_layout, trivial_flag
If success_flag is True, then best_circ contains a DAGCircuit with
the swap circuit, best_d contains the depth of the swap circuit, and
best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
"""
if self.seed is None:
self.seed = np.random.randint(0, np.iinfo(np.int32).max)
rng = np.random.RandomState(self.seed)
rev_layout = {b: a for a, b in layout.items()}
gates = []
for layer in layer_partition:
if len(layer) > 2:
raise TranspilerError("Layer contains >2 qubit gates")
elif len(layer) == 2:
gates.append(tuple(layer))
# Can we already apply the gates?
dist = sum([self.coupling_map.distance(layout[g[0]][1], layout[g[1]][1]) for g in gates])
if dist == len(gates):
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(self.coupling_map.size(), "q"))
return True, circ, 0, layout, bool(gates)
# Begin loop over trials of randomized algorithm
n = self.coupling_map.size()
best_d = sys.maxsize # initialize best depth
best_circ = None # initialize best swap circuit
best_layout = None # initialize best final layout
QR = QuantumRegister(self.coupling_map.size(), "q")
for _ in range(self.trials):
trial_layout = layout.copy()
rev_trial_layout = rev_layout.copy()
# SWAP circuit constructed this trial
trial_circ = DAGCircuit()
trial_circ.add_qreg(QR)
# Compute Sergey's randomized distance
xi = {}
for i in self.coupling_map.physical_qubits:
xi[(QR, i)] = {}
for i in self.coupling_map.physical_qubits:
i = (QR, i)
for j in self.coupling_map.physical_qubits:
j = (QR, j)
scale = 1 + rng.normal(0, 1 / n)
xi[i][j] = scale * self.coupling_map.distance(i[1], j[1]) ** 2
xi[j][i] = xi[i][j]
# Loop over depths d up to a max depth of 2n+1
d = 1
# Circuit for this swap slice
circ = DAGCircuit()
circ.add_qreg(QR)
# Identity wire-map for composing the circuits
identity_wire_map = {(QR, j): (QR, j) for j in range(n)}
while d < 2 * n + 1:
# Set of available qubits
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]]
for g in gates])
# Try to decrease objective function
progress_made = False
# Loop over edges of coupling graph
for e in self.coupling_map.get_edges():
e = [(QR, edge) for edge in e]
# Are the qubits available?
if e[0] in qubit_set and e[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout[rev_trial_layout[e[0]]] = e[1]
new_layout[rev_trial_layout[e[1]]] = e[0]
rev_new_layout = rev_trial_layout.copy()
rev_new_layout[e[0]] = rev_trial_layout[e[1]]
rev_new_layout[e[1]] = rev_trial_layout[e[0]]
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]]
for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
progress_made = True
min_cost = new_cost
opt_layout = new_layout
rev_opt_layout = rev_new_layout
opt_edge = e
# Were there any good choices?
if progress_made:
qubit_set.remove(opt_edge[0])
qubit_set.remove(opt_edge[1])
trial_layout = opt_layout
rev_trial_layout = rev_opt_layout
circ.apply_operation_back(
SwapGate(),
[(opt_edge[0][0], opt_edge[0][1]), (opt_edge[1][0], opt_edge[1][1])],
[])
else:
break
# We have either run out of qubits or failed to improve
# Compute the coupling graph distance_qubits
dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],
trial_layout[g[1]][1]) for g in gates])
# If all gates can be applied now, we are finished
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
trial_circ.compose_back(circ, identity_wire_map)
break
# Increment the depth
d += 1
# Either we have succeeded at some depth d < dmax or failed
dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],
trial_layout[g[1]][1]) for g in gates])
if dist == len(gates):
if d < best_d:
best_circ = trial_circ
best_layout = trial_layout
best_d = min(best_d, d)
if best_circ is None:
return False, None, None, None, False
return True, best_circ, best_d, best_layout, False
|
def layer_permutation(self, layer_partition, layout, qubit_subset):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
The layout is a dict mapping qubits in the circuit to qubits in the
coupling graph and represents the current positions of the data.
The qubit_subset is the subset of qubits in the coupling graph that
we have chosen to map into.
The coupling is a CouplingGraph.
TRIALS is the number of attempts the randomized algorithm makes.
Returns: success_flag, best_circ, best_d, best_layout, trivial_flag
If success_flag is True, then best_circ contains a DAGCircuit with
the swap circuit, best_d contains the depth of the swap circuit, and
best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
"""
if self.seed is None:
self.seed = np.random.randint(0, np.iinfo(np.int32).max)
rng = np.random.RandomState(self.seed)
rev_layout = {b: a for a, b in layout.items()}
gates = []
for layer in layer_partition:
if len(layer) > 2:
raise TranspilerError("Layer contains >2 qubit gates")
elif len(layer) == 2:
gates.append(tuple(layer))
# Can we already apply the gates?
dist = sum([self.coupling_map.distance(layout[g[0]][1], layout[g[1]][1]) for g in gates])
if dist == len(gates):
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(self.coupling_map.size(), "q"))
return True, circ, 0, layout, bool(gates)
# Begin loop over trials of randomized algorithm
n = self.coupling_map.size()
best_d = sys.maxsize # initialize best depth
best_circ = None # initialize best swap circuit
best_layout = None # initialize best final layout
QR = QuantumRegister(self.coupling_map.size(), "q")
for _ in range(self.trials):
trial_layout = layout.copy()
rev_trial_layout = rev_layout.copy()
# SWAP circuit constructed this trial
trial_circ = DAGCircuit()
trial_circ.add_qreg(QR)
# Compute Sergey's randomized distance
xi = {}
for i in self.coupling_map.physical_qubits:
xi[(QR, i)] = {}
for i in self.coupling_map.physical_qubits:
i = (QR, i)
for j in self.coupling_map.physical_qubits:
j = (QR, j)
scale = 1 + rng.normal(0, 1 / n)
xi[i][j] = scale * self.coupling_map.distance(i[1], j[1]) ** 2
xi[j][i] = xi[i][j]
# Loop over depths d up to a max depth of 2n+1
d = 1
# Circuit for this swap slice
circ = DAGCircuit()
circ.add_qreg(QR)
# Identity wire-map for composing the circuits
identity_wire_map = {(QR, j): (QR, j) for j in range(n)}
while d < 2 * n + 1:
# Set of available qubits
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]]
for g in gates])
# Try to decrease objective function
progress_made = False
# Loop over edges of coupling graph
for e in self.coupling_map.get_edges():
e = [(QR, edge) for edge in e]
# Are the qubits available?
if e[0] in qubit_set and e[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout[rev_trial_layout[e[0]]] = e[1]
new_layout[rev_trial_layout[e[1]]] = e[0]
rev_new_layout = rev_trial_layout.copy()
rev_new_layout[e[0]] = rev_trial_layout[e[1]]
rev_new_layout[e[1]] = rev_trial_layout[e[0]]
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]]
for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
progress_made = True
min_cost = new_cost
opt_layout = new_layout
rev_opt_layout = rev_new_layout
opt_edge = e
# Were there any good choices?
if progress_made:
qubit_set.remove(opt_edge[0])
qubit_set.remove(opt_edge[1])
trial_layout = opt_layout
rev_trial_layout = rev_opt_layout
circ.apply_operation_back(
SwapGate(),
[(opt_edge[0][0], opt_edge[0][1]), (opt_edge[1][0], opt_edge[1][1])],
[])
else:
break
# We have either run out of qubits or failed to improve
# Compute the coupling graph distance_qubits
dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],
trial_layout[g[1]][1]) for g in gates])
# If all gates can be applied now, we are finished
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
trial_circ.compose_back(circ, identity_wire_map)
break
# Increment the depth
d += 1
# Either we have succeeded at some depth d < dmax or failed
dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],
trial_layout[g[1]][1]) for g in gates])
if dist == len(gates):
if d < best_d:
best_circ = trial_circ
best_layout = trial_layout
best_d = min(best_d, d)
if best_circ is None:
return False, None, None, None, False
return True, best_circ, best_d, best_layout, False
|
[
"Find",
"a",
"swap",
"circuit",
"that",
"implements",
"a",
"permutation",
"for",
"this",
"layer",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/legacy_swap.py#L206-L355
|
[
"def",
"layer_permutation",
"(",
"self",
",",
"layer_partition",
",",
"layout",
",",
"qubit_subset",
")",
":",
"if",
"self",
".",
"seed",
"is",
"None",
":",
"self",
".",
"seed",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"np",
".",
"iinfo",
"(",
"np",
".",
"int32",
")",
".",
"max",
")",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"self",
".",
"seed",
")",
"rev_layout",
"=",
"{",
"b",
":",
"a",
"for",
"a",
",",
"b",
"in",
"layout",
".",
"items",
"(",
")",
"}",
"gates",
"=",
"[",
"]",
"for",
"layer",
"in",
"layer_partition",
":",
"if",
"len",
"(",
"layer",
")",
">",
"2",
":",
"raise",
"TranspilerError",
"(",
"\"Layer contains >2 qubit gates\"",
")",
"elif",
"len",
"(",
"layer",
")",
"==",
"2",
":",
"gates",
".",
"append",
"(",
"tuple",
"(",
"layer",
")",
")",
"# Can we already apply the gates?",
"dist",
"=",
"sum",
"(",
"[",
"self",
".",
"coupling_map",
".",
"distance",
"(",
"layout",
"[",
"g",
"[",
"0",
"]",
"]",
"[",
"1",
"]",
",",
"layout",
"[",
"g",
"[",
"1",
"]",
"]",
"[",
"1",
"]",
")",
"for",
"g",
"in",
"gates",
"]",
")",
"if",
"dist",
"==",
"len",
"(",
"gates",
")",
":",
"circ",
"=",
"DAGCircuit",
"(",
")",
"circ",
".",
"add_qreg",
"(",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"\"q\"",
")",
")",
"return",
"True",
",",
"circ",
",",
"0",
",",
"layout",
",",
"bool",
"(",
"gates",
")",
"# Begin loop over trials of randomized algorithm",
"n",
"=",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
"best_d",
"=",
"sys",
".",
"maxsize",
"# initialize best depth",
"best_circ",
"=",
"None",
"# initialize best swap circuit",
"best_layout",
"=",
"None",
"# initialize best final layout",
"QR",
"=",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"\"q\"",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"trials",
")",
":",
"trial_layout",
"=",
"layout",
".",
"copy",
"(",
")",
"rev_trial_layout",
"=",
"rev_layout",
".",
"copy",
"(",
")",
"# SWAP circuit constructed this trial",
"trial_circ",
"=",
"DAGCircuit",
"(",
")",
"trial_circ",
".",
"add_qreg",
"(",
"QR",
")",
"# Compute Sergey's randomized distance",
"xi",
"=",
"{",
"}",
"for",
"i",
"in",
"self",
".",
"coupling_map",
".",
"physical_qubits",
":",
"xi",
"[",
"(",
"QR",
",",
"i",
")",
"]",
"=",
"{",
"}",
"for",
"i",
"in",
"self",
".",
"coupling_map",
".",
"physical_qubits",
":",
"i",
"=",
"(",
"QR",
",",
"i",
")",
"for",
"j",
"in",
"self",
".",
"coupling_map",
".",
"physical_qubits",
":",
"j",
"=",
"(",
"QR",
",",
"j",
")",
"scale",
"=",
"1",
"+",
"rng",
".",
"normal",
"(",
"0",
",",
"1",
"/",
"n",
")",
"xi",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"scale",
"*",
"self",
".",
"coupling_map",
".",
"distance",
"(",
"i",
"[",
"1",
"]",
",",
"j",
"[",
"1",
"]",
")",
"**",
"2",
"xi",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"xi",
"[",
"i",
"]",
"[",
"j",
"]",
"# Loop over depths d up to a max depth of 2n+1",
"d",
"=",
"1",
"# Circuit for this swap slice",
"circ",
"=",
"DAGCircuit",
"(",
")",
"circ",
".",
"add_qreg",
"(",
"QR",
")",
"# Identity wire-map for composing the circuits",
"identity_wire_map",
"=",
"{",
"(",
"QR",
",",
"j",
")",
":",
"(",
"QR",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"n",
")",
"}",
"while",
"d",
"<",
"2",
"*",
"n",
"+",
"1",
":",
"# Set of available qubits",
"qubit_set",
"=",
"set",
"(",
"qubit_subset",
")",
"# While there are still qubits available",
"while",
"qubit_set",
":",
"# Compute the objective function",
"min_cost",
"=",
"sum",
"(",
"[",
"xi",
"[",
"trial_layout",
"[",
"g",
"[",
"0",
"]",
"]",
"]",
"[",
"trial_layout",
"[",
"g",
"[",
"1",
"]",
"]",
"]",
"for",
"g",
"in",
"gates",
"]",
")",
"# Try to decrease objective function",
"progress_made",
"=",
"False",
"# Loop over edges of coupling graph",
"for",
"e",
"in",
"self",
".",
"coupling_map",
".",
"get_edges",
"(",
")",
":",
"e",
"=",
"[",
"(",
"QR",
",",
"edge",
")",
"for",
"edge",
"in",
"e",
"]",
"# Are the qubits available?",
"if",
"e",
"[",
"0",
"]",
"in",
"qubit_set",
"and",
"e",
"[",
"1",
"]",
"in",
"qubit_set",
":",
"# Try this edge to reduce the cost",
"new_layout",
"=",
"trial_layout",
".",
"copy",
"(",
")",
"new_layout",
"[",
"rev_trial_layout",
"[",
"e",
"[",
"0",
"]",
"]",
"]",
"=",
"e",
"[",
"1",
"]",
"new_layout",
"[",
"rev_trial_layout",
"[",
"e",
"[",
"1",
"]",
"]",
"]",
"=",
"e",
"[",
"0",
"]",
"rev_new_layout",
"=",
"rev_trial_layout",
".",
"copy",
"(",
")",
"rev_new_layout",
"[",
"e",
"[",
"0",
"]",
"]",
"=",
"rev_trial_layout",
"[",
"e",
"[",
"1",
"]",
"]",
"rev_new_layout",
"[",
"e",
"[",
"1",
"]",
"]",
"=",
"rev_trial_layout",
"[",
"e",
"[",
"0",
"]",
"]",
"# Compute the objective function",
"new_cost",
"=",
"sum",
"(",
"[",
"xi",
"[",
"new_layout",
"[",
"g",
"[",
"0",
"]",
"]",
"]",
"[",
"new_layout",
"[",
"g",
"[",
"1",
"]",
"]",
"]",
"for",
"g",
"in",
"gates",
"]",
")",
"# Record progress if we succceed",
"if",
"new_cost",
"<",
"min_cost",
":",
"progress_made",
"=",
"True",
"min_cost",
"=",
"new_cost",
"opt_layout",
"=",
"new_layout",
"rev_opt_layout",
"=",
"rev_new_layout",
"opt_edge",
"=",
"e",
"# Were there any good choices?",
"if",
"progress_made",
":",
"qubit_set",
".",
"remove",
"(",
"opt_edge",
"[",
"0",
"]",
")",
"qubit_set",
".",
"remove",
"(",
"opt_edge",
"[",
"1",
"]",
")",
"trial_layout",
"=",
"opt_layout",
"rev_trial_layout",
"=",
"rev_opt_layout",
"circ",
".",
"apply_operation_back",
"(",
"SwapGate",
"(",
")",
",",
"[",
"(",
"opt_edge",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"opt_edge",
"[",
"0",
"]",
"[",
"1",
"]",
")",
",",
"(",
"opt_edge",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"opt_edge",
"[",
"1",
"]",
"[",
"1",
"]",
")",
"]",
",",
"[",
"]",
")",
"else",
":",
"break",
"# We have either run out of qubits or failed to improve",
"# Compute the coupling graph distance_qubits",
"dist",
"=",
"sum",
"(",
"[",
"self",
".",
"coupling_map",
".",
"distance",
"(",
"trial_layout",
"[",
"g",
"[",
"0",
"]",
"]",
"[",
"1",
"]",
",",
"trial_layout",
"[",
"g",
"[",
"1",
"]",
"]",
"[",
"1",
"]",
")",
"for",
"g",
"in",
"gates",
"]",
")",
"# If all gates can be applied now, we are finished",
"# Otherwise we need to consider a deeper swap circuit",
"if",
"dist",
"==",
"len",
"(",
"gates",
")",
":",
"trial_circ",
".",
"compose_back",
"(",
"circ",
",",
"identity_wire_map",
")",
"break",
"# Increment the depth",
"d",
"+=",
"1",
"# Either we have succeeded at some depth d < dmax or failed",
"dist",
"=",
"sum",
"(",
"[",
"self",
".",
"coupling_map",
".",
"distance",
"(",
"trial_layout",
"[",
"g",
"[",
"0",
"]",
"]",
"[",
"1",
"]",
",",
"trial_layout",
"[",
"g",
"[",
"1",
"]",
"]",
"[",
"1",
"]",
")",
"for",
"g",
"in",
"gates",
"]",
")",
"if",
"dist",
"==",
"len",
"(",
"gates",
")",
":",
"if",
"d",
"<",
"best_d",
":",
"best_circ",
"=",
"trial_circ",
"best_layout",
"=",
"trial_layout",
"best_d",
"=",
"min",
"(",
"best_d",
",",
"d",
")",
"if",
"best_circ",
"is",
"None",
":",
"return",
"False",
",",
"None",
",",
"None",
",",
"None",
",",
"False",
"return",
"True",
",",
"best_circ",
",",
"best_d",
",",
"best_layout",
",",
"False"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LegacySwap.swap_mapper_layer_update
|
Update the QASM string for an iteration of swap_mapper.
i = layer number
first_layer = True if this is the first layer with multi-qubit gates
best_layout = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
|
qiskit/transpiler/passes/mapping/legacy_swap.py
|
def swap_mapper_layer_update(self, i, first_layer, best_layout, best_d,
best_circ, layer_list):
"""Update the QASM string for an iteration of swap_mapper.
i = layer number
first_layer = True if this is the first layer with multi-qubit gates
best_layout = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
"""
layout = best_layout
dagcircuit_output = DAGCircuit()
QR = QuantumRegister(self.coupling_map.size(), 'q')
dagcircuit_output.add_qreg(QR)
# Identity wire-map for composing the circuits
identity_wire_map = {(QR, j): (QR, j) for j in range(self.coupling_map.size())}
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
# Output all layers up to this point
for j in range(i + 1):
dagcircuit_output.compose_back(layer_list[j]["graph"], layout)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_d > 0:
dagcircuit_output.compose_back(best_circ, identity_wire_map)
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], layout)
return dagcircuit_output
|
def swap_mapper_layer_update(self, i, first_layer, best_layout, best_d,
best_circ, layer_list):
"""Update the QASM string for an iteration of swap_mapper.
i = layer number
first_layer = True if this is the first layer with multi-qubit gates
best_layout = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
"""
layout = best_layout
dagcircuit_output = DAGCircuit()
QR = QuantumRegister(self.coupling_map.size(), 'q')
dagcircuit_output.add_qreg(QR)
# Identity wire-map for composing the circuits
identity_wire_map = {(QR, j): (QR, j) for j in range(self.coupling_map.size())}
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
# Output all layers up to this point
for j in range(i + 1):
dagcircuit_output.compose_back(layer_list[j]["graph"], layout)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_d > 0:
dagcircuit_output.compose_back(best_circ, identity_wire_map)
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], layout)
return dagcircuit_output
|
[
"Update",
"the",
"QASM",
"string",
"for",
"an",
"iteration",
"of",
"swap_mapper",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/legacy_swap.py#L357-L392
|
[
"def",
"swap_mapper_layer_update",
"(",
"self",
",",
"i",
",",
"first_layer",
",",
"best_layout",
",",
"best_d",
",",
"best_circ",
",",
"layer_list",
")",
":",
"layout",
"=",
"best_layout",
"dagcircuit_output",
"=",
"DAGCircuit",
"(",
")",
"QR",
"=",
"QuantumRegister",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
",",
"'q'",
")",
"dagcircuit_output",
".",
"add_qreg",
"(",
"QR",
")",
"# Identity wire-map for composing the circuits",
"identity_wire_map",
"=",
"{",
"(",
"QR",
",",
"j",
")",
":",
"(",
"QR",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"coupling_map",
".",
"size",
"(",
")",
")",
"}",
"# If this is the first layer with multi-qubit gates,",
"# output all layers up to this point and ignore any",
"# swap gates. Set the initial layout.",
"if",
"first_layer",
":",
"# Output all layers up to this point",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
")",
":",
"dagcircuit_output",
".",
"compose_back",
"(",
"layer_list",
"[",
"j",
"]",
"[",
"\"graph\"",
"]",
",",
"layout",
")",
"# Otherwise, we output the current layer and the associated swap gates.",
"else",
":",
"# Output any swaps",
"if",
"best_d",
">",
"0",
":",
"dagcircuit_output",
".",
"compose_back",
"(",
"best_circ",
",",
"identity_wire_map",
")",
"# Output this layer",
"dagcircuit_output",
".",
"compose_back",
"(",
"layer_list",
"[",
"i",
"]",
"[",
"\"graph\"",
"]",
",",
"layout",
")",
"return",
"dagcircuit_output"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Prefix.real
|
Return the correspond floating point number.
|
qiskit/qasm/node/prefix.py
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
operation = self.children[0].operation()
expr = self.children[1].real(nested_scope)
return operation(expr)
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
operation = self.children[0].operation()
expr = self.children[1].real(nested_scope)
return operation(expr)
|
[
"Return",
"the",
"correspond",
"floating",
"point",
"number",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/prefix.py#L36-L40
|
[
"def",
"real",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"operation",
"=",
"self",
".",
"children",
"[",
"0",
"]",
".",
"operation",
"(",
")",
"expr",
"=",
"self",
".",
"children",
"[",
"1",
"]",
".",
"real",
"(",
"nested_scope",
")",
"return",
"operation",
"(",
"expr",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Prefix.sym
|
Return the correspond symbolic number.
|
qiskit/qasm/node/prefix.py
|
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
expr = self.children[1].sym(nested_scope)
return operation(expr)
|
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
expr = self.children[1].sym(nested_scope)
return operation(expr)
|
[
"Return",
"the",
"correspond",
"symbolic",
"number",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/prefix.py#L42-L46
|
[
"def",
"sym",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"operation",
"=",
"self",
".",
"children",
"[",
"0",
"]",
".",
"operation",
"(",
")",
"expr",
"=",
"self",
".",
"children",
"[",
"1",
"]",
".",
"sym",
"(",
"nested_scope",
")",
"return",
"operation",
"(",
"expr",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_separate_bitstring
|
Separate a bitstring according to the registers defined in the result header.
|
qiskit/result/postprocess.py
|
def _separate_bitstring(bitstring, creg_sizes):
"""Separate a bitstring according to the registers defined in the result header."""
substrings = []
running_index = 0
for _, size in reversed(creg_sizes):
substrings.append(bitstring[running_index: running_index + size])
running_index += size
return ' '.join(substrings)
|
def _separate_bitstring(bitstring, creg_sizes):
"""Separate a bitstring according to the registers defined in the result header."""
substrings = []
running_index = 0
for _, size in reversed(creg_sizes):
substrings.append(bitstring[running_index: running_index + size])
running_index += size
return ' '.join(substrings)
|
[
"Separate",
"a",
"bitstring",
"according",
"to",
"the",
"registers",
"defined",
"in",
"the",
"result",
"header",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L26-L33
|
[
"def",
"_separate_bitstring",
"(",
"bitstring",
",",
"creg_sizes",
")",
":",
"substrings",
"=",
"[",
"]",
"running_index",
"=",
"0",
"for",
"_",
",",
"size",
"in",
"reversed",
"(",
"creg_sizes",
")",
":",
"substrings",
".",
"append",
"(",
"bitstring",
"[",
"running_index",
":",
"running_index",
"+",
"size",
"]",
")",
"running_index",
"+=",
"size",
"return",
"' '",
".",
"join",
"(",
"substrings",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_counts_memory
|
Format a single bitstring (memory) from a single shot experiment.
- The hexadecimals are expanded to bitstrings
- Spaces are inserted at register divisions.
Args:
shot_memory (str): result of a single experiment.
header (dict): the experiment header dictionary containing
useful information for postprocessing. creg_sizes
are a nested list where the inner element is a list
of creg name, creg size pairs. memory_slots is an integers
specifying the number of total memory_slots in the experiment.
Returns:
dict: a formatted memory
|
qiskit/result/postprocess.py
|
def format_counts_memory(shot_memory, header=None):
"""
Format a single bitstring (memory) from a single shot experiment.
- The hexadecimals are expanded to bitstrings
- Spaces are inserted at register divisions.
Args:
shot_memory (str): result of a single experiment.
header (dict): the experiment header dictionary containing
useful information for postprocessing. creg_sizes
are a nested list where the inner element is a list
of creg name, creg size pairs. memory_slots is an integers
specifying the number of total memory_slots in the experiment.
Returns:
dict: a formatted memory
"""
if shot_memory.startswith('0x'):
shot_memory = _hex_to_bin(shot_memory)
if header:
creg_sizes = header.get('creg_sizes', None)
memory_slots = header.get('memory_slots', None)
if memory_slots:
shot_memory = _pad_zeros(shot_memory, memory_slots)
if creg_sizes and memory_slots:
shot_memory = _separate_bitstring(shot_memory, creg_sizes)
return shot_memory
|
def format_counts_memory(shot_memory, header=None):
"""
Format a single bitstring (memory) from a single shot experiment.
- The hexadecimals are expanded to bitstrings
- Spaces are inserted at register divisions.
Args:
shot_memory (str): result of a single experiment.
header (dict): the experiment header dictionary containing
useful information for postprocessing. creg_sizes
are a nested list where the inner element is a list
of creg name, creg size pairs. memory_slots is an integers
specifying the number of total memory_slots in the experiment.
Returns:
dict: a formatted memory
"""
if shot_memory.startswith('0x'):
shot_memory = _hex_to_bin(shot_memory)
if header:
creg_sizes = header.get('creg_sizes', None)
memory_slots = header.get('memory_slots', None)
if memory_slots:
shot_memory = _pad_zeros(shot_memory, memory_slots)
if creg_sizes and memory_slots:
shot_memory = _separate_bitstring(shot_memory, creg_sizes)
return shot_memory
|
[
"Format",
"a",
"single",
"bitstring",
"(",
"memory",
")",
"from",
"a",
"single",
"shot",
"experiment",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L36-L64
|
[
"def",
"format_counts_memory",
"(",
"shot_memory",
",",
"header",
"=",
"None",
")",
":",
"if",
"shot_memory",
".",
"startswith",
"(",
"'0x'",
")",
":",
"shot_memory",
"=",
"_hex_to_bin",
"(",
"shot_memory",
")",
"if",
"header",
":",
"creg_sizes",
"=",
"header",
".",
"get",
"(",
"'creg_sizes'",
",",
"None",
")",
"memory_slots",
"=",
"header",
".",
"get",
"(",
"'memory_slots'",
",",
"None",
")",
"if",
"memory_slots",
":",
"shot_memory",
"=",
"_pad_zeros",
"(",
"shot_memory",
",",
"memory_slots",
")",
"if",
"creg_sizes",
"and",
"memory_slots",
":",
"shot_memory",
"=",
"_separate_bitstring",
"(",
"shot_memory",
",",
"creg_sizes",
")",
"return",
"shot_memory"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
_list_to_complex_array
|
Convert nested list of shape (..., 2) to complex numpy array with shape (...)
Args:
complex_list (list): List to convert.
Returns:
np.ndarray: Complex numpy aray
Raises:
QiskitError: If inner most array of input nested list is not of length 2.
|
qiskit/result/postprocess.py
|
def _list_to_complex_array(complex_list):
"""Convert nested list of shape (..., 2) to complex numpy array with shape (...)
Args:
complex_list (list): List to convert.
Returns:
np.ndarray: Complex numpy aray
Raises:
QiskitError: If inner most array of input nested list is not of length 2.
"""
arr = np.asarray(complex_list, dtype=np.complex_)
if not arr.shape[-1] == 2:
raise QiskitError('Inner most nested list is not of length 2.')
return arr[..., 0] + 1j*arr[..., 1]
|
def _list_to_complex_array(complex_list):
"""Convert nested list of shape (..., 2) to complex numpy array with shape (...)
Args:
complex_list (list): List to convert.
Returns:
np.ndarray: Complex numpy aray
Raises:
QiskitError: If inner most array of input nested list is not of length 2.
"""
arr = np.asarray(complex_list, dtype=np.complex_)
if not arr.shape[-1] == 2:
raise QiskitError('Inner most nested list is not of length 2.')
return arr[..., 0] + 1j*arr[..., 1]
|
[
"Convert",
"nested",
"list",
"of",
"shape",
"(",
"...",
"2",
")",
"to",
"complex",
"numpy",
"array",
"with",
"shape",
"(",
"...",
")"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L67-L83
|
[
"def",
"_list_to_complex_array",
"(",
"complex_list",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"complex_list",
",",
"dtype",
"=",
"np",
".",
"complex_",
")",
"if",
"not",
"arr",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"2",
":",
"raise",
"QiskitError",
"(",
"'Inner most nested list is not of length 2.'",
")",
"return",
"arr",
"[",
"...",
",",
"0",
"]",
"+",
"1j",
"*",
"arr",
"[",
"...",
",",
"1",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_level_0_memory
|
Format an experiment result memory object for measurement level 0.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 0 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
indicies.
|
qiskit/result/postprocess.py
|
def format_level_0_memory(memory):
""" Format an experiment result memory object for measurement level 0.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 0 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
indicies.
"""
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 2 <= len(formatted_memory.shape) <= 3:
raise QiskitError('Level zero memory is not of correct shape.')
return formatted_memory
|
def format_level_0_memory(memory):
""" Format an experiment result memory object for measurement level 0.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 0 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
indicies.
"""
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 2 <= len(formatted_memory.shape) <= 3:
raise QiskitError('Level zero memory is not of correct shape.')
return formatted_memory
|
[
"Format",
"an",
"experiment",
"result",
"memory",
"object",
"for",
"measurement",
"level",
"0",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L86-L104
|
[
"def",
"format_level_0_memory",
"(",
"memory",
")",
":",
"formatted_memory",
"=",
"_list_to_complex_array",
"(",
"memory",
")",
"# infer meas_return from shape of returned data.",
"if",
"not",
"2",
"<=",
"len",
"(",
"formatted_memory",
".",
"shape",
")",
"<=",
"3",
":",
"raise",
"QiskitError",
"(",
"'Level zero memory is not of correct shape.'",
")",
"return",
"formatted_memory"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_level_1_memory
|
Format an experiment result memory object for measurement level 1.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 1 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
indicies.
|
qiskit/result/postprocess.py
|
def format_level_1_memory(memory):
""" Format an experiment result memory object for measurement level 1.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 1 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
indicies.
"""
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 1 <= len(formatted_memory.shape) <= 2:
raise QiskitError('Level one memory is not of correct shape.')
return formatted_memory
|
def format_level_1_memory(memory):
""" Format an experiment result memory object for measurement level 1.
Args:
memory (list): Memory from experiment with `meas_level==1`. `avg` or
`single` will be inferred from shape of result memory.
Returns:
np.ndarray: Measurement level 1 complex numpy array
Raises:
QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
indicies.
"""
formatted_memory = _list_to_complex_array(memory)
# infer meas_return from shape of returned data.
if not 1 <= len(formatted_memory.shape) <= 2:
raise QiskitError('Level one memory is not of correct shape.')
return formatted_memory
|
[
"Format",
"an",
"experiment",
"result",
"memory",
"object",
"for",
"measurement",
"level",
"1",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L107-L125
|
[
"def",
"format_level_1_memory",
"(",
"memory",
")",
":",
"formatted_memory",
"=",
"_list_to_complex_array",
"(",
"memory",
")",
"# infer meas_return from shape of returned data.",
"if",
"not",
"1",
"<=",
"len",
"(",
"formatted_memory",
".",
"shape",
")",
"<=",
"2",
":",
"raise",
"QiskitError",
"(",
"'Level one memory is not of correct shape.'",
")",
"return",
"formatted_memory"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_level_2_memory
|
Format an experiment result memory object for measurement level 2.
Args:
memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
list[str]: List of bitstrings
|
qiskit/result/postprocess.py
|
def format_level_2_memory(memory, header=None):
""" Format an experiment result memory object for measurement level 2.
Args:
memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
list[str]: List of bitstrings
"""
memory_list = []
for shot_memory in memory:
memory_list.append(format_counts_memory(shot_memory, header))
return memory_list
|
def format_level_2_memory(memory, header=None):
""" Format an experiment result memory object for measurement level 2.
Args:
memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
list[str]: List of bitstrings
"""
memory_list = []
for shot_memory in memory:
memory_list.append(format_counts_memory(shot_memory, header))
return memory_list
|
[
"Format",
"an",
"experiment",
"result",
"memory",
"object",
"for",
"measurement",
"level",
"2",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L128-L142
|
[
"def",
"format_level_2_memory",
"(",
"memory",
",",
"header",
"=",
"None",
")",
":",
"memory_list",
"=",
"[",
"]",
"for",
"shot_memory",
"in",
"memory",
":",
"memory_list",
".",
"append",
"(",
"format_counts_memory",
"(",
"shot_memory",
",",
"header",
")",
")",
"return",
"memory_list"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_counts
|
Format a single experiment result coming from backend to present
to the Qiskit user.
Args:
counts (dict): counts histogram of multiple shots
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
dict: a formatted counts
|
qiskit/result/postprocess.py
|
def format_counts(counts, header=None):
"""Format a single experiment result coming from backend to present
to the Qiskit user.
Args:
counts (dict): counts histogram of multiple shots
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
dict: a formatted counts
"""
counts_dict = {}
for key, val in counts.items():
key = format_counts_memory(key, header)
counts_dict[key] = val
return counts_dict
|
def format_counts(counts, header=None):
"""Format a single experiment result coming from backend to present
to the Qiskit user.
Args:
counts (dict): counts histogram of multiple shots
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
dict: a formatted counts
"""
counts_dict = {}
for key, val in counts.items():
key = format_counts_memory(key, header)
counts_dict[key] = val
return counts_dict
|
[
"Format",
"a",
"single",
"experiment",
"result",
"coming",
"from",
"backend",
"to",
"present",
"to",
"the",
"Qiskit",
"user",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L145-L161
|
[
"def",
"format_counts",
"(",
"counts",
",",
"header",
"=",
"None",
")",
":",
"counts_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"counts",
".",
"items",
"(",
")",
":",
"key",
"=",
"format_counts_memory",
"(",
"key",
",",
"header",
")",
"counts_dict",
"[",
"key",
"]",
"=",
"val",
"return",
"counts_dict"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_statevector
|
Format statevector coming from the backend to present to the Qiskit user.
Args:
vec (list): a list of [re, im] complex numbers.
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[complex]: a list of python complex numbers.
|
qiskit/result/postprocess.py
|
def format_statevector(vec, decimals=None):
"""Format statevector coming from the backend to present to the Qiskit user.
Args:
vec (list): a list of [re, im] complex numbers.
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[complex]: a list of python complex numbers.
"""
num_basis = len(vec)
vec_complex = np.zeros(num_basis, dtype=complex)
for i in range(num_basis):
vec_complex[i] = vec[i][0] + 1j * vec[i][1]
if decimals:
vec_complex = np.around(vec_complex, decimals=decimals)
return vec_complex
|
def format_statevector(vec, decimals=None):
"""Format statevector coming from the backend to present to the Qiskit user.
Args:
vec (list): a list of [re, im] complex numbers.
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[complex]: a list of python complex numbers.
"""
num_basis = len(vec)
vec_complex = np.zeros(num_basis, dtype=complex)
for i in range(num_basis):
vec_complex[i] = vec[i][0] + 1j * vec[i][1]
if decimals:
vec_complex = np.around(vec_complex, decimals=decimals)
return vec_complex
|
[
"Format",
"statevector",
"coming",
"from",
"the",
"backend",
"to",
"present",
"to",
"the",
"Qiskit",
"user",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L164-L181
|
[
"def",
"format_statevector",
"(",
"vec",
",",
"decimals",
"=",
"None",
")",
":",
"num_basis",
"=",
"len",
"(",
"vec",
")",
"vec_complex",
"=",
"np",
".",
"zeros",
"(",
"num_basis",
",",
"dtype",
"=",
"complex",
")",
"for",
"i",
"in",
"range",
"(",
"num_basis",
")",
":",
"vec_complex",
"[",
"i",
"]",
"=",
"vec",
"[",
"i",
"]",
"[",
"0",
"]",
"+",
"1j",
"*",
"vec",
"[",
"i",
"]",
"[",
"1",
"]",
"if",
"decimals",
":",
"vec_complex",
"=",
"np",
".",
"around",
"(",
"vec_complex",
",",
"decimals",
"=",
"decimals",
")",
"return",
"vec_complex"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
format_unitary
|
Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[list[complex]]: a matrix of complex numbers
|
qiskit/result/postprocess.py
|
def format_unitary(mat, decimals=None):
"""Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[list[complex]]: a matrix of complex numbers
"""
num_basis = len(mat)
mat_complex = np.zeros((num_basis, num_basis), dtype=complex)
for i, vec in enumerate(mat):
mat_complex[i] = format_statevector(vec, decimals)
return mat_complex
|
def format_unitary(mat, decimals=None):
"""Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[list[complex]]: a matrix of complex numbers
"""
num_basis = len(mat)
mat_complex = np.zeros((num_basis, num_basis), dtype=complex)
for i, vec in enumerate(mat):
mat_complex[i] = format_statevector(vec, decimals)
return mat_complex
|
[
"Format",
"unitary",
"coming",
"from",
"the",
"backend",
"to",
"present",
"to",
"the",
"Qiskit",
"user",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/result/postprocess.py#L184-L199
|
[
"def",
"format_unitary",
"(",
"mat",
",",
"decimals",
"=",
"None",
")",
":",
"num_basis",
"=",
"len",
"(",
"mat",
")",
"mat_complex",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_basis",
",",
"num_basis",
")",
",",
"dtype",
"=",
"complex",
")",
"for",
"i",
",",
"vec",
"in",
"enumerate",
"(",
"mat",
")",
":",
"mat_complex",
"[",
"i",
"]",
"=",
"format_statevector",
"(",
"vec",
",",
"decimals",
")",
"return",
"mat_complex"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
requires_submit
|
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
|
qiskit/providers/basicaer/basicaerjob.py
|
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
|
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
|
[
"Decorator",
"to",
"ensure",
"that",
"a",
"submit",
"has",
"been",
"performed",
"before",
"calling",
"the",
"method",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaerjob.py#L21-L37
|
[
"def",
"requires_submit",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_future",
"is",
"None",
":",
"raise",
"JobError",
"(",
"\"Job not submitted yet!. You have to .submit() first!\"",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
BasicAerJob.submit
|
Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
|
qiskit/providers/basicaer/basicaerjob.py
|
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
|
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
|
[
"Submit",
"the",
"job",
"to",
"the",
"backend",
"for",
"execution",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaerjob.py#L58-L71
|
[
"def",
"submit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_future",
"is",
"not",
"None",
":",
"raise",
"JobError",
"(",
"\"We have already submitted the job!\"",
")",
"validate_qobj_against_schema",
"(",
"self",
".",
"_qobj",
")",
"self",
".",
"_future",
"=",
"self",
".",
"_executor",
".",
"submit",
"(",
"self",
".",
"_fn",
",",
"self",
".",
"_job_id",
",",
"self",
".",
"_qobj",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
BasicAerJob.status
|
Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
|
qiskit/providers/basicaer/basicaerjob.py
|
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
# Note: There is an undocumented Future state: PENDING, that seems to show up when
# the job is enqueued, waiting for someone to pick it up. We need to deal with this
# state but there's no public API for it, so we are assuming that if the job is not
# in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
|
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
# Note: There is an undocumented Future state: PENDING, that seems to show up when
# the job is enqueued, waiting for someone to pick it up. We need to deal with this
# state but there's no public API for it, so we are assuming that if the job is not
# in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
|
[
"Gets",
"the",
"status",
"of",
"the",
"job",
"by",
"querying",
"the",
"Python",
"s",
"future"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaerjob.py#L98-L122
|
[
"def",
"status",
"(",
"self",
")",
":",
"# The order is important here",
"if",
"self",
".",
"_future",
".",
"running",
"(",
")",
":",
"_status",
"=",
"JobStatus",
".",
"RUNNING",
"elif",
"self",
".",
"_future",
".",
"cancelled",
"(",
")",
":",
"_status",
"=",
"JobStatus",
".",
"CANCELLED",
"elif",
"self",
".",
"_future",
".",
"done",
"(",
")",
":",
"_status",
"=",
"JobStatus",
".",
"DONE",
"if",
"self",
".",
"_future",
".",
"exception",
"(",
")",
"is",
"None",
"else",
"JobStatus",
".",
"ERROR",
"else",
":",
"# Note: There is an undocumented Future state: PENDING, that seems to show up when",
"# the job is enqueued, waiting for someone to pick it up. We need to deal with this",
"# state but there's no public API for it, so we are assuming that if the job is not",
"# in any of the previous states, is PENDING, ergo INITIALIZING for us.",
"_status",
"=",
"JobStatus",
".",
"INITIALIZING",
"return",
"_status"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LoRange.includes
|
Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
|
qiskit/pulse/channels/pulse_channels.py
|
def includes(self, lo_freq: float) -> bool:
"""Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
"""
if self._lb <= lo_freq <= self._ub:
return True
return False
|
def includes(self, lo_freq: float) -> bool:
"""Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
"""
if self._lb <= lo_freq <= self._ub:
return True
return False
|
[
"Whether",
"lo_freq",
"is",
"within",
"the",
"LoRange",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/channels/pulse_channels.py#L25-L36
|
[
"def",
"includes",
"(",
"self",
",",
"lo_freq",
":",
"float",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_lb",
"<=",
"lo_freq",
"<=",
"self",
".",
"_ub",
":",
"return",
"True",
"return",
"False"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
iplot_bloch_multivector
|
Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size in pixels.
|
qiskit/visualization/interactive/iplot_blochsphere.py
|
def iplot_bloch_multivector(rho, figsize=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="bloch_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
data = $data;
dataValues = [];
for (var i = 0; i < data.length; i++) {
// Coordinates
var x = data[i][0];
var y = data[i][1];
var z = data[i][2];
var point = {'x': x,
'y': y,
'z': z};
dataValues.push(point);
}
require(["qVisualization"], function(qVisualizations) {
// Plot figure
qVisualizations.plotState("bloch_$divNumber",
"bloch",
dataValues,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
# Process data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
|
def iplot_bloch_multivector(rho, figsize=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="bloch_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
data = $data;
dataValues = [];
for (var i = 0; i < data.length; i++) {
// Coordinates
var x = data[i][0];
var y = data[i][1];
var z = data[i][2];
var point = {'x': x,
'y': y,
'z': z};
dataValues.push(point);
}
require(["qVisualization"], function(qVisualizations) {
// Plot figure
qVisualizations.plotState("bloch_$divNumber",
"bloch",
dataValues,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
# Process data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
|
[
"Create",
"a",
"bloch",
"sphere",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_blochsphere.py#L25-L105
|
[
"def",
"iplot_bloch_multivector",
"(",
"rho",
",",
"figsize",
"=",
"None",
")",
":",
"# HTML",
"html_template",
"=",
"Template",
"(",
"\"\"\"\n <p>\n <div id=\"content_$divNumber\" style=\"position: absolute; z-index: 1;\">\n <div id=\"bloch_$divNumber\"></div>\n </div>\n </p>\n \"\"\"",
")",
"# JavaScript",
"javascript_template",
"=",
"Template",
"(",
"\"\"\"\n <script>\n requirejs.config({\n paths: {\n qVisualization: \"https://qvisualization.mybluemix.net/q-visualizations\"\n }\n });\n data = $data;\n dataValues = [];\n for (var i = 0; i < data.length; i++) {\n // Coordinates\n var x = data[i][0];\n var y = data[i][1];\n var z = data[i][2];\n var point = {'x': x,\n 'y': y,\n 'z': z};\n dataValues.push(point);\n }\n\n require([\"qVisualization\"], function(qVisualizations) {\n // Plot figure\n qVisualizations.plotState(\"bloch_$divNumber\",\n \"bloch\",\n dataValues,\n $options);\n });\n </script>\n \"\"\"",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"if",
"figsize",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"else",
":",
"options",
"=",
"{",
"'width'",
":",
"figsize",
"[",
"0",
"]",
",",
"'height'",
":",
"figsize",
"[",
"1",
"]",
"}",
"# Process data and execute",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"bloch_data",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
"pauli_singles",
"=",
"[",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'X'",
")",
",",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'Y'",
")",
",",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'Z'",
")",
"]",
"bloch_state",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"np",
".",
"real",
"(",
"np",
".",
"trace",
"(",
"np",
".",
"dot",
"(",
"x",
".",
"to_matrix",
"(",
")",
",",
"rho",
")",
")",
")",
",",
"pauli_singles",
")",
")",
"bloch_data",
".",
"append",
"(",
"bloch_state",
")",
"div_number",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
"div_number",
"=",
"re",
".",
"sub",
"(",
"'[.]'",
",",
"''",
",",
"div_number",
")",
"html",
"=",
"html_template",
".",
"substitute",
"(",
"{",
"'divNumber'",
":",
"div_number",
"}",
")",
"javascript",
"=",
"javascript_template",
".",
"substitute",
"(",
"{",
"'data'",
":",
"bloch_data",
",",
"'divNumber'",
":",
"div_number",
",",
"'options'",
":",
"options",
"}",
")",
"display",
"(",
"HTML",
"(",
"html",
"+",
"javascript",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
parallel_map
|
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``values``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QiskitError: If user interrupts via keyboard.
Events:
terra.parallel.start: The collection of parallel tasks are about to start.
terra.parallel.update: One of the parallel task has finished.
terra.parallel.finish: All the parallel tasks have finished.
|
qiskit/tools/parallel.py
|
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``values``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QiskitError: If user interrupts via keyboard.
Events:
terra.parallel.start: The collection of parallel tasks are about to start.
terra.parallel.update: One of the parallel task has finished.
terra.parallel.finish: All the parallel tasks have finished.
"""
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
Publisher().publish("terra.parallel.start", len(values))
nfinished = [0]
def _callback(_):
nfinished[0] += 1
Publisher().publish("terra.parallel.done", nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
Publisher().publish("terra.parallel.finish")
raise QiskitError('Keyboard interrupt in parallel_map.')
Publisher().publish("terra.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
Publisher().publish("terra.parallel.finish")
return results
|
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``values``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QiskitError: If user interrupts via keyboard.
Events:
terra.parallel.start: The collection of parallel tasks are about to start.
terra.parallel.update: One of the parallel task has finished.
terra.parallel.finish: All the parallel tasks have finished.
"""
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
Publisher().publish("terra.parallel.start", len(values))
nfinished = [0]
def _callback(_):
nfinished[0] += 1
Publisher().publish("terra.parallel.done", nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
Publisher().publish("terra.parallel.finish")
raise QiskitError('Keyboard interrupt in parallel_map.')
Publisher().publish("terra.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
Publisher().publish("terra.parallel.finish")
return results
|
[
"Parallel",
"execution",
"of",
"a",
"mapping",
"of",
"values",
"to",
"the",
"function",
"task",
".",
"This",
"is",
"functionally",
"equivalent",
"to",
"::"
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/parallel.py#L60-L137
|
[
"def",
"parallel_map",
"(",
"task",
",",
"values",
",",
"task_args",
"=",
"tuple",
"(",
")",
",",
"task_kwargs",
"=",
"{",
"}",
",",
"# pylint: disable=W0102",
"num_processes",
"=",
"CPU_COUNT",
")",
":",
"if",
"len",
"(",
"values",
")",
"==",
"1",
":",
"return",
"[",
"task",
"(",
"values",
"[",
"0",
"]",
",",
"*",
"task_args",
",",
"*",
"*",
"task_kwargs",
")",
"]",
"Publisher",
"(",
")",
".",
"publish",
"(",
"\"terra.parallel.start\"",
",",
"len",
"(",
"values",
")",
")",
"nfinished",
"=",
"[",
"0",
"]",
"def",
"_callback",
"(",
"_",
")",
":",
"nfinished",
"[",
"0",
"]",
"+=",
"1",
"Publisher",
"(",
")",
".",
"publish",
"(",
"\"terra.parallel.done\"",
",",
"nfinished",
"[",
"0",
"]",
")",
"# Run in parallel if not Win and not in parallel already",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Windows'",
"and",
"num_processes",
">",
"1",
"and",
"os",
".",
"getenv",
"(",
"'QISKIT_IN_PARALLEL'",
")",
"==",
"'FALSE'",
":",
"os",
".",
"environ",
"[",
"'QISKIT_IN_PARALLEL'",
"]",
"=",
"'TRUE'",
"try",
":",
"pool",
"=",
"Pool",
"(",
"processes",
"=",
"num_processes",
")",
"async_res",
"=",
"[",
"pool",
".",
"apply_async",
"(",
"task",
",",
"(",
"value",
",",
")",
"+",
"task_args",
",",
"task_kwargs",
",",
"_callback",
")",
"for",
"value",
"in",
"values",
"]",
"while",
"not",
"all",
"(",
"[",
"item",
".",
"ready",
"(",
")",
"for",
"item",
"in",
"async_res",
"]",
")",
":",
"for",
"item",
"in",
"async_res",
":",
"item",
".",
"wait",
"(",
"timeout",
"=",
"0.1",
")",
"pool",
".",
"terminate",
"(",
")",
"pool",
".",
"join",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pool",
".",
"terminate",
"(",
")",
"pool",
".",
"join",
"(",
")",
"Publisher",
"(",
")",
".",
"publish",
"(",
"\"terra.parallel.finish\"",
")",
"raise",
"QiskitError",
"(",
"'Keyboard interrupt in parallel_map.'",
")",
"Publisher",
"(",
")",
".",
"publish",
"(",
"\"terra.parallel.finish\"",
")",
"os",
".",
"environ",
"[",
"'QISKIT_IN_PARALLEL'",
"]",
"=",
"'FALSE'",
"return",
"[",
"ar",
".",
"get",
"(",
")",
"for",
"ar",
"in",
"async_res",
"]",
"# Cannot do parallel on Windows , if another parallel_map is running in parallel,",
"# or len(values) == 1.",
"results",
"=",
"[",
"]",
"for",
"_",
",",
"value",
"in",
"enumerate",
"(",
"values",
")",
":",
"result",
"=",
"task",
"(",
"value",
",",
"*",
"task_args",
",",
"*",
"*",
"task_kwargs",
")",
"results",
".",
"append",
"(",
"result",
")",
"_callback",
"(",
"0",
")",
"Publisher",
"(",
")",
".",
"publish",
"(",
"\"terra.parallel.finish\"",
")",
"return",
"results"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LoConfigConverter.get_qubit_los
|
Embed default qubit LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of qubit LOs.
Raises:
PulseError: when LO frequencies are missing.
|
qiskit/qobj/converters/lo_config.py
|
def get_qubit_los(self, user_lo_config):
"""Embed default qubit LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of qubit LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_q_los = self.default_qubit_los.copy()
except KeyError:
raise PulseError('Qubit default frequencies not exist.')
for channel, lo_freq in user_lo_config.qubit_lo_dict().items():
_q_los[channel.index] = lo_freq
if _q_los == self.default_qubit_los:
return None
return _q_los
|
def get_qubit_los(self, user_lo_config):
"""Embed default qubit LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of qubit LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_q_los = self.default_qubit_los.copy()
except KeyError:
raise PulseError('Qubit default frequencies not exist.')
for channel, lo_freq in user_lo_config.qubit_lo_dict().items():
_q_los[channel.index] = lo_freq
if _q_los == self.default_qubit_los:
return None
return _q_los
|
[
"Embed",
"default",
"qubit",
"LO",
"frequencies",
"from",
"backend",
"and",
"format",
"them",
"to",
"list",
"object",
".",
"If",
"configured",
"lo",
"frequency",
"is",
"the",
"same",
"as",
"default",
"this",
"method",
"returns",
"None",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qobj/converters/lo_config.py#L54-L77
|
[
"def",
"get_qubit_los",
"(",
"self",
",",
"user_lo_config",
")",
":",
"try",
":",
"_q_los",
"=",
"self",
".",
"default_qubit_los",
".",
"copy",
"(",
")",
"except",
"KeyError",
":",
"raise",
"PulseError",
"(",
"'Qubit default frequencies not exist.'",
")",
"for",
"channel",
",",
"lo_freq",
"in",
"user_lo_config",
".",
"qubit_lo_dict",
"(",
")",
".",
"items",
"(",
")",
":",
"_q_los",
"[",
"channel",
".",
"index",
"]",
"=",
"lo_freq",
"if",
"_q_los",
"==",
"self",
".",
"default_qubit_los",
":",
"return",
"None",
"return",
"_q_los"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
LoConfigConverter.get_meas_los
|
Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Raises:
PulseError: when LO frequencies are missing.
|
qiskit/qobj/converters/lo_config.py
|
def get_meas_los(self, user_lo_config):
"""Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_m_los = self.default_meas_los.copy()
except KeyError:
raise PulseError('Default measurement frequencies not exist.')
for channel, lo_freq in user_lo_config.meas_lo_dict().items():
_m_los[channel.index] = lo_freq
if _m_los == self.default_meas_los:
return None
return _m_los
|
def get_meas_los(self, user_lo_config):
"""Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_m_los = self.default_meas_los.copy()
except KeyError:
raise PulseError('Default measurement frequencies not exist.')
for channel, lo_freq in user_lo_config.meas_lo_dict().items():
_m_los[channel.index] = lo_freq
if _m_los == self.default_meas_los:
return None
return _m_los
|
[
"Embed",
"default",
"meas",
"LO",
"frequencies",
"from",
"backend",
"and",
"format",
"them",
"to",
"list",
"object",
".",
"If",
"configured",
"lo",
"frequency",
"is",
"the",
"same",
"as",
"default",
"this",
"method",
"returns",
"None",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qobj/converters/lo_config.py#L79-L102
|
[
"def",
"get_meas_los",
"(",
"self",
",",
"user_lo_config",
")",
":",
"try",
":",
"_m_los",
"=",
"self",
".",
"default_meas_los",
".",
"copy",
"(",
")",
"except",
"KeyError",
":",
"raise",
"PulseError",
"(",
"'Default measurement frequencies not exist.'",
")",
"for",
"channel",
",",
"lo_freq",
"in",
"user_lo_config",
".",
"meas_lo_dict",
"(",
")",
".",
"items",
"(",
")",
":",
"_m_los",
"[",
"channel",
".",
"index",
"]",
"=",
"lo_freq",
"if",
"_m_los",
"==",
"self",
".",
"default_meas_los",
":",
"return",
"None",
"return",
"_m_los"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
Unroller.run
|
Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unrolled dag
|
qiskit/transpiler/passes/unroller.py
|
def run(self, dag):
"""Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unrolled dag
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes():
basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
if node.name in basic_insts:
# TODO: this is legacy behavior.Basis_insts should be removed that these
# instructions should be part of the device-reported basis. Currently, no
# backend reports "measure", for example.
continue
if node.name in self.basis: # If already a base, ignore.
continue
# TODO: allow choosing other possible decompositions
rule = node.op.definition
if not rule:
raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
"No rule to expand instruction %s." %
(str(self.basis), node.op.name))
# hacky way to build a dag on the same register as the rule is defined
# TODO: need anonymous rules to address wires by index
decomposition = DAGCircuit()
decomposition.add_qreg(rule[0][1][0][0])
for inst in rule:
decomposition.apply_operation_back(*inst)
unrolled_dag = self.run(decomposition) # recursively unroll ops
dag.substitute_node_with_dag(node, unrolled_dag)
return dag
|
def run(self, dag):
"""Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unrolled dag
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes():
basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
if node.name in basic_insts:
# TODO: this is legacy behavior.Basis_insts should be removed that these
# instructions should be part of the device-reported basis. Currently, no
# backend reports "measure", for example.
continue
if node.name in self.basis: # If already a base, ignore.
continue
# TODO: allow choosing other possible decompositions
rule = node.op.definition
if not rule:
raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
"No rule to expand instruction %s." %
(str(self.basis), node.op.name))
# hacky way to build a dag on the same register as the rule is defined
# TODO: need anonymous rules to address wires by index
decomposition = DAGCircuit()
decomposition.add_qreg(rule[0][1][0][0])
for inst in rule:
decomposition.apply_operation_back(*inst)
unrolled_dag = self.run(decomposition) # recursively unroll ops
dag.substitute_node_with_dag(node, unrolled_dag)
return dag
|
[
"Expand",
"all",
"op",
"nodes",
"to",
"the",
"given",
"basis",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/unroller.py#L29-L69
|
[
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"# Walk through the DAG and expand each non-basis node",
"for",
"node",
"in",
"dag",
".",
"op_nodes",
"(",
")",
":",
"basic_insts",
"=",
"[",
"'measure'",
",",
"'reset'",
",",
"'barrier'",
",",
"'snapshot'",
"]",
"if",
"node",
".",
"name",
"in",
"basic_insts",
":",
"# TODO: this is legacy behavior.Basis_insts should be removed that these",
"# instructions should be part of the device-reported basis. Currently, no",
"# backend reports \"measure\", for example.",
"continue",
"if",
"node",
".",
"name",
"in",
"self",
".",
"basis",
":",
"# If already a base, ignore.",
"continue",
"# TODO: allow choosing other possible decompositions",
"rule",
"=",
"node",
".",
"op",
".",
"definition",
"if",
"not",
"rule",
":",
"raise",
"QiskitError",
"(",
"\"Cannot unroll the circuit to the given basis, %s. \"",
"\"No rule to expand instruction %s.\"",
"%",
"(",
"str",
"(",
"self",
".",
"basis",
")",
",",
"node",
".",
"op",
".",
"name",
")",
")",
"# hacky way to build a dag on the same register as the rule is defined",
"# TODO: need anonymous rules to address wires by index",
"decomposition",
"=",
"DAGCircuit",
"(",
")",
"decomposition",
".",
"add_qreg",
"(",
"rule",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"for",
"inst",
"in",
"rule",
":",
"decomposition",
".",
"apply_operation_back",
"(",
"*",
"inst",
")",
"unrolled_dag",
"=",
"self",
".",
"run",
"(",
"decomposition",
")",
"# recursively unroll ops",
"dag",
".",
"substitute_node_with_dag",
"(",
"node",
",",
"unrolled_dag",
")",
"return",
"dag"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
iplot_state_qsphere
|
Create a Q sphere representation.
Graphical representation of the input array, using a Q sphere for each
eigenvalue.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
|
qiskit/visualization/interactive/iplot_qsphere.py
|
def iplot_state_qsphere(rho, figsize=None):
""" Create a Q sphere representation.
Graphical representation of the input array, using a Q sphere for each
eigenvalue.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="qsphere_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
data = $data;
qVisualizations.plotState("qsphere_$divNumber",
"qsphere",
data,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
qspheres_data = []
# Process data and execute
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
weig, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = weig.max()
prob_location = weig.argmax()
if probmix > 0.001:
# print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
state = angleset*state
state.flatten()
spherepoints = []
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
number_of_divisions = n_choose_k(num, weight)
weight_order = bit_string_index(element)
angle = weight_order * 2 * np.pi / number_of_divisions
zvalue = -2 * weight / num + 1
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
qpoint = {
'x': xvalue,
'y': yvalue,
'z': zvalue,
'prob': prob,
'phase': angles
}
spherepoints.append(qpoint)
# Associate all points to one sphere
sphere = {
'points': spherepoints,
'eigenvalue': probmix
}
# Add sphere to the spheres array
qspheres_data.append(sphere)
weig[prob_location] = 0
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': qspheres_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
|
def iplot_state_qsphere(rho, figsize=None):
""" Create a Q sphere representation.
Graphical representation of the input array, using a Q sphere for each
eigenvalue.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="qsphere_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
data = $data;
qVisualizations.plotState("qsphere_$divNumber",
"qsphere",
data,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
qspheres_data = []
# Process data and execute
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
weig, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = weig.max()
prob_location = weig.argmax()
if probmix > 0.001:
# print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
state = angleset*state
state.flatten()
spherepoints = []
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
number_of_divisions = n_choose_k(num, weight)
weight_order = bit_string_index(element)
angle = weight_order * 2 * np.pi / number_of_divisions
zvalue = -2 * weight / num + 1
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
qpoint = {
'x': xvalue,
'y': yvalue,
'z': zvalue,
'prob': prob,
'phase': angles
}
spherepoints.append(qpoint)
# Associate all points to one sphere
sphere = {
'points': spherepoints,
'eigenvalue': probmix
}
# Add sphere to the spheres array
qspheres_data.append(sphere)
weig[prob_location] = 0
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': qspheres_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
|
[
"Create",
"a",
"Q",
"sphere",
"representation",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_qsphere.py#L31-L155
|
[
"def",
"iplot_state_qsphere",
"(",
"rho",
",",
"figsize",
"=",
"None",
")",
":",
"# HTML",
"html_template",
"=",
"Template",
"(",
"\"\"\"\n <p>\n <div id=\"content_$divNumber\" style=\"position: absolute; z-index: 1;\">\n <div id=\"qsphere_$divNumber\"></div>\n </div>\n </p>\n \"\"\"",
")",
"# JavaScript",
"javascript_template",
"=",
"Template",
"(",
"\"\"\"\n <script>\n requirejs.config({\n paths: {\n qVisualization: \"https://qvisualization.mybluemix.net/q-visualizations\"\n }\n });\n require([\"qVisualization\"], function(qVisualizations) {\n data = $data;\n qVisualizations.plotState(\"qsphere_$divNumber\",\n \"qsphere\",\n data,\n $options);\n });\n </script>\n\n \"\"\"",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"if",
"figsize",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"else",
":",
"options",
"=",
"{",
"'width'",
":",
"figsize",
"[",
"0",
"]",
",",
"'height'",
":",
"figsize",
"[",
"1",
"]",
"}",
"qspheres_data",
"=",
"[",
"]",
"# Process data and execute",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"# get the eigenvectors and eigenvalues",
"weig",
",",
"stateall",
"=",
"linalg",
".",
"eigh",
"(",
"rho",
")",
"for",
"_",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"# start with the max",
"probmix",
"=",
"weig",
".",
"max",
"(",
")",
"prob_location",
"=",
"weig",
".",
"argmax",
"(",
")",
"if",
"probmix",
">",
"0.001",
":",
"# print(\"The \" + str(k) + \"th eigenvalue = \" + str(probmix))",
"# get the max eigenvalue",
"state",
"=",
"stateall",
"[",
":",
",",
"prob_location",
"]",
"loc",
"=",
"np",
".",
"absolute",
"(",
"state",
")",
".",
"argmax",
"(",
")",
"# get the element location closes to lowest bin representation.",
"for",
"j",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"test",
"=",
"np",
".",
"absolute",
"(",
"np",
".",
"absolute",
"(",
"state",
"[",
"j",
"]",
")",
"-",
"np",
".",
"absolute",
"(",
"state",
"[",
"loc",
"]",
")",
")",
"if",
"test",
"<",
"0.001",
":",
"loc",
"=",
"j",
"break",
"# remove the global phase",
"angles",
"=",
"(",
"np",
".",
"angle",
"(",
"state",
"[",
"loc",
"]",
")",
"+",
"2",
"*",
"np",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"angleset",
"=",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"angles",
")",
"state",
"=",
"angleset",
"*",
"state",
"state",
".",
"flatten",
"(",
")",
"spherepoints",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"# get x,y,z points",
"element",
"=",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"weight",
"=",
"element",
".",
"count",
"(",
"\"1\"",
")",
"number_of_divisions",
"=",
"n_choose_k",
"(",
"num",
",",
"weight",
")",
"weight_order",
"=",
"bit_string_index",
"(",
"element",
")",
"angle",
"=",
"weight_order",
"*",
"2",
"*",
"np",
".",
"pi",
"/",
"number_of_divisions",
"zvalue",
"=",
"-",
"2",
"*",
"weight",
"/",
"num",
"+",
"1",
"xvalue",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"zvalue",
"**",
"2",
")",
"*",
"np",
".",
"cos",
"(",
"angle",
")",
"yvalue",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"zvalue",
"**",
"2",
")",
"*",
"np",
".",
"sin",
"(",
"angle",
")",
"# get prob and angle - prob will be shade and angle color",
"prob",
"=",
"np",
".",
"real",
"(",
"np",
".",
"dot",
"(",
"state",
"[",
"i",
"]",
",",
"state",
"[",
"i",
"]",
".",
"conj",
"(",
")",
")",
")",
"angles",
"=",
"(",
"np",
".",
"angle",
"(",
"state",
"[",
"i",
"]",
")",
"+",
"2",
"*",
"np",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"qpoint",
"=",
"{",
"'x'",
":",
"xvalue",
",",
"'y'",
":",
"yvalue",
",",
"'z'",
":",
"zvalue",
",",
"'prob'",
":",
"prob",
",",
"'phase'",
":",
"angles",
"}",
"spherepoints",
".",
"append",
"(",
"qpoint",
")",
"# Associate all points to one sphere",
"sphere",
"=",
"{",
"'points'",
":",
"spherepoints",
",",
"'eigenvalue'",
":",
"probmix",
"}",
"# Add sphere to the spheres array",
"qspheres_data",
".",
"append",
"(",
"sphere",
")",
"weig",
"[",
"prob_location",
"]",
"=",
"0",
"div_number",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
"div_number",
"=",
"re",
".",
"sub",
"(",
"'[.]'",
",",
"''",
",",
"div_number",
")",
"html",
"=",
"html_template",
".",
"substitute",
"(",
"{",
"'divNumber'",
":",
"div_number",
"}",
")",
"javascript",
"=",
"javascript_template",
".",
"substitute",
"(",
"{",
"'data'",
":",
"qspheres_data",
",",
"'divNumber'",
":",
"div_number",
",",
"'options'",
":",
"options",
"}",
")",
"display",
"(",
"HTML",
"(",
"html",
"+",
"javascript",
")",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
n_choose_k
|
Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
|
qiskit/visualization/interactive/iplot_qsphere.py
|
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
|
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
|
[
"Return",
"the",
"number",
"of",
"combinations",
"for",
"n",
"choose",
"k",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_qsphere.py#L158-L172
|
[
"def",
"n_choose_k",
"(",
"n",
",",
"k",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"0",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"y",
"[",
"0",
"]",
"/",
"y",
"[",
"1",
"]",
",",
"zip",
"(",
"range",
"(",
"n",
"-",
"k",
"+",
"1",
",",
"n",
"+",
"1",
")",
",",
"range",
"(",
"1",
",",
"k",
"+",
"1",
")",
")",
",",
"1",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
bit_string_index
|
Return the index of a string of 0s and 1s.
|
qiskit/visualization/interactive/iplot_qsphere.py
|
def bit_string_index(text):
"""Return the index of a string of 0s and 1s."""
n = len(text)
k = text.count("1")
if text.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(text) if char == "1"]
return lex_index(n, k, ones)
|
def bit_string_index(text):
"""Return the index of a string of 0s and 1s."""
n = len(text)
k = text.count("1")
if text.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(text) if char == "1"]
return lex_index(n, k, ones)
|
[
"Return",
"the",
"index",
"of",
"a",
"string",
"of",
"0s",
"and",
"1s",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_qsphere.py#L175-L182
|
[
"def",
"bit_string_index",
"(",
"text",
")",
":",
"n",
"=",
"len",
"(",
"text",
")",
"k",
"=",
"text",
".",
"count",
"(",
"\"1\"",
")",
"if",
"text",
".",
"count",
"(",
"\"0\"",
")",
"!=",
"n",
"-",
"k",
":",
"raise",
"VisualizationError",
"(",
"\"s must be a string of 0 and 1\"",
")",
"ones",
"=",
"[",
"pos",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
"if",
"char",
"==",
"\"1\"",
"]",
"return",
"lex_index",
"(",
"n",
",",
"k",
",",
"ones",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
lex_index
|
Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
|
qiskit/visualization/interactive/iplot_qsphere.py
|
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
|
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
|
[
"Return",
"the",
"lex",
"index",
"of",
"a",
"combination",
".."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/interactive/iplot_qsphere.py#L185-L203
|
[
"def",
"lex_index",
"(",
"n",
",",
"k",
",",
"lst",
")",
":",
"if",
"len",
"(",
"lst",
")",
"!=",
"k",
":",
"raise",
"VisualizationError",
"(",
"\"list should have length k\"",
")",
"comb",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"n",
"-",
"1",
"-",
"x",
",",
"lst",
")",
")",
"dualm",
"=",
"sum",
"(",
"[",
"n_choose_k",
"(",
"comb",
"[",
"k",
"-",
"1",
"-",
"i",
"]",
",",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"k",
")",
"]",
")",
"return",
"int",
"(",
"dualm",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_state_hinton
|
Plot a hinton diagram for the quanum state.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
|
qiskit/visualization/state_visualization.py
|
def plot_state_hinton(rho, title='', figsize=None):
"""Plot a hinton diagram for the quanum state.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (8, 5)
num = int(np.log2(len(rho)))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
max_weight = 2 ** np.ceil(np.log(np.abs(rho).max()) / np.log(2))
datareal = np.real(rho)
dataimag = np.imag(rho)
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
# Real
ax1.patch.set_facecolor('gray')
ax1.set_aspect('equal', 'box')
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax1.add_patch(rect)
ax1.set_xticks(np.arange(0, lx+0.5, 1))
ax1.set_yticks(np.arange(0, ly+0.5, 1))
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.autoscale_view()
ax1.invert_yaxis()
ax1.set_title('Real[rho]', fontsize=14)
# Imaginary
ax2.patch.set_facecolor('gray')
ax2.set_aspect('equal', 'box')
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax2.add_patch(rect)
if np.any(dataimag != 0):
ax2.set_xticks(np.arange(0, lx+0.5, 1))
ax2.set_yticks(np.arange(0, ly+0.5, 1))
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.autoscale_view()
ax2.invert_yaxis()
ax2.set_title('Imag[rho]', fontsize=14)
if title:
fig.suptitle(title, fontsize=16)
plt.tight_layout()
plt.close(fig)
return fig
|
def plot_state_hinton(rho, title='', figsize=None):
"""Plot a hinton diagram for the quanum state.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (8, 5)
num = int(np.log2(len(rho)))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
max_weight = 2 ** np.ceil(np.log(np.abs(rho).max()) / np.log(2))
datareal = np.real(rho)
dataimag = np.imag(rho)
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
# Real
ax1.patch.set_facecolor('gray')
ax1.set_aspect('equal', 'box')
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax1.add_patch(rect)
ax1.set_xticks(np.arange(0, lx+0.5, 1))
ax1.set_yticks(np.arange(0, ly+0.5, 1))
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.autoscale_view()
ax1.invert_yaxis()
ax1.set_title('Real[rho]', fontsize=14)
# Imaginary
ax2.patch.set_facecolor('gray')
ax2.set_aspect('equal', 'box')
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax2.add_patch(rect)
if np.any(dataimag != 0):
ax2.set_xticks(np.arange(0, lx+0.5, 1))
ax2.set_yticks(np.arange(0, ly+0.5, 1))
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.autoscale_view()
ax2.invert_yaxis()
ax2.set_title('Imag[rho]', fontsize=14)
if title:
fig.suptitle(title, fontsize=16)
plt.tight_layout()
plt.close(fig)
return fig
|
[
"Plot",
"a",
"hinton",
"diagram",
"for",
"the",
"quanum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L50-L121
|
[
"def",
"plot_state_hinton",
"(",
"rho",
",",
"title",
"=",
"''",
",",
"figsize",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"8",
",",
"5",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"fig",
",",
"(",
"ax1",
",",
"ax2",
")",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"2",
",",
"figsize",
"=",
"figsize",
")",
"max_weight",
"=",
"2",
"**",
"np",
".",
"ceil",
"(",
"np",
".",
"log",
"(",
"np",
".",
"abs",
"(",
"rho",
")",
".",
"max",
"(",
")",
")",
"/",
"np",
".",
"log",
"(",
"2",
")",
")",
"datareal",
"=",
"np",
".",
"real",
"(",
"rho",
")",
"dataimag",
"=",
"np",
".",
"imag",
"(",
"rho",
")",
"column_names",
"=",
"[",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
"]",
"row_names",
"=",
"[",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
"]",
"lx",
"=",
"len",
"(",
"datareal",
"[",
"0",
"]",
")",
"# Work out matrix dimensions",
"ly",
"=",
"len",
"(",
"datareal",
"[",
":",
",",
"0",
"]",
")",
"# Real",
"ax1",
".",
"patch",
".",
"set_facecolor",
"(",
"'gray'",
")",
"ax1",
".",
"set_aspect",
"(",
"'equal'",
",",
"'box'",
")",
"ax1",
".",
"xaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"ax1",
".",
"yaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
",",
"w",
"in",
"np",
".",
"ndenumerate",
"(",
"datareal",
")",
":",
"color",
"=",
"'white'",
"if",
"w",
">",
"0",
"else",
"'black'",
"size",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"abs",
"(",
"w",
")",
"/",
"max_weight",
")",
"rect",
"=",
"plt",
".",
"Rectangle",
"(",
"[",
"x",
"-",
"size",
"/",
"2",
",",
"y",
"-",
"size",
"/",
"2",
"]",
",",
"size",
",",
"size",
",",
"facecolor",
"=",
"color",
",",
"edgecolor",
"=",
"color",
")",
"ax1",
".",
"add_patch",
"(",
"rect",
")",
"ax1",
".",
"set_xticks",
"(",
"np",
".",
"arange",
"(",
"0",
",",
"lx",
"+",
"0.5",
",",
"1",
")",
")",
"ax1",
".",
"set_yticks",
"(",
"np",
".",
"arange",
"(",
"0",
",",
"ly",
"+",
"0.5",
",",
"1",
")",
")",
"ax1",
".",
"set_yticklabels",
"(",
"row_names",
",",
"fontsize",
"=",
"14",
")",
"ax1",
".",
"set_xticklabels",
"(",
"column_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"90",
")",
"ax1",
".",
"autoscale_view",
"(",
")",
"ax1",
".",
"invert_yaxis",
"(",
")",
"ax1",
".",
"set_title",
"(",
"'Real[rho]'",
",",
"fontsize",
"=",
"14",
")",
"# Imaginary",
"ax2",
".",
"patch",
".",
"set_facecolor",
"(",
"'gray'",
")",
"ax2",
".",
"set_aspect",
"(",
"'equal'",
",",
"'box'",
")",
"ax2",
".",
"xaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"ax2",
".",
"yaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
",",
"w",
"in",
"np",
".",
"ndenumerate",
"(",
"dataimag",
")",
":",
"color",
"=",
"'white'",
"if",
"w",
">",
"0",
"else",
"'black'",
"size",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"abs",
"(",
"w",
")",
"/",
"max_weight",
")",
"rect",
"=",
"plt",
".",
"Rectangle",
"(",
"[",
"x",
"-",
"size",
"/",
"2",
",",
"y",
"-",
"size",
"/",
"2",
"]",
",",
"size",
",",
"size",
",",
"facecolor",
"=",
"color",
",",
"edgecolor",
"=",
"color",
")",
"ax2",
".",
"add_patch",
"(",
"rect",
")",
"if",
"np",
".",
"any",
"(",
"dataimag",
"!=",
"0",
")",
":",
"ax2",
".",
"set_xticks",
"(",
"np",
".",
"arange",
"(",
"0",
",",
"lx",
"+",
"0.5",
",",
"1",
")",
")",
"ax2",
".",
"set_yticks",
"(",
"np",
".",
"arange",
"(",
"0",
",",
"ly",
"+",
"0.5",
",",
"1",
")",
")",
"ax2",
".",
"set_yticklabels",
"(",
"row_names",
",",
"fontsize",
"=",
"14",
")",
"ax2",
".",
"set_xticklabels",
"(",
"column_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"90",
")",
"ax2",
".",
"autoscale_view",
"(",
")",
"ax2",
".",
"invert_yaxis",
"(",
")",
"ax2",
".",
"set_title",
"(",
"'Imag[rho]'",
",",
"fontsize",
"=",
"14",
")",
"if",
"title",
":",
"fig",
".",
"suptitle",
"(",
"title",
",",
"fontsize",
"=",
"16",
")",
"plt",
".",
"tight_layout",
"(",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_bloch_vector
|
Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>]
title (str): a string that represents the plot title
ax (matplotlib.Axes): An Axes to use for rendering the bloch sphere
figsize (tuple): Figure size in inches. Has no effect is passing `ax`.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
|
qiskit/visualization/state_visualization.py
|
def plot_bloch_vector(bloch, title="", ax=None, figsize=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>]
title (str): a string that represents the plot title
ax (matplotlib.Axes): An Axes to use for rendering the bloch sphere
figsize (tuple): Figure size in inches. Has no effect is passing `ax`.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
if figsize is None:
figsize = (5, 5)
B = Bloch(axes=ax)
B.add_vectors(bloch)
B.render(title=title)
if ax is None:
fig = B.fig
fig.set_size_inches(figsize[0], figsize[1])
plt.close(fig)
return fig
return None
|
def plot_bloch_vector(bloch, title="", ax=None, figsize=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>]
title (str): a string that represents the plot title
ax (matplotlib.Axes): An Axes to use for rendering the bloch sphere
figsize (tuple): Figure size in inches. Has no effect is passing `ax`.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
if figsize is None:
figsize = (5, 5)
B = Bloch(axes=ax)
B.add_vectors(bloch)
B.render(title=title)
if ax is None:
fig = B.fig
fig.set_size_inches(figsize[0], figsize[1])
plt.close(fig)
return fig
return None
|
[
"Plot",
"the",
"Bloch",
"sphere",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L124-L153
|
[
"def",
"plot_bloch_vector",
"(",
"bloch",
",",
"title",
"=",
"\"\"",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"5",
",",
"5",
")",
"B",
"=",
"Bloch",
"(",
"axes",
"=",
"ax",
")",
"B",
".",
"add_vectors",
"(",
"bloch",
")",
"B",
".",
"render",
"(",
"title",
"=",
"title",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
"=",
"B",
".",
"fig",
"fig",
".",
"set_size_inches",
"(",
"figsize",
"[",
"0",
"]",
",",
"figsize",
"[",
"1",
"]",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig",
"return",
"None"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_bloch_multivector
|
Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Has no effect, here for compatibility only.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
|
qiskit/visualization/state_visualization.py
|
def plot_bloch_multivector(rho, title='', figsize=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Has no effect, here for compatibility only.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
width, height = plt.figaspect(1/num)
fig = plt.figure(figsize=(width, height))
for i in range(num):
ax = fig.add_subplot(1, num, i + 1, projection='3d')
pauli_singles = [
Pauli.pauli_single(num, i, 'X'),
Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')
]
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
plot_bloch_vector(bloch_state, "qubit " + str(i), ax=ax,
figsize=figsize)
fig.suptitle(title, fontsize=16)
plt.close(fig)
return fig
|
def plot_bloch_multivector(rho, title='', figsize=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Has no effect, here for compatibility only.
Returns:
Figure: A matplotlib figure instance if `ax = None`.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
width, height = plt.figaspect(1/num)
fig = plt.figure(figsize=(width, height))
for i in range(num):
ax = fig.add_subplot(1, num, i + 1, projection='3d')
pauli_singles = [
Pauli.pauli_single(num, i, 'X'),
Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')
]
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
plot_bloch_vector(bloch_state, "qubit " + str(i), ax=ax,
figsize=figsize)
fig.suptitle(title, fontsize=16)
plt.close(fig)
return fig
|
[
"Plot",
"the",
"Bloch",
"sphere",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L156-L192
|
[
"def",
"plot_bloch_multivector",
"(",
"rho",
",",
"title",
"=",
"''",
",",
"figsize",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"width",
",",
"height",
"=",
"plt",
".",
"figaspect",
"(",
"1",
"/",
"num",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"width",
",",
"height",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"num",
",",
"i",
"+",
"1",
",",
"projection",
"=",
"'3d'",
")",
"pauli_singles",
"=",
"[",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'X'",
")",
",",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'Y'",
")",
",",
"Pauli",
".",
"pauli_single",
"(",
"num",
",",
"i",
",",
"'Z'",
")",
"]",
"bloch_state",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"np",
".",
"real",
"(",
"np",
".",
"trace",
"(",
"np",
".",
"dot",
"(",
"x",
".",
"to_matrix",
"(",
")",
",",
"rho",
")",
")",
")",
",",
"pauli_singles",
")",
")",
"plot_bloch_vector",
"(",
"bloch_state",
",",
"\"qubit \"",
"+",
"str",
"(",
"i",
")",
",",
"ax",
"=",
"ax",
",",
"figsize",
"=",
"figsize",
")",
"fig",
".",
"suptitle",
"(",
"title",
",",
"fontsize",
"=",
"16",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_state_city
|
Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
|
qiskit/visualization/state_visualization.py
|
def plot_state_city(rho, title="", figsize=None, color=None,
alpha=1):
"""Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
if color is None:
color = ["#648fff", "#648fff"]
else:
if len(color) != 2:
raise ValueError("'color' must be a list of len=2.")
if color[0] is None:
color[0] = "#648fff"
if color[1] is None:
color[1] = "#648fff"
# set default figure size
if figsize is None:
figsize = (15, 5)
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
x = [0, max(xpos)+0.5, max(xpos)+0.5, 0]
y = [0, 0, max(ypos)+0.5, max(ypos)+0.5]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
for idx, cur_zpos in enumerate(zpos):
if dzr[idx] > 0:
zorder = 2
else:
zorder = 0
b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos,
dx[idx], dy[idx], dzr[idx],
alpha=alpha, zorder=zorder)
b1.set_facecolors(fc1[6*idx:6*idx+6])
pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k',
linewidths=1, zorder=1)
if min(dzr) < 0 < max(dzr):
ax1.add_collection3d(pc1)
ax2 = fig.add_subplot(1, 2, 2, projection='3d')
fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
for idx, cur_zpos in enumerate(zpos):
if dzi[idx] > 0:
zorder = 2
else:
zorder = 0
b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos,
dx[idx], dy[idx], dzi[idx],
alpha=alpha, zorder=zorder)
b2.set_facecolors(fc2[6*idx:6*idx+6])
pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k',
linewidths=1, zorder=1)
if min(dzi) < 0 < max(dzi):
ax2.add_collection3d(pc2)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
max_dzr = max(dzr)
min_dzr = min(dzr)
if max_dzr != min_dzr:
ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)
else:
if min_dzr == 0:
ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)
else:
ax1.axes.set_zlim3d(auto=True)
ax1.zaxis.set_major_locator(MaxNLocator(5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)
ax1.set_zlabel("Real[rho]", fontsize=14)
for tick in ax1.zaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
min_dzi = np.min(dzi)
max_dzi = np.max(dzi)
if min_dzi != max_dzi:
eps = 0
ax2.zaxis.set_major_locator(MaxNLocator(5))
ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)
else:
if min_dzi == 0:
ax2.set_zticks([0])
eps = 1e-9
ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)
else:
ax2.axes.set_zlim3d(auto=True)
ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)
ax2.set_zlabel("Imag[rho]", fontsize=14)
for tick in ax2.zaxis.get_major_ticks():
tick.label.set_fontsize(14)
plt.suptitle(title, fontsize=16)
plt.tight_layout()
plt.close(fig)
return fig
|
def plot_state_city(rho, title="", figsize=None, color=None,
alpha=1):
"""Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
if color is None:
color = ["#648fff", "#648fff"]
else:
if len(color) != 2:
raise ValueError("'color' must be a list of len=2.")
if color[0] is None:
color[0] = "#648fff"
if color[1] is None:
color[1] = "#648fff"
# set default figure size
if figsize is None:
figsize = (15, 5)
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
x = [0, max(xpos)+0.5, max(xpos)+0.5, 0]
y = [0, 0, max(ypos)+0.5, max(ypos)+0.5]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
for idx, cur_zpos in enumerate(zpos):
if dzr[idx] > 0:
zorder = 2
else:
zorder = 0
b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos,
dx[idx], dy[idx], dzr[idx],
alpha=alpha, zorder=zorder)
b1.set_facecolors(fc1[6*idx:6*idx+6])
pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k',
linewidths=1, zorder=1)
if min(dzr) < 0 < max(dzr):
ax1.add_collection3d(pc1)
ax2 = fig.add_subplot(1, 2, 2, projection='3d')
fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
for idx, cur_zpos in enumerate(zpos):
if dzi[idx] > 0:
zorder = 2
else:
zorder = 0
b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos,
dx[idx], dy[idx], dzi[idx],
alpha=alpha, zorder=zorder)
b2.set_facecolors(fc2[6*idx:6*idx+6])
pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k',
linewidths=1, zorder=1)
if min(dzi) < 0 < max(dzi):
ax2.add_collection3d(pc2)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
max_dzr = max(dzr)
min_dzr = min(dzr)
if max_dzr != min_dzr:
ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)
else:
if min_dzr == 0:
ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)
else:
ax1.axes.set_zlim3d(auto=True)
ax1.zaxis.set_major_locator(MaxNLocator(5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)
ax1.set_zlabel("Real[rho]", fontsize=14)
for tick in ax1.zaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
min_dzi = np.min(dzi)
max_dzi = np.max(dzi)
if min_dzi != max_dzi:
eps = 0
ax2.zaxis.set_major_locator(MaxNLocator(5))
ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)
else:
if min_dzi == 0:
ax2.set_zticks([0])
eps = 1e-9
ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)
else:
ax2.axes.set_zlim3d(auto=True)
ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)
ax2.set_zlabel("Imag[rho]", fontsize=14)
for tick in ax2.zaxis.get_major_ticks():
tick.label.set_fontsize(14)
plt.suptitle(title, fontsize=16)
plt.tight_layout()
plt.close(fig)
return fig
|
[
"Plot",
"the",
"cityscape",
"of",
"quantum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L195-L341
|
[
"def",
"plot_state_city",
"(",
"rho",
",",
"title",
"=",
"\"\"",
",",
"figsize",
"=",
"None",
",",
"color",
"=",
"None",
",",
"alpha",
"=",
"1",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"# get the real and imag parts of rho",
"datareal",
"=",
"np",
".",
"real",
"(",
"rho",
")",
"dataimag",
"=",
"np",
".",
"imag",
"(",
"rho",
")",
"# get the labels",
"column_names",
"=",
"[",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
"]",
"row_names",
"=",
"[",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
"]",
"lx",
"=",
"len",
"(",
"datareal",
"[",
"0",
"]",
")",
"# Work out matrix dimensions",
"ly",
"=",
"len",
"(",
"datareal",
"[",
":",
",",
"0",
"]",
")",
"xpos",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"lx",
",",
"1",
")",
"# Set up a mesh of positions",
"ypos",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"ly",
",",
"1",
")",
"xpos",
",",
"ypos",
"=",
"np",
".",
"meshgrid",
"(",
"xpos",
"+",
"0.25",
",",
"ypos",
"+",
"0.25",
")",
"xpos",
"=",
"xpos",
".",
"flatten",
"(",
")",
"ypos",
"=",
"ypos",
".",
"flatten",
"(",
")",
"zpos",
"=",
"np",
".",
"zeros",
"(",
"lx",
"*",
"ly",
")",
"dx",
"=",
"0.5",
"*",
"np",
".",
"ones_like",
"(",
"zpos",
")",
"# width of bars",
"dy",
"=",
"dx",
".",
"copy",
"(",
")",
"dzr",
"=",
"datareal",
".",
"flatten",
"(",
")",
"dzi",
"=",
"dataimag",
".",
"flatten",
"(",
")",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"[",
"\"#648fff\"",
",",
"\"#648fff\"",
"]",
"else",
":",
"if",
"len",
"(",
"color",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"'color' must be a list of len=2.\"",
")",
"if",
"color",
"[",
"0",
"]",
"is",
"None",
":",
"color",
"[",
"0",
"]",
"=",
"\"#648fff\"",
"if",
"color",
"[",
"1",
"]",
"is",
"None",
":",
"color",
"[",
"1",
"]",
"=",
"\"#648fff\"",
"# set default figure size",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"15",
",",
"5",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax1",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"2",
",",
"1",
",",
"projection",
"=",
"'3d'",
")",
"x",
"=",
"[",
"0",
",",
"max",
"(",
"xpos",
")",
"+",
"0.5",
",",
"max",
"(",
"xpos",
")",
"+",
"0.5",
",",
"0",
"]",
"y",
"=",
"[",
"0",
",",
"0",
",",
"max",
"(",
"ypos",
")",
"+",
"0.5",
",",
"max",
"(",
"ypos",
")",
"+",
"0.5",
"]",
"z",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"verts",
"=",
"[",
"list",
"(",
"zip",
"(",
"x",
",",
"y",
",",
"z",
")",
")",
"]",
"fc1",
"=",
"generate_facecolors",
"(",
"xpos",
",",
"ypos",
",",
"zpos",
",",
"dx",
",",
"dy",
",",
"dzr",
",",
"color",
"[",
"0",
"]",
")",
"for",
"idx",
",",
"cur_zpos",
"in",
"enumerate",
"(",
"zpos",
")",
":",
"if",
"dzr",
"[",
"idx",
"]",
">",
"0",
":",
"zorder",
"=",
"2",
"else",
":",
"zorder",
"=",
"0",
"b1",
"=",
"ax1",
".",
"bar3d",
"(",
"xpos",
"[",
"idx",
"]",
",",
"ypos",
"[",
"idx",
"]",
",",
"cur_zpos",
",",
"dx",
"[",
"idx",
"]",
",",
"dy",
"[",
"idx",
"]",
",",
"dzr",
"[",
"idx",
"]",
",",
"alpha",
"=",
"alpha",
",",
"zorder",
"=",
"zorder",
")",
"b1",
".",
"set_facecolors",
"(",
"fc1",
"[",
"6",
"*",
"idx",
":",
"6",
"*",
"idx",
"+",
"6",
"]",
")",
"pc1",
"=",
"Poly3DCollection",
"(",
"verts",
",",
"alpha",
"=",
"0.15",
",",
"facecolor",
"=",
"'k'",
",",
"linewidths",
"=",
"1",
",",
"zorder",
"=",
"1",
")",
"if",
"min",
"(",
"dzr",
")",
"<",
"0",
"<",
"max",
"(",
"dzr",
")",
":",
"ax1",
".",
"add_collection3d",
"(",
"pc1",
")",
"ax2",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"2",
",",
"2",
",",
"projection",
"=",
"'3d'",
")",
"fc2",
"=",
"generate_facecolors",
"(",
"xpos",
",",
"ypos",
",",
"zpos",
",",
"dx",
",",
"dy",
",",
"dzi",
",",
"color",
"[",
"1",
"]",
")",
"for",
"idx",
",",
"cur_zpos",
"in",
"enumerate",
"(",
"zpos",
")",
":",
"if",
"dzi",
"[",
"idx",
"]",
">",
"0",
":",
"zorder",
"=",
"2",
"else",
":",
"zorder",
"=",
"0",
"b2",
"=",
"ax2",
".",
"bar3d",
"(",
"xpos",
"[",
"idx",
"]",
",",
"ypos",
"[",
"idx",
"]",
",",
"cur_zpos",
",",
"dx",
"[",
"idx",
"]",
",",
"dy",
"[",
"idx",
"]",
",",
"dzi",
"[",
"idx",
"]",
",",
"alpha",
"=",
"alpha",
",",
"zorder",
"=",
"zorder",
")",
"b2",
".",
"set_facecolors",
"(",
"fc2",
"[",
"6",
"*",
"idx",
":",
"6",
"*",
"idx",
"+",
"6",
"]",
")",
"pc2",
"=",
"Poly3DCollection",
"(",
"verts",
",",
"alpha",
"=",
"0.2",
",",
"facecolor",
"=",
"'k'",
",",
"linewidths",
"=",
"1",
",",
"zorder",
"=",
"1",
")",
"if",
"min",
"(",
"dzi",
")",
"<",
"0",
"<",
"max",
"(",
"dzi",
")",
":",
"ax2",
".",
"add_collection3d",
"(",
"pc2",
")",
"ax1",
".",
"set_xticks",
"(",
"np",
".",
"arange",
"(",
"0.5",
",",
"lx",
"+",
"0.5",
",",
"1",
")",
")",
"ax1",
".",
"set_yticks",
"(",
"np",
".",
"arange",
"(",
"0.5",
",",
"ly",
"+",
"0.5",
",",
"1",
")",
")",
"max_dzr",
"=",
"max",
"(",
"dzr",
")",
"min_dzr",
"=",
"min",
"(",
"dzr",
")",
"if",
"max_dzr",
"!=",
"min_dzr",
":",
"ax1",
".",
"axes",
".",
"set_zlim3d",
"(",
"np",
".",
"min",
"(",
"dzr",
")",
",",
"np",
".",
"max",
"(",
"dzr",
")",
"+",
"1e-9",
")",
"else",
":",
"if",
"min_dzr",
"==",
"0",
":",
"ax1",
".",
"axes",
".",
"set_zlim3d",
"(",
"np",
".",
"min",
"(",
"dzr",
")",
",",
"np",
".",
"max",
"(",
"dzr",
")",
"+",
"1e-9",
")",
"else",
":",
"ax1",
".",
"axes",
".",
"set_zlim3d",
"(",
"auto",
"=",
"True",
")",
"ax1",
".",
"zaxis",
".",
"set_major_locator",
"(",
"MaxNLocator",
"(",
"5",
")",
")",
"ax1",
".",
"w_xaxis",
".",
"set_ticklabels",
"(",
"row_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"45",
")",
"ax1",
".",
"w_yaxis",
".",
"set_ticklabels",
"(",
"column_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"-",
"22.5",
")",
"ax1",
".",
"set_zlabel",
"(",
"\"Real[rho]\"",
",",
"fontsize",
"=",
"14",
")",
"for",
"tick",
"in",
"ax1",
".",
"zaxis",
".",
"get_major_ticks",
"(",
")",
":",
"tick",
".",
"label",
".",
"set_fontsize",
"(",
"14",
")",
"ax2",
".",
"set_xticks",
"(",
"np",
".",
"arange",
"(",
"0.5",
",",
"lx",
"+",
"0.5",
",",
"1",
")",
")",
"ax2",
".",
"set_yticks",
"(",
"np",
".",
"arange",
"(",
"0.5",
",",
"ly",
"+",
"0.5",
",",
"1",
")",
")",
"min_dzi",
"=",
"np",
".",
"min",
"(",
"dzi",
")",
"max_dzi",
"=",
"np",
".",
"max",
"(",
"dzi",
")",
"if",
"min_dzi",
"!=",
"max_dzi",
":",
"eps",
"=",
"0",
"ax2",
".",
"zaxis",
".",
"set_major_locator",
"(",
"MaxNLocator",
"(",
"5",
")",
")",
"ax2",
".",
"axes",
".",
"set_zlim3d",
"(",
"np",
".",
"min",
"(",
"dzi",
")",
",",
"np",
".",
"max",
"(",
"dzi",
")",
"+",
"eps",
")",
"else",
":",
"if",
"min_dzi",
"==",
"0",
":",
"ax2",
".",
"set_zticks",
"(",
"[",
"0",
"]",
")",
"eps",
"=",
"1e-9",
"ax2",
".",
"axes",
".",
"set_zlim3d",
"(",
"np",
".",
"min",
"(",
"dzi",
")",
",",
"np",
".",
"max",
"(",
"dzi",
")",
"+",
"eps",
")",
"else",
":",
"ax2",
".",
"axes",
".",
"set_zlim3d",
"(",
"auto",
"=",
"True",
")",
"ax2",
".",
"w_xaxis",
".",
"set_ticklabels",
"(",
"row_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"45",
")",
"ax2",
".",
"w_yaxis",
".",
"set_ticklabels",
"(",
"column_names",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"-",
"22.5",
")",
"ax2",
".",
"set_zlabel",
"(",
"\"Imag[rho]\"",
",",
"fontsize",
"=",
"14",
")",
"for",
"tick",
"in",
"ax2",
".",
"zaxis",
".",
"get_major_ticks",
"(",
")",
":",
"tick",
".",
"label",
".",
"set_fontsize",
"(",
"14",
")",
"plt",
".",
"suptitle",
"(",
"title",
",",
"fontsize",
"=",
"16",
")",
"plt",
".",
"tight_layout",
"(",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_state_paulivec
|
Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (ndarray): Numpy array for state vector or density matrix
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the expectation value bars.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
|
qiskit/visualization/state_visualization.py
|
def plot_state_paulivec(rho, title="", figsize=None, color=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (ndarray): Numpy array for state vector or density matrix
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the expectation value bars.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (7, 5)
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
fig, ax = plt.subplots(figsize=figsize)
ax.grid(zorder=0, linewidth=1, linestyle='--')
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color='k')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel('Pauli', fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor('#eeeeee')
for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax.set_title(title, fontsize=16)
plt.close(fig)
return fig
|
def plot_state_paulivec(rho, title="", figsize=None, color=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (ndarray): Numpy array for state vector or density matrix
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the expectation value bars.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (7, 5)
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
fig, ax = plt.subplots(figsize=figsize)
ax.grid(zorder=0, linewidth=1, linestyle='--')
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color='k')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel('Pauli', fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor('#eeeeee')
for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax.set_title(title, fontsize=16)
plt.close(fig)
return fig
|
[
"Plot",
"the",
"paulivec",
"representation",
"of",
"a",
"quantum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L344-L390
|
[
"def",
"plot_state_paulivec",
"(",
"rho",
",",
"title",
"=",
"\"\"",
",",
"figsize",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"7",
",",
"5",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"labels",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"to_label",
"(",
")",
",",
"pauli_group",
"(",
"num",
")",
")",
")",
"values",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"np",
".",
"real",
"(",
"np",
".",
"trace",
"(",
"np",
".",
"dot",
"(",
"x",
".",
"to_matrix",
"(",
")",
",",
"rho",
")",
")",
")",
",",
"pauli_group",
"(",
"num",
")",
")",
")",
"numelem",
"=",
"len",
"(",
"values",
")",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"\"#648fff\"",
"ind",
"=",
"np",
".",
"arange",
"(",
"numelem",
")",
"# the x locations for the groups",
"width",
"=",
"0.5",
"# the width of the bars",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
".",
"grid",
"(",
"zorder",
"=",
"0",
",",
"linewidth",
"=",
"1",
",",
"linestyle",
"=",
"'--'",
")",
"ax",
".",
"bar",
"(",
"ind",
",",
"values",
",",
"width",
",",
"color",
"=",
"color",
",",
"zorder",
"=",
"2",
")",
"ax",
".",
"axhline",
"(",
"linewidth",
"=",
"1",
",",
"color",
"=",
"'k'",
")",
"# add some text for labels, title, and axes ticks",
"ax",
".",
"set_ylabel",
"(",
"'Expectation value'",
",",
"fontsize",
"=",
"14",
")",
"ax",
".",
"set_xticks",
"(",
"ind",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"-",
"1",
",",
"-",
"0.5",
",",
"0",
",",
"0.5",
",",
"1",
"]",
")",
"ax",
".",
"set_xticklabels",
"(",
"labels",
",",
"fontsize",
"=",
"14",
",",
"rotation",
"=",
"70",
")",
"ax",
".",
"set_xlabel",
"(",
"'Pauli'",
",",
"fontsize",
"=",
"14",
")",
"ax",
".",
"set_ylim",
"(",
"[",
"-",
"1",
",",
"1",
"]",
")",
"ax",
".",
"set_facecolor",
"(",
"'#eeeeee'",
")",
"for",
"tick",
"in",
"ax",
".",
"xaxis",
".",
"get_major_ticks",
"(",
")",
"+",
"ax",
".",
"yaxis",
".",
"get_major_ticks",
"(",
")",
":",
"tick",
".",
"label",
".",
"set_fontsize",
"(",
"14",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"16",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
bit_string_index
|
Return the index of a string of 0s and 1s.
|
qiskit/visualization/state_visualization.py
|
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
|
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
|
[
"Return",
"the",
"index",
"of",
"a",
"string",
"of",
"0s",
"and",
"1s",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L431-L438
|
[
"def",
"bit_string_index",
"(",
"s",
")",
":",
"n",
"=",
"len",
"(",
"s",
")",
"k",
"=",
"s",
".",
"count",
"(",
"\"1\"",
")",
"if",
"s",
".",
"count",
"(",
"\"0\"",
")",
"!=",
"n",
"-",
"k",
":",
"raise",
"VisualizationError",
"(",
"\"s must be a string of 0 and 1\"",
")",
"ones",
"=",
"[",
"pos",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"s",
")",
"if",
"char",
"==",
"\"1\"",
"]",
"return",
"lex_index",
"(",
"n",
",",
"k",
",",
"ones",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
phase_to_color_wheel
|
Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
|
qiskit/visualization/state_visualization.py
|
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
|
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
|
[
"Map",
"a",
"phase",
"of",
"a",
"complexnumber",
"to",
"a",
"color",
"in",
"(",
"r",
"g",
"b",
")",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L441-L463
|
[
"def",
"phase_to_color_wheel",
"(",
"complex_number",
")",
":",
"angles",
"=",
"np",
".",
"angle",
"(",
"complex_number",
")",
"angle_round",
"=",
"int",
"(",
"(",
"(",
"angles",
"+",
"2",
"*",
"np",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
"/",
"np",
".",
"pi",
"*",
"6",
")",
"color_map",
"=",
"{",
"0",
":",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"# blue,",
"1",
":",
"(",
"0.5",
",",
"0",
",",
"1",
")",
",",
"# blue-violet",
"2",
":",
"(",
"1",
",",
"0",
",",
"1",
")",
",",
"# violet",
"3",
":",
"(",
"1",
",",
"0",
",",
"0.5",
")",
",",
"# red-violet,",
"4",
":",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
"# red",
"5",
":",
"(",
"1",
",",
"0.5",
",",
"0",
")",
",",
"# red-oranage,",
"6",
":",
"(",
"1",
",",
"1",
",",
"0",
")",
",",
"# orange",
"7",
":",
"(",
"0.5",
",",
"1",
",",
"0",
")",
",",
"# orange-yellow",
"8",
":",
"(",
"0",
",",
"1",
",",
"0",
")",
",",
"# yellow,",
"9",
":",
"(",
"0",
",",
"1",
",",
"0.5",
")",
",",
"# yellow-green,",
"10",
":",
"(",
"0",
",",
"1",
",",
"1",
")",
",",
"# green,",
"11",
":",
"(",
"0",
",",
"0.5",
",",
"1",
")",
"# green-blue,",
"}",
"return",
"color_map",
"[",
"angle_round",
"]"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_state_qsphere
|
Plot the qsphere representation of a quantum state.
Args:
rho (ndarray): State vector or density matrix representation.
of quantum state.
figsize (tuple): Figure size in inches.
Returns:
Figure: A matplotlib figure instance.
Raises:
ImportError: Requires matplotlib.
|
qiskit/visualization/state_visualization.py
|
def plot_state_qsphere(rho, figsize=None):
"""Plot the qsphere representation of a quantum state.
Args:
rho (ndarray): State vector or density matrix representation.
of quantum state.
figsize (tuple): Figure size in inches.
Returns:
Figure: A matplotlib figure instance.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (7, 7)
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
we, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
we[prob_location] = 0
else:
break
plt.tight_layout()
plt.close(fig)
return fig
|
def plot_state_qsphere(rho, figsize=None):
"""Plot the qsphere representation of a quantum state.
Args:
rho (ndarray): State vector or density matrix representation.
of quantum state.
figsize (tuple): Figure size in inches.
Returns:
Figure: A matplotlib figure instance.
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
figsize = (7, 7)
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
we, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
we[prob_location] = 0
else:
break
plt.tight_layout()
plt.close(fig)
return fig
|
[
"Plot",
"the",
"qsphere",
"representation",
"of",
"a",
"quantum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L466-L586
|
[
"def",
"plot_state_qsphere",
"(",
"rho",
",",
"figsize",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"rho",
"=",
"_validate_input_state",
"(",
"rho",
")",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"(",
"7",
",",
"7",
")",
"num",
"=",
"int",
"(",
"np",
".",
"log2",
"(",
"len",
"(",
"rho",
")",
")",
")",
"# get the eigenvectors and eigenvalues",
"we",
",",
"stateall",
"=",
"linalg",
".",
"eigh",
"(",
"rho",
")",
"for",
"_",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"# start with the max",
"probmix",
"=",
"we",
".",
"max",
"(",
")",
"prob_location",
"=",
"we",
".",
"argmax",
"(",
")",
"if",
"probmix",
">",
"0.001",
":",
"# get the max eigenvalue",
"state",
"=",
"stateall",
"[",
":",
",",
"prob_location",
"]",
"loc",
"=",
"np",
".",
"absolute",
"(",
"state",
")",
".",
"argmax",
"(",
")",
"# get the element location closes to lowest bin representation.",
"for",
"j",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"test",
"=",
"np",
".",
"absolute",
"(",
"np",
".",
"absolute",
"(",
"state",
"[",
"j",
"]",
")",
"-",
"np",
".",
"absolute",
"(",
"state",
"[",
"loc",
"]",
")",
")",
"if",
"test",
"<",
"0.001",
":",
"loc",
"=",
"j",
"break",
"# remove the global phase",
"angles",
"=",
"(",
"np",
".",
"angle",
"(",
"state",
"[",
"loc",
"]",
")",
"+",
"2",
"*",
"np",
".",
"pi",
")",
"%",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"angleset",
"=",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"angles",
")",
"# print(state)",
"# print(angles)",
"state",
"=",
"angleset",
"*",
"state",
"# print(state)",
"state",
".",
"flatten",
"(",
")",
"# start the plotting",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
",",
"projection",
"=",
"'3d'",
")",
"ax",
".",
"axes",
".",
"set_xlim3d",
"(",
"-",
"1.0",
",",
"1.0",
")",
"ax",
".",
"axes",
".",
"set_ylim3d",
"(",
"-",
"1.0",
",",
"1.0",
")",
"ax",
".",
"axes",
".",
"set_zlim3d",
"(",
"-",
"1.0",
",",
"1.0",
")",
"ax",
".",
"set_aspect",
"(",
"\"equal\"",
")",
"ax",
".",
"axes",
".",
"grid",
"(",
"False",
")",
"# Plot semi-transparent sphere",
"u",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
",",
"25",
")",
"v",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"np",
".",
"pi",
",",
"25",
")",
"x",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"cos",
"(",
"u",
")",
",",
"np",
".",
"sin",
"(",
"v",
")",
")",
"y",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"sin",
"(",
"u",
")",
",",
"np",
".",
"sin",
"(",
"v",
")",
")",
"z",
"=",
"np",
".",
"outer",
"(",
"np",
".",
"ones",
"(",
"np",
".",
"size",
"(",
"u",
")",
")",
",",
"np",
".",
"cos",
"(",
"v",
")",
")",
"ax",
".",
"plot_surface",
"(",
"x",
",",
"y",
",",
"z",
",",
"rstride",
"=",
"1",
",",
"cstride",
"=",
"1",
",",
"color",
"=",
"'k'",
",",
"alpha",
"=",
"0.05",
",",
"linewidth",
"=",
"0",
")",
"# wireframe",
"# Get rid of the panes",
"ax",
".",
"w_xaxis",
".",
"set_pane_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"ax",
".",
"w_yaxis",
".",
"set_pane_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"ax",
".",
"w_zaxis",
".",
"set_pane_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"# Get rid of the spines",
"ax",
".",
"w_xaxis",
".",
"line",
".",
"set_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"ax",
".",
"w_yaxis",
".",
"line",
".",
"set_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"ax",
".",
"w_zaxis",
".",
"line",
".",
"set_color",
"(",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
")",
")",
"# Get rid of the ticks",
"ax",
".",
"set_xticks",
"(",
"[",
"]",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"]",
")",
"ax",
".",
"set_zticks",
"(",
"[",
"]",
")",
"d",
"=",
"num",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"num",
")",
":",
"# get x,y,z points",
"element",
"=",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"num",
")",
"weight",
"=",
"element",
".",
"count",
"(",
"\"1\"",
")",
"zvalue",
"=",
"-",
"2",
"*",
"weight",
"/",
"d",
"+",
"1",
"number_of_divisions",
"=",
"n_choose_k",
"(",
"d",
",",
"weight",
")",
"weight_order",
"=",
"bit_string_index",
"(",
"element",
")",
"# if weight_order >= number_of_divisions / 2:",
"# com_key = compliment(element)",
"# weight_order_temp = bit_string_index(com_key)",
"# weight_order = np.floor(",
"# number_of_divisions / 2) + weight_order_temp + 1",
"angle",
"=",
"weight_order",
"*",
"2",
"*",
"np",
".",
"pi",
"/",
"number_of_divisions",
"xvalue",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"zvalue",
"**",
"2",
")",
"*",
"np",
".",
"cos",
"(",
"angle",
")",
"yvalue",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"zvalue",
"**",
"2",
")",
"*",
"np",
".",
"sin",
"(",
"angle",
")",
"ax",
".",
"plot",
"(",
"[",
"xvalue",
"]",
",",
"[",
"yvalue",
"]",
",",
"[",
"zvalue",
"]",
",",
"markerfacecolor",
"=",
"(",
".5",
",",
".5",
",",
".5",
")",
",",
"markeredgecolor",
"=",
"(",
".5",
",",
".5",
",",
".5",
")",
",",
"marker",
"=",
"'o'",
",",
"markersize",
"=",
"10",
",",
"alpha",
"=",
"1",
")",
"# get prob and angle - prob will be shade and angle color",
"prob",
"=",
"np",
".",
"real",
"(",
"np",
".",
"dot",
"(",
"state",
"[",
"i",
"]",
",",
"state",
"[",
"i",
"]",
".",
"conj",
"(",
")",
")",
")",
"colorstate",
"=",
"phase_to_color_wheel",
"(",
"state",
"[",
"i",
"]",
")",
"a",
"=",
"Arrow3D",
"(",
"[",
"0",
",",
"xvalue",
"]",
",",
"[",
"0",
",",
"yvalue",
"]",
",",
"[",
"0",
",",
"zvalue",
"]",
",",
"mutation_scale",
"=",
"20",
",",
"alpha",
"=",
"prob",
",",
"arrowstyle",
"=",
"\"-\"",
",",
"color",
"=",
"colorstate",
",",
"lw",
"=",
"10",
")",
"ax",
".",
"add_artist",
"(",
"a",
")",
"# add weight lines",
"for",
"weight",
"in",
"range",
"(",
"d",
"+",
"1",
")",
":",
"theta",
"=",
"np",
".",
"linspace",
"(",
"-",
"2",
"*",
"np",
".",
"pi",
",",
"2",
"*",
"np",
".",
"pi",
",",
"100",
")",
"z",
"=",
"-",
"2",
"*",
"weight",
"/",
"d",
"+",
"1",
"r",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"z",
"**",
"2",
")",
"x",
"=",
"r",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"y",
"=",
"r",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"ax",
".",
"plot",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"(",
".5",
",",
".5",
",",
".5",
")",
")",
"# add center point",
"ax",
".",
"plot",
"(",
"[",
"0",
"]",
",",
"[",
"0",
"]",
",",
"[",
"0",
"]",
",",
"markerfacecolor",
"=",
"(",
".5",
",",
".5",
",",
".5",
")",
",",
"markeredgecolor",
"=",
"(",
".5",
",",
".5",
",",
".5",
")",
",",
"marker",
"=",
"'o'",
",",
"markersize",
"=",
"10",
",",
"alpha",
"=",
"1",
")",
"we",
"[",
"prob_location",
"]",
"=",
"0",
"else",
":",
"break",
"plt",
".",
"tight_layout",
"(",
")",
"plt",
".",
"close",
"(",
"fig",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
plot_state
|
Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in inches,
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
|
qiskit/visualization/state_visualization.py
|
def plot_state(quantum_state, method='city', figsize=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in inches,
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
warnings.warn("plot_state is deprecated, and will be removed in \
the 0.9 release. Use the plot_state_ * functions \
instead.",
DeprecationWarning)
# Check if input is a statevector, and convert to density matrix
rho = _validate_input_state(quantum_state)
fig = None
if method == 'city':
fig = plot_state_city(rho, figsize=figsize)
elif method == "paulivec":
fig = plot_state_paulivec(rho, figsize=figsize)
elif method == "qsphere":
fig = plot_state_qsphere(rho, figsize=figsize)
elif method == "bloch":
plot_bloch_multivector(rho, figsize=figsize)
elif method == "hinton":
fig = plot_state_hinton(rho, figsize=figsize)
return fig
|
def plot_state(quantum_state, method='city', figsize=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
figsize (tuple): Figure size in inches,
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
warnings.warn("plot_state is deprecated, and will be removed in \
the 0.9 release. Use the plot_state_ * functions \
instead.",
DeprecationWarning)
# Check if input is a statevector, and convert to density matrix
rho = _validate_input_state(quantum_state)
fig = None
if method == 'city':
fig = plot_state_city(rho, figsize=figsize)
elif method == "paulivec":
fig = plot_state_paulivec(rho, figsize=figsize)
elif method == "qsphere":
fig = plot_state_qsphere(rho, figsize=figsize)
elif method == "bloch":
plot_bloch_multivector(rho, figsize=figsize)
elif method == "hinton":
fig = plot_state_hinton(rho, figsize=figsize)
return fig
|
[
"Plot",
"the",
"quantum",
"state",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L589-L624
|
[
"def",
"plot_state",
"(",
"quantum_state",
",",
"method",
"=",
"'city'",
",",
"figsize",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"'Must have Matplotlib installed.'",
")",
"warnings",
".",
"warn",
"(",
"\"plot_state is deprecated, and will be removed in \\\n the 0.9 release. Use the plot_state_ * functions \\\n instead.\"",
",",
"DeprecationWarning",
")",
"# Check if input is a statevector, and convert to density matrix",
"rho",
"=",
"_validate_input_state",
"(",
"quantum_state",
")",
"fig",
"=",
"None",
"if",
"method",
"==",
"'city'",
":",
"fig",
"=",
"plot_state_city",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"paulivec\"",
":",
"fig",
"=",
"plot_state_paulivec",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"qsphere\"",
":",
"fig",
"=",
"plot_state_qsphere",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"bloch\"",
":",
"plot_bloch_multivector",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"elif",
"method",
"==",
"\"hinton\"",
":",
"fig",
"=",
"plot_state_hinton",
"(",
"rho",
",",
"figsize",
"=",
"figsize",
")",
"return",
"fig"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
test
|
generate_facecolors
|
Generates shaded facecolors for shaded bars.
This is here to work around a Matplotlib bug
where alpha does not work in Bar3D.
Args:
x (array_like): The x- coordinates of the anchor point of the bars.
y (array_like): The y- coordinates of the anchor point of the bars.
z (array_like): The z- coordinates of the anchor point of the bars.
dx (array_like): Width of bars.
dy (array_like): Depth of bars.
dz (array_like): Height of bars.
color (array_like): sequence of valid color specifications, optional
Returns:
list: Shaded colors for bars.
|
qiskit/visualization/state_visualization.py
|
def generate_facecolors(x, y, z, dx, dy, dz, color):
"""Generates shaded facecolors for shaded bars.
This is here to work around a Matplotlib bug
where alpha does not work in Bar3D.
Args:
x (array_like): The x- coordinates of the anchor point of the bars.
y (array_like): The y- coordinates of the anchor point of the bars.
z (array_like): The z- coordinates of the anchor point of the bars.
dx (array_like): Width of bars.
dy (array_like): Depth of bars.
dz (array_like): Height of bars.
color (array_like): sequence of valid color specifications, optional
Returns:
list: Shaded colors for bars.
"""
cuboid = np.array([
# -z
(
(0, 0, 0),
(0, 1, 0),
(1, 1, 0),
(1, 0, 0),
),
# +z
(
(0, 0, 1),
(1, 0, 1),
(1, 1, 1),
(0, 1, 1),
),
# -y
(
(0, 0, 0),
(1, 0, 0),
(1, 0, 1),
(0, 0, 1),
),
# +y
(
(0, 1, 0),
(0, 1, 1),
(1, 1, 1),
(1, 1, 0),
),
# -x
(
(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(0, 1, 0),
),
# +x
(
(1, 0, 0),
(1, 1, 0),
(1, 1, 1),
(1, 0, 1),
),
])
# indexed by [bar, face, vertex, coord]
polys = np.empty(x.shape + cuboid.shape)
# handle each coordinate separately
for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:
p = p[..., np.newaxis, np.newaxis]
dp = dp[..., np.newaxis, np.newaxis]
polys[..., i] = p + dp * cuboid[..., i]
# collapse the first two axes
polys = polys.reshape((-1,) + polys.shape[2:])
facecolors = []
if len(color) == len(x):
# bar colors specified, need to expand to number of faces
for c in color:
facecolors.extend([c] * 6)
else:
# a single color specified, or face colors specified explicitly
facecolors = list(mcolors.to_rgba_array(color))
if len(facecolors) < len(x):
facecolors *= (6 * len(x))
normals = _generate_normals(polys)
return _shade_colors(facecolors, normals)
|
def generate_facecolors(x, y, z, dx, dy, dz, color):
"""Generates shaded facecolors for shaded bars.
This is here to work around a Matplotlib bug
where alpha does not work in Bar3D.
Args:
x (array_like): The x- coordinates of the anchor point of the bars.
y (array_like): The y- coordinates of the anchor point of the bars.
z (array_like): The z- coordinates of the anchor point of the bars.
dx (array_like): Width of bars.
dy (array_like): Depth of bars.
dz (array_like): Height of bars.
color (array_like): sequence of valid color specifications, optional
Returns:
list: Shaded colors for bars.
"""
cuboid = np.array([
# -z
(
(0, 0, 0),
(0, 1, 0),
(1, 1, 0),
(1, 0, 0),
),
# +z
(
(0, 0, 1),
(1, 0, 1),
(1, 1, 1),
(0, 1, 1),
),
# -y
(
(0, 0, 0),
(1, 0, 0),
(1, 0, 1),
(0, 0, 1),
),
# +y
(
(0, 1, 0),
(0, 1, 1),
(1, 1, 1),
(1, 1, 0),
),
# -x
(
(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(0, 1, 0),
),
# +x
(
(1, 0, 0),
(1, 1, 0),
(1, 1, 1),
(1, 0, 1),
),
])
# indexed by [bar, face, vertex, coord]
polys = np.empty(x.shape + cuboid.shape)
# handle each coordinate separately
for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:
p = p[..., np.newaxis, np.newaxis]
dp = dp[..., np.newaxis, np.newaxis]
polys[..., i] = p + dp * cuboid[..., i]
# collapse the first two axes
polys = polys.reshape((-1,) + polys.shape[2:])
facecolors = []
if len(color) == len(x):
# bar colors specified, need to expand to number of faces
for c in color:
facecolors.extend([c] * 6)
else:
# a single color specified, or face colors specified explicitly
facecolors = list(mcolors.to_rgba_array(color))
if len(facecolors) < len(x):
facecolors *= (6 * len(x))
normals = _generate_normals(polys)
return _shade_colors(facecolors, normals)
|
[
"Generates",
"shaded",
"facecolors",
"for",
"shaded",
"bars",
".",
"This",
"is",
"here",
"to",
"work",
"around",
"a",
"Matplotlib",
"bug",
"where",
"alpha",
"does",
"not",
"work",
"in",
"Bar3D",
".",
"Args",
":",
"x",
"(",
"array_like",
")",
":",
"The",
"x",
"-",
"coordinates",
"of",
"the",
"anchor",
"point",
"of",
"the",
"bars",
".",
"y",
"(",
"array_like",
")",
":",
"The",
"y",
"-",
"coordinates",
"of",
"the",
"anchor",
"point",
"of",
"the",
"bars",
".",
"z",
"(",
"array_like",
")",
":",
"The",
"z",
"-",
"coordinates",
"of",
"the",
"anchor",
"point",
"of",
"the",
"bars",
".",
"dx",
"(",
"array_like",
")",
":",
"Width",
"of",
"bars",
".",
"dy",
"(",
"array_like",
")",
":",
"Depth",
"of",
"bars",
".",
"dz",
"(",
"array_like",
")",
":",
"Height",
"of",
"bars",
".",
"color",
"(",
"array_like",
")",
":",
"sequence",
"of",
"valid",
"color",
"specifications",
"optional",
"Returns",
":",
"list",
":",
"Shaded",
"colors",
"for",
"bars",
"."
] |
Qiskit/qiskit-terra
|
python
|
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/state_visualization.py#L627-L710
|
[
"def",
"generate_facecolors",
"(",
"x",
",",
"y",
",",
"z",
",",
"dx",
",",
"dy",
",",
"dz",
",",
"color",
")",
":",
"cuboid",
"=",
"np",
".",
"array",
"(",
"[",
"# -z",
"(",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"1",
",",
"0",
")",
",",
"(",
"1",
",",
"1",
",",
"0",
")",
",",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
")",
",",
"# +z",
"(",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"(",
"1",
",",
"0",
",",
"1",
")",
",",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"(",
"0",
",",
"1",
",",
"1",
")",
",",
")",
",",
"# -y",
"(",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
"(",
"1",
",",
"0",
",",
"1",
")",
",",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
")",
",",
"# +y",
"(",
"(",
"0",
",",
"1",
",",
"0",
")",
",",
"(",
"0",
",",
"1",
",",
"1",
")",
",",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"(",
"1",
",",
"1",
",",
"0",
")",
",",
")",
",",
"# -x",
"(",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"(",
"0",
",",
"1",
",",
"1",
")",
",",
"(",
"0",
",",
"1",
",",
"0",
")",
",",
")",
",",
"# +x",
"(",
"(",
"1",
",",
"0",
",",
"0",
")",
",",
"(",
"1",
",",
"1",
",",
"0",
")",
",",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"(",
"1",
",",
"0",
",",
"1",
")",
",",
")",
",",
"]",
")",
"# indexed by [bar, face, vertex, coord]",
"polys",
"=",
"np",
".",
"empty",
"(",
"x",
".",
"shape",
"+",
"cuboid",
".",
"shape",
")",
"# handle each coordinate separately",
"for",
"i",
",",
"p",
",",
"dp",
"in",
"[",
"(",
"0",
",",
"x",
",",
"dx",
")",
",",
"(",
"1",
",",
"y",
",",
"dy",
")",
",",
"(",
"2",
",",
"z",
",",
"dz",
")",
"]",
":",
"p",
"=",
"p",
"[",
"...",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
"]",
"dp",
"=",
"dp",
"[",
"...",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
"]",
"polys",
"[",
"...",
",",
"i",
"]",
"=",
"p",
"+",
"dp",
"*",
"cuboid",
"[",
"...",
",",
"i",
"]",
"# collapse the first two axes",
"polys",
"=",
"polys",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
")",
"+",
"polys",
".",
"shape",
"[",
"2",
":",
"]",
")",
"facecolors",
"=",
"[",
"]",
"if",
"len",
"(",
"color",
")",
"==",
"len",
"(",
"x",
")",
":",
"# bar colors specified, need to expand to number of faces",
"for",
"c",
"in",
"color",
":",
"facecolors",
".",
"extend",
"(",
"[",
"c",
"]",
"*",
"6",
")",
"else",
":",
"# a single color specified, or face colors specified explicitly",
"facecolors",
"=",
"list",
"(",
"mcolors",
".",
"to_rgba_array",
"(",
"color",
")",
")",
"if",
"len",
"(",
"facecolors",
")",
"<",
"len",
"(",
"x",
")",
":",
"facecolors",
"*=",
"(",
"6",
"*",
"len",
"(",
"x",
")",
")",
"normals",
"=",
"_generate_normals",
"(",
"polys",
")",
"return",
"_shade_colors",
"(",
"facecolors",
",",
"normals",
")"
] |
d4f58d903bc96341b816f7c35df936d6421267d1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.