1.2 Entanglement Entropy by Randomized Measurement#


Multiple Experiments#

Consider a scenario, you have multiple circuits that you want to run at once.

Call .measure() one by one will be inefficient, no to mention that you also need to call .anlyze() for their post-processing.

Here we provide a more efficient way solve this problem, where the true power of Qurrium as experiment manage toolkit.

a. Import the instances#

from qurry import EntropyMeasure

experiment_randomized = EntropyMeasure()
# It's default method. EntropyMeasure(method='randomized') also works

b. Preparing quantum circuit#

Prepare and add circuits to the .wave for later usage.

from qiskit import QuantumCircuit
from qurry.recipe import TrivialParamagnet, GHZ


def make_neel_circuit(n):
    qc = QuantumCircuit(n)
    for i in range(0, n, 2):
        qc.x(i)
    return qc


for i in range(2, 13, 2):
    experiment_randomized.add(TrivialParamagnet(i), f"trivial_paramagnet_{i}")
    experiment_randomized.add(GHZ(i), f"ghz_{i}")
    experiment_randomized.add(make_neel_circuit(i), f"neel_{i}")

experiment_randomized.waves
WaveContainer({
  'trivial_paramagnet_2': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d6317c8590>,
  'ghz_2': <qurry.recipe.simple.cat.GHZ object at 0x70d6317c86e0>,
  'neel_2': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c58d0>,
  'trivial_paramagnet_4': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d631a56c10>,
  'ghz_4': <qurry.recipe.simple.cat.GHZ object at 0x70d631a56d50>,
  'neel_4': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c5b70>,
  'trivial_paramagnet_6': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d631a56e90>,
  'ghz_6': <qurry.recipe.simple.cat.GHZ object at 0x70d631a56fd0>,
  'neel_6': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c59b0>,
  'trivial_paramagnet_8': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d63195d6e0>,
  'ghz_8': <qurry.recipe.simple.cat.GHZ object at 0x70d63195d810>,
  'neel_8': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c5a90>,
  'trivial_paramagnet_10': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d63195dba0>,
  'ghz_10': <qurry.recipe.simple.cat.GHZ object at 0x70d63195dcd0>,
  'neel_10': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c5390>,
  'trivial_paramagnet_12': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x70d6317d0050>,
  'ghz_12': <qurry.recipe.simple.cat.GHZ object at 0x70d6317d03b0>,
  'neel_12': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x70d6317c5c50>})

c. Execute multiple experiments at once#

Letโ€™s demonstrate the true power of Qurrium.

from qurry.qurrent import EntropyMeasureRandomizedMeasureArgs

Preparing a configuration list for multiple experiments with following parameters:

class EntropyMeasureRandomizedMeasureArgs(total=False):
    """Output arguments for :meth:`output`."""
    shots: int
    """Number of shots."""
    tags: Optional[tuple[str, ...]]
    """The tags to be used for the experiment."""

    wave: Optional[Union[QuantumCircuit, Hashable]]
    """The key or the circuit to execute."""
    times: int
    """The number of random unitary operator.
    It will denote as `N_U` in the experiment name."""
    measure: Optional[Union[tuple[int, int], int, list[int]]]
    """The measure range."""
    unitary_loc: Optional[Union[tuple[int, int], int, list[int]]]
    """The range of the unitary operator."""
    unitary_loc_not_cover_measure: bool
    """Whether the range of the unitary operator is not cover the measure range."""
    random_unitary_seeds: Optional[dict[int, dict[int, int]]]
    """The seeds for all random unitary operator.
    This argument only takes input as type of `dict[int, dict[int, int]]`.
    The first key is the index for the random unitary operator.
    The second key is the index for the qubit.

    .. code-block:: python
        {
            0: {0: 1234, 1: 5678},
            1: {0: 2345, 1: 6789},
            2: {0: 3456, 1: 7890},
        }

    If you want to generate the seeds for all random unitary operator,
    you can use the function :func:`generate_random_unitary_seeds`
    in :mod:`qurry.qurrium.utils.random_unitary`.

    .. code-block:: python
        from qurry.qurrium.utils.random_unitary import generate_random_unitary_seeds

        random_unitary_seeds = generate_random_unitary_seeds(100, 2)
    """
config_list: list[EntropyMeasureRandomizedMeasureArgs] = [
    {
        "shots": 1024,
        "wave": f"{wave_names}_{i}",
        "times": 100,
        "tags": (wave_names, f"size_{i}"),
    }
    for _ in range(10)
    for i in range(2, 13, 2)
    for wave_names in ["trivial_paramagnet", "ghz", "neel"]
]
print(len(config_list))
180

The .multiOutput will return an id of this multimanager instance, which can be used to get the results and post-process them.

Each multimanager will export the experiments in a folder you can specify by setting save_location parameter with default location for current directory where Python executed. It will create a folder with the name of the multimanager instance, and inside it will create a folder for storing each experiment data.

It will do firstly in the building process, but you can skip it by setting skip_build_write=True to save time. After all experiments are executed, it will export secondly, which can also be skipped by setting skip_output_write=True for no files output.

multi_exps1 = experiment_randomized.multiOutput(
    config_list,
    summoner_name="qurrent.randomized_measure",  # you can name it whatever you want
    multiprocess_build=True,
    # Using multiprocessing to build the experiments,
    # it will be faster but take all the CPU
    skip_build_write=True,
    # Skip the writing of the experiment as files during the build,
    save_location=".",
    # Save the experiment as files in the current directory
    multiprocess_write=True,
    # Writing the experiment as files using multiprocessing,
)
multi_exps1
| MultiManager building...
| Write "qurrent.randomized_measure.001", at location "qurrent.randomized_measure.001"
| MultiOutput running...
| Export multimanager...
| No quantity to export.
| Export multi.config.json for 2dbe7143-71a1-47a8-92d3-fafb1ab7a37e
| Exporting qurrent.randomized_measure.001/qurryinfo.json...
| Exporting qurrent.randomized_measure.001/qurryinfo.json done.
'2dbe7143-71a1-47a8-92d3-fafb1ab7a37e'

You can check the result of multiOutput that we just executed by accessing the .multimanagers

experiment_randomized.multimanagers
MultiManagerContainer(num=1, {
  "2dbe7143-71a1-47a8-92d3-fafb1ab7a37e":
    <MultiManager(name="qurrent.randomized_measure.001", jobstype="local", ..., exps_num=180)>,
})
experiment_randomized.multimanagers[multi_exps1]
<MultiManager(id="2dbe7143-71a1-47a8-92d3-fafb1ab7a37e",
  name="qurrent.randomized_measure.001",
  tags=(),
  jobstype="local",
  pending_strategy="tags",
  last_events={
    'output.001': '2025-06-26 11:48:34',},
  exps_num=180)>

d. Run post-processing at once#

experiment_randomized.multiAnalysis(
    summoner_id=multi_exps1,
    skip_write=True,
    multiprocess_write=False,
    selected_qubits=[0, 1],
)
| "report.001" has been completed.
'2dbe7143-71a1-47a8-92d3-fafb1ab7a37e'
print("| Available results:")
for k, v in (
    experiment_randomized.multimanagers[multi_exps1]
    .quantity_container["report.001"]
    .items()
):
    print("| -", k, "with length", len(v))
| Available results:
| - ('trivial_paramagnet', 'size_2') with length 10
| - ('ghz', 'size_2') with length 10
| - ('neel', 'size_2') with length 10
| - ('trivial_paramagnet', 'size_4') with length 10
| - ('ghz', 'size_4') with length 10
| - ('neel', 'size_4') with length 10
| - ('trivial_paramagnet', 'size_6') with length 10
| - ('ghz', 'size_6') with length 10
| - ('neel', 'size_6') with length 10
| - ('trivial_paramagnet', 'size_8') with length 10
| - ('ghz', 'size_8') with length 10
| - ('neel', 'size_8') with length 10
| - ('trivial_paramagnet', 'size_10') with length 10
| - ('ghz', 'size_10') with length 10
| - ('neel', 'size_10') with length 10
| - ('trivial_paramagnet', 'size_12') with length 10
| - ('ghz', 'size_12') with length 10
| - ('neel', 'size_12') with length 10
  • Example of the content of quantity_container

experiment_randomized.multimanagers[multi_exps1].quantity_container["report.001"][
    ("trivial_paramagnet", "size_10")
][:2]
[{'purity': np.float64(0.9761892509460449),
  'entropy': np.float64(0.03476722892939162),
  'puritySD': np.float64(0.675373474123654),
  'entropySD': np.float64(0.9981240429782198),
  'num_classical_registers': 10,
  'classical_registers': [0, 1],
  'classical_registers_actually': [0, 1],
  'all_system_source': 'independent',
  'purityAllSys': np.float64(1.9131527519226075),
  'entropyAllSys': np.float64(-0.9359520674337983),
  'puritySDAllSys': np.float64(1.6666545434857554),
  'entropySDAllSys': np.float64(1.2568124747726503),
  'num_classical_registers_all_sys': 10,
  'classical_registers_all_sys': None,
  'classical_registers_actually_all_sys': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  'errorRate': np.float64(-0.38349028704884824),
  'mitigatedPurity': np.float64(0.6294002277450859),
  'mitigatedEntropy': np.float64(0.6679503942194932),
  'counts_num': 100,
  'taking_time': 0.000538504,
  'taking_time_all_sys': 0.022669253,
  'counts_used': None,
  'input': {'num_qubits': 10,
   'selected_qubits': [0, 1],
   'registers_mapping': {0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9},
   'bitstring_mapping': {0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9},
   'shots': 1024,
   'unitary_located': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
  'header': {'serial': 0, 'datetime': '2025-06-26 11:48:43', 'log': {}}},
 {'purity': np.float64(1.0287687301635742),
  'entropy': np.float64(-0.04091869715296783),
  'puritySD': np.float64(0.6768308840830503),
  'entropySD': np.float64(0.9491545877680908),
  'num_classical_registers': 10,
  'classical_registers': [0, 1],
  'classical_registers_actually': [0, 1],
  'all_system_source': 'independent',
  'purityAllSys': np.float64(1.8064389419555664),
  'entropyAllSys': np.float64(-0.8531484921760617),
  'puritySDAllSys': np.float64(1.9236320679094456),
  'entropySDAllSys': np.float64(1.5362902007989385),
  'num_classical_registers_all_sys': 10,
  'classical_registers_all_sys': None,
  'classical_registers_actually_all_sys': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  'errorRate': np.float64(-0.34433152526328686),
  'mitigatedPurity': np.float64(0.6809190945646459),
  'mitigatedEntropy': np.float64(0.5544447045860224),
  'counts_num': 100,
  'taking_time': 0.000613604,
  'taking_time_all_sys': 0.024777519,
  'counts_used': None,
  'input': {'num_qubits': 10,
   'selected_qubits': [0, 1],
   'registers_mapping': {0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9},
   'bitstring_mapping': {0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9},
   'shots': 1024,
   'unitary_located': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
  'header': {'serial': 0, 'datetime': '2025-06-26 11:48:44', 'log': {}}}]

e. Run post-processing at once with specific analysis arguments#

At first, we need to get the each experimentโ€™s id in the multimanager instance.

expkeys_of_multi_exps1 = list(
    experiment_randomized.multimanagers[multi_exps1].exps.keys()
)
print("| The number of exp_id:", len(expkeys_of_multi_exps1))
print("| First 3 experiment keys:")
expkeys_of_multi_exps1[:3]
| The number of exp_id: 180
| First 3 experiment keys:
['4ddfd461-83b4-4fed-a06b-013dff1b8ce7',
 '92963649-6d3d-418c-8998-4bc0b7d31b88',
 'de75d45c-5e43-4e6d-baa7-2c7520e14443']
  1. If you want to run the post-processing for some specific experiments, for example, the first 3 experiments we get for the multimanager instance.

experiment_randomized.multiAnalysis(
    summoner_id=multi_exps1,
    analysis_name="first_3",
    skip_write=True,
    multiprocess_write=False,
    specific_analysis_args={
        k: (
            {
                "selected_qubits": [0, 1],
            }
            if idx < 3
            else False  # Give False to skip analysis for this experiment
        )
        for idx, k in enumerate(expkeys_of_multi_exps1)
    },
)
| "first_3.001" has been completed.
'2dbe7143-71a1-47a8-92d3-fafb1ab7a37e'
print("| Available results:")
print(
    "| length:",
    sum(
        len(v)
        for v in experiment_randomized.multimanagers[multi_exps1]
        .quantity_container["first_3.001"]
        .values()
    ),
)
| Available results:
| length: 3
  1. Or manually specify all the analysis arguments for each experiment.

experiment_randomized.multiAnalysis(
    summoner_id=multi_exps1,
    skip_write=False,
    analysis_name="all_manual",
    multiprocess_write=True,
    specific_analysis_args={
        k: {
            "selected_qubits": [0, 1],  # selected qubits for the analysis
        }
        for idx, k in enumerate(expkeys_of_multi_exps1)
    },
)
| "all_manual.001" has been completed.
| Export multimanager...
| Export multi.config.json for 2dbe7143-71a1-47a8-92d3-fafb1ab7a37e
| Exporting qurrent.randomized_measure.001/qurryinfo.json...
| Exporting qurrent.randomized_measure.001/qurryinfo.json done.
'2dbe7143-71a1-47a8-92d3-fafb1ab7a37e'
print("| Available results:")
print(
    "| length:",
    sum(
        len(v)
        for v in experiment_randomized.multimanagers[multi_exps1]
        .quantity_container["all_manual.001"]
        .values()
    ),
)
| Available results:
| length: 180

All multiAnalysis results#

experiment_randomized.multimanagers[multi_exps1].quantity_container.keys()
dict_keys(['report.001', 'first_3.001', 'all_manual.001'])

f. Read exported multimanager data#

multi_exps1_reades = experiment_randomized.multiRead(
    save_location=".",
    summoner_name="qurrent.randomized_measure.001",
)
| Retrieve qurrent.randomized_measure.001...
| at: qurrent.randomized_measure.001

Post-Process Availablities and Version Info#

from qurry.process import AVAIBILITY_STATESHEET

AVAIBILITY_STATESHEET
 | Qurrium version: 0.13.0
---------------------------------------------------------------------------
 ### Qurrium Post-Processing
   - Backend Availability ................... Python Cython Rust   JAX   
 - randomized_measure
   - entangled_entropy.entropy_core_2 ....... Yes    Depr.  Yes    No    
   - entangle_entropy.purity_cell_2 ......... Yes    Depr.  Yes    No    
   - entangled_entropy_v1.entropy_core ...... Yes    Depr.  Yes    No    
   - entangle_entropy_v1.purity_cell ........ Yes    Depr.  Yes    No    
   - wavefunction_overlap.echo_core_2 ....... Yes    Depr.  Yes    No    
   - wavefunction_overlap.echo_cell_2 ....... Yes    Depr.  Yes    No    
   - wavefunction_overlap_v1.echo_core ...... Yes    Depr.  Yes    No    
   - wavefunction_overlap_v1.echo_cell ...... Yes    Depr.  Yes    No    
 - hadamard_test
   - purity_echo_core ....................... Yes    No     Yes    No    
 - magnet_square
   - magnsq_core ............................ Yes    No     Yes    No    
 - string_operator
   - strop_core ............................. Yes    No     Yes    No    
 - classical_shadow
   - rho_m_core ............................. Yes    No     No     Yes   
 - utils
   - randomized ............................. Yes    Depr.  Yes    No    
   - counts_process ......................... Yes    No     Yes    No    
   - bit_slice .............................. Yes    No     Yes    No    
   - dummy .................................. Yes    No     Yes    No    
   - test ................................... Yes    No     Yes    No    
---------------------------------------------------------------------------
   + Yes ...... Working normally.
   + Error .... Exception occurred.
   + No ....... Not supported.
   + Depr. .... Deprecated.
---------------------------------------------------------------------------
by <Hoshi>