1.3 Entanglement Entropy by Classical Shadow#


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 ShadowUnveil

experiment_shadow = ShadowUnveil()

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_shadow.add(TrivialParamagnet(i), f"trivial_paramagnet_{i}")
    experiment_shadow.add(GHZ(i), f"ghz_{i}")
    experiment_shadow.add(make_neel_circuit(i), f"neel_{i}")

experiment_shadow.waves
WaveContainer({
  'trivial_paramagnet_2': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb740fe4590>,
  'ghz_2': <qurry.recipe.simple.cat.GHZ object at 0x7bb740fe46e0>,
  'neel_2': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe18d0>,
  'trivial_paramagnet_4': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb741076c10>,
  'ghz_4': <qurry.recipe.simple.cat.GHZ object at 0x7bb741076d50>,
  'neel_4': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe1b70>,
  'trivial_paramagnet_6': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb741076e90>,
  'ghz_6': <qurry.recipe.simple.cat.GHZ object at 0x7bb741076fd0>,
  'neel_6': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe19b0>,
  'trivial_paramagnet_8': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb740f995b0>,
  'ghz_8': <qurry.recipe.simple.cat.GHZ object at 0x7bb740f996e0>,
  'neel_8': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe1a90>,
  'trivial_paramagnet_10': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb740f99a70>,
  'ghz_10': <qurry.recipe.simple.cat.GHZ object at 0x7bb740f99ba0>,
  'neel_10': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe1390>,
  'trivial_paramagnet_12': <qurry.recipe.simple.paramagnet.TrivialParamagnet object at 0x7bb740ff0050>,
  'ghz_12': <qurry.recipe.simple.cat.GHZ object at 0x7bb740ff03b0>,
  'neel_12': <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x7bb740fe1c50>})

c. Execute multiple experiments at once#

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

from qurry.qurrent import ShadowUnveilMeasureArgs

Preparing a configuration list for multiple experiments with following parameters:

class ShadowUnveilMeasureArgs(BasicArgs, total=False):
    """Output arguments for :meth:`output`."""

    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 `generate_random_unitary_seeds`
    in `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[ShadowUnveilMeasureArgs] = [
    {
        "shots": 1024,
        "times": 100,
        "wave": f"{wave_names}_{i}",
        "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_shadow.multiOutput(
    config_list,
    summoner_name="qurshady",  # 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 "qurshady.001", at location "qurshady.001"
| MultiOutput running...
| Export multimanager...
| No quantity to export.
| Export multi.config.json for 12dc8911-d082-4e23-ac78-227ff89fee30
| Exporting qurshady.001/qurryinfo.json...
| Exporting qurshady.001/qurryinfo.json done.
'12dc8911-d082-4e23-ac78-227ff89fee30'

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

experiment_shadow.multimanagers
MultiManagerContainer(num=1, {
  "12dc8911-d082-4e23-ac78-227ff89fee30":
    <MultiManager(name="qurshady.001", jobstype="local", ..., exps_num=180)>,
})
experiment_shadow.multimanagers[multi_exps1]
<MultiManager(id="12dc8911-d082-4e23-ac78-227ff89fee30",
  name="qurshady.001",
  tags=(),
  jobstype="local",
  pending_strategy="tags",
  last_events={
    'output.001': '2025-06-26 11:49:39',},
  exps_num=180)>

d. Run post-processing at once#

experiment_shadow.multiAnalysis(
    summoner_id=multi_exps1,
    skip_write=True,
    multiprocess_write=False,
    selected_qubits=[0, 1],
)
| "report.001" has been completed.
'12dc8911-d082-4e23-ac78-227ff89fee30'
print("| Available results:")
for k, v in (
    experiment_shadow.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_shadow.multimanagers[multi_exps1].quantity_container["report.001"][
    ("trivial_paramagnet", "size_10")
][:2]
[{'classical_registers_actually': [1, 0],
  'taking_time': 0.006193876266479492,
  'mean_of_rho': array([[0.24935547+0.j        , 0.26351074-0.00563965j,
          0.24648926-0.00448242j, 0.27188965-0.00193359j],
         [0.26351074+0.00563965j, 0.24686523+0.j        ,
          0.26811035+0.j        , 0.24851074-0.00114258j],
         [0.24648926+0.00448242j, 0.26811035+0.j        ,
          0.25049805+0.j        , 0.26148926+0.00209473j],
         [0.27188965+0.00193359j, 0.24851074+0.00114258j,
          0.26148926-0.00209473j, 0.25328125+0.j        ]]),
  'purity': np.float64(1.0304237261685458),
  'entropy': np.float64(-0.043237717928150676),
  'estimate_of_given_operators': [],
  'accuracy_prob_comp_delta': nan,
  'num_of_estimators_k': 0,
  'accuracy_predict_epsilon': nan,
  'maximum_shadow_norm': nan,
  'input': {'shots': 1024,
   '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},
   'unitary_located': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
  'header': {'serial': 0, 'datetime': '2025-06-26 11:49:47', 'log': {}}},
 {'classical_registers_actually': [1, 0],
  'taking_time': 0.006423473358154297,
  'mean_of_rho': array([[0.24625   +0.j        , 0.31937988-0.00496582j,
          0.22952637+0.00342773j, 0.29030273+0.00549316j],
         [0.31937988+0.00496582j, 0.24745117+0.j        ,
          0.29469727+0.00268066j, 0.22047363-0.00123047j],
         [0.22952637-0.00342773j, 0.29469727-0.00268066j,
          0.2574707 +0.j        , 0.32562012+0.00733887j],
         [0.29030273-0.00549316j, 0.22047363+0.00123047j,
          0.32562012-0.00733887j, 0.24882812+0.j        ]]),
  'purity': np.float64(1.1775472571633079),
  'entropy': np.float64(-0.23578495903728053),
  'estimate_of_given_operators': [],
  'accuracy_prob_comp_delta': nan,
  'num_of_estimators_k': 0,
  'accuracy_predict_epsilon': nan,
  'maximum_shadow_norm': nan,
  'input': {'shots': 1024,
   '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},
   'unitary_located': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]},
  'header': {'serial': 0, 'datetime': '2025-06-26 11:49:47', '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_shadow.multimanagers[multi_exps1].exps.keys())
print(len(expkeys_of_multi_exps1))
print("| The number of exp_id:", len(expkeys_of_multi_exps1))
print("| First 3 experiment keys:")
expkeys_of_multi_exps1[:3]
180
| The number of exp_id: 180
| First 3 experiment keys:
['68c3d6eb-894c-4f6d-a9d8-2dfd249c24d9',
 '3de570ad-3d1e-4c76-ab7d-39d9927ee6a4',
 '03c33ee8-3e48-4645-b6aa-0996c5cedd82']
  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_shadow.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.
'12dc8911-d082-4e23-ac78-227ff89fee30'
print("| Available results:")
print(
    "| length:",
    sum(
        len(v)
        for v in experiment_shadow.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_shadow.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 12dc8911-d082-4e23-ac78-227ff89fee30
| Exporting qurshady.001/qurryinfo.json...
| Exporting qurshady.001/qurryinfo.json done.
'12dc8911-d082-4e23-ac78-227ff89fee30'
print("| Available results:")
print(
    "| length:",
    sum(
        len(v)
        for v in experiment_shadow.multimanagers[multi_exps1]
        .quantity_container["all_manual.001"]
        .values()
    ),
)
| Available results:
| length: 180

All multiAnalysis results#

experiment_shadow.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_shadow.multiRead(
    save_location=".",
    summoner_name="qurshady.001",
)
| Retrieve qurshady.001...
| at: qurshady.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>