Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
440 changes: 396 additions & 44 deletions src/braket/default_simulator/openqasm/interpreter.py

Large diffs are not rendered by default.

96 changes: 77 additions & 19 deletions src/braket/default_simulator/openqasm/program_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,17 +168,19 @@ def validate_qubit_in_range(qubit: int):
if len(primary_index) != 1:
raise IndexError("Cannot index multiple dimensions for qubits.")
primary_index = primary_index[0]
# Index the tuple of qubits directly rather than a numpy array of it, so that the
# qubits stay plain ints, which results can serialize.
if isinstance(primary_index, IntegerLiteral):
validate_qubit_in_range(primary_index.value)
target = (self[name][primary_index.value],)
elif isinstance(primary_index, RangeDefinition):
target = tuple(np.array(self[name])[convert_range_def_to_slice(primary_index)])
target = tuple(self[name][convert_range_def_to_slice(primary_index)])
# Discrete set
else:
indices = convert_discrete_set_to_list(primary_index)
for index in indices:
validate_qubit_in_range(index)
target = tuple(np.array(self[name])[indices])
target = tuple(self[name][index] for index in indices)

if len(identifier.indices) == 1:
return target
Expand Down Expand Up @@ -609,6 +611,18 @@ def pop_scope(self) -> None:
self.gate_table.pop_scope()
self._mcm_dependent_scopes.pop()

def declare_temporary(self, name: str, value: LiteralType) -> None:
"""Store an expression temporary without declaring a measurement register."""
self.declare_variable(name, type(value), value)

def discard_temporary(self, name: str) -> None:
"""Remove a consumed expression temporary from its declaration scope."""
for table in (self.symbol_table, self.variable_table):
for scope in table._scopes:
scope.pop(name, None)
for scope in self._mcm_dependent_scopes:
scope.discard(name)

@property
def in_global_scope(self):
return self.symbol_table.in_global_scope
Expand Down Expand Up @@ -799,6 +813,27 @@ def add_qubits(self, name: str, num_qubits: int | None = 1) -> None:
self.num_qubits += num_qubits
self.declare_qubit_alias(name, Identifier(name))

def add_local_qubits(self, name: str, qubits: tuple[int, ...]) -> Identifier:
"""
Add the qubits of an alias that is declared in an inner scope, such as a subroutine
body, under a register name that no program can use.

The qubit mapping is not scoped, so a register named ``name`` would replace a register
or alias of the same name from an enclosing scope, which arguments may refer to, and
would outlive the alias. The name holds the depth of the current scope, so an alias
with the same name in a nested scope gets its own register.

Args:
name (str): The name of the alias.
qubits (tuple[int, ...]): The indices of the qubits the alias refers to.

Returns:
Identifier: The identifier of the register that holds the qubits.
"""
register = Identifier(f"{len(self.symbol_table._scopes) - 1}{name}")
self.qubit_mapping[register.name] = qubits
return register

def get_qubits(self, qubits: Identifier | IndexedIdentifier) -> tuple[int]:
"""
Get qubit indices from a qubit identifier, possibly referring to a sub-index of
Expand Down Expand Up @@ -1314,6 +1349,22 @@ def __init__(self, circuit: Circuit | None = None, simulator: BaseLocalSimulator
self._batch_size: int = 1
self._pending_mcm_targets: list[_PendingMeasurement] = []

def push_scope(self) -> None:
super().push_scope()
self._enter_frame_for_active_paths()

def pop_scope(self) -> None:
self._exit_frame_for_active_paths()
super().pop_scope()

def declare_temporary(self, name: str, value: LiteralType) -> None:
self._store_variable(name, type(value), value, False)

def discard_temporary(self, name: str) -> None:
super().discard_temporary(name)
for path in self._paths:
path.variables.pop(name, None)

@property
def circuit(self):
self._flush_pending_mcm_targets()
Expand Down Expand Up @@ -1435,6 +1486,7 @@ def _store_variable(

# Symbol table is shared across paths (type info only)
self.symbol_table.add_symbol(name, symbol_type, const)
self.variable_table.add_variable(name, None)
# Store value per-path as a FramedVariable
for path_idx in self._active_path_indices:
path = self._paths[path_idx]
Expand Down Expand Up @@ -1545,11 +1597,13 @@ def is_initialized(self, name: str) -> bool:
return super().is_initialized(name)

def _bound_in_inner_scope(self, name: str) -> bool:
"""Whether ``name`` is bound to a value in a non-global variable-table scope."""
return any(
not is_none_like(scope[name])
for scope in self.variable_table._scopes[1:]
if name in scope
"""Whether a scoped qubit alias shadows the per-path classical binding."""
return (
any(
name in scope and not is_none_like(scope[name])
for scope in self.variable_table._scopes[1:]
)
and self.get_type(name) is Identifier
)

def _flush_pending_mcm_for_variable(self, name: str) -> None:
Expand Down Expand Up @@ -1912,10 +1966,12 @@ def iter_classical_scopes(self, expression):
return

saved_active = list(self._active_path_indices)
surviving_paths = []
for path_idx in saved_active:
self._focus_on_path(path_idx)
yield
self._active_path_indices = saved_active
surviving_paths.extend(self._active_path_indices)
self._active_path_indices = surviving_paths

def evaluate_condition(self, condition):
"""Evaluate a branching condition, yielding per-path branch decisions.
Expand Down Expand Up @@ -2194,17 +2250,19 @@ def _initialize_paths_from_circuit(self) -> None:
initial_path._instructions = [copy(ins) for ins in self._circuit.instructions]
initial_path.shots = self._shots

for name, value in self.variable_table.items():
var_type = self.get_type(name)
is_const = self.get_const(name)
fv = FramedVariable(
name=name,
var_type=var_type,
value=value,
is_const=bool(is_const),
frame_number=initial_path.frame_number,
)
initial_path.set_variable(name, fv)
for frame_number, (variables, symbols) in enumerate(
zip(self.variable_table._scopes, self.symbol_table._scopes, strict=True)
):
for name, value in variables.items():
symbol = symbols[name]
fv = FramedVariable(
name=name,
var_type=symbol.type,
value=value,
is_const=bool(symbol.const),
frame_number=frame_number,
)
initial_path.set_variable(name, fv)

def _branch_measurement(
self,
Expand Down
16 changes: 13 additions & 3 deletions src/braket/default_simulator/openqasm/simulation_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(self, name: str, var_type: Any, value: Any, is_const: bool, frame_n
self._value = value
self._is_const = is_const
self._frame_number = frame_number
self.previous: FramedVariable | None = None

@property
def name(self) -> str:
Expand Down Expand Up @@ -149,9 +150,13 @@ def exit_frame(self, previous_frame: int) -> None:
Removes all variables declared in frames newer than `previous_frame`
and restores the frame number.
"""
self._variables = {
name: var for name, var in self._variables.items() if var.frame_number <= previous_frame
}
restored = {}
for name, var in self._variables.items():
while var is not None and var.frame_number > previous_frame:
var = var.previous
if var is not None:
restored[name] = var
self._variables = restored
self._frame_number = previous_frame

def add_instruction(self, instruction: GateOperation | KrausOperation) -> None:
Expand All @@ -160,6 +165,11 @@ def add_instruction(self, instruction: GateOperation | KrausOperation) -> None:

def set_variable(self, name: str, var: FramedVariable) -> None:
"""Set a classical variable in this path's variable state."""
previous = self._variables.get(name)
if previous is not None and previous.frame_number < var.frame_number:
var.previous = previous
elif previous is not None and previous.frame_number == var.frame_number:
var.previous = previous.previous
self._variables[name] = var

def get_variable(self, name: str) -> FramedVariable | None:
Expand Down
Loading