• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Quang00 / dqsweep / 13817498433

12 Mar 2025 05:16PM UTC coverage: 80.723% (-0.02%) from 80.747%
13817498433

push

github

Quang00
clean code

7 of 15 new or added lines in 2 files covered. (46.67%)

1 existing line in 1 file now uncovered.

402 of 498 relevant lines covered (80.72%)

1.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

60.32
/experiments/run_simulation.py
1
"""
2
Dqsweep
3
=======================================================
4

5
Overview:
6
---------
7
This script simulates distributed quantum experiments using a configurable
8
setup. It allows to sweep one or more parameters over defined ranges and then
9
execute multiple simulation runs for each parameter combination. For every run,
10
it calculates two performance metrics: the average fidelity (as a percentage)
11
and the average simulation time (in milliseconds).
12

13
Process:
14
--------
15
1. Parameter Sweep:
16
   - Generates all combinations of values for the specified parameters.
17
   - For each combination, it executes the simulation a certain amount of times
18
     which is configurable by the user and computes the mean fidelity and
19
     simulation time.
20

21
2. Data Generation:
22
   - Raw results and computed averages for each parameter combination are
23
     stored in a pandas DataFrame and saved as a CSV file.
24
   - Parameter–Performance Correlation txt file is provided and shows the
25
     correlations between the input parameters and the performance metrics.
26

27
3. Visualization:
28
   - 2D Heatmaps: These are generated for each performance metric based on
29
     each unique pair of swept parameters.
30

31
Usage:
32
------
33
Run the script with the following command-line arguments:
34

35
  --config         Path to the YAML config file that defines the network setup
36
  --experiment     Experiment to simulate (e.g., cnot, pingpong, dgrover2, ...)
37
  --epr_rounds     Number of EPR rounds per simulation
38
  --num_experiments Number of simulation runs per parameter combination
39
  --sweep_params   Comma-separated list of parameter names for the sweep.
40
  --ranges         For each swept parameter, provide a range in the format
41
                   "start,end,points", where start is the initial value, end
42
                   is the final value, and points is the number of values
43
                   (or steps) to generate between start and end.
44
  --output_dir     Directory where the CSV file, txt file and generated plots
45
                   will be saved.
46
"""
47

48
import argparse
2✔
49
import itertools
2✔
50
import os
2✔
51

52
import numpy as np
2✔
53
import pandas as pd
2✔
54

55
from experiments.dgrover_2 import AliceDGrover2, BobDGrover2
2✔
56
from experiments.dqft_2 import AliceDQFT2, BobDQFT2
2✔
57
from experiments.nonlocal_cnot import AliceProgram, BobProgram
2✔
58
from experiments.nonlocal_cnot_2_teleportations import (
2✔
59
    Alice2Teleportations,
60
    Bob2Teleportations,
61
)
62
from experiments.pingpong import (
2✔
63
    AlicePingpongTeleportation,
64
    BobPingpongTeleportation
65
)
66
from experiments.utils import (
2✔
67
    create_subdir,
68
    metric_correlation,
69
    parse_range,
70
    plot_combined_heatmaps,
71
    check_sweep_params_input
72
)
73
from squidasm.run.stack.config import StackNetworkConfig
2✔
74
from squidasm.run.stack.run import run
2✔
75

76

77
# =============================================================================
78
# Parameter Sweep Function
79
# =============================================================================
80
def sweep_parameters(
2✔
81
    cfg: StackNetworkConfig,
82
    epr_rounds: int,
83
    num_experiments: int,
84
    sweep_params: str,
85
    ranges: list,
86
    experiment: str,
87
    output_dir: str,
88
) -> pd.DataFrame:
89
    """Performs a parameter sweep, runs simulations, and stores results.
90

91
    Args:
92
        cfg (StackNetworkConfig): Network configuration.
93
        epr_rounds (int): Number of EPR rounds.
94
        num_experiments (int): Number of experiments per configuration.
95
        sweep_params (str): Parameters to sweep.
96
        ranges (list): Ranges for each parameter.
97
        experiment (str): Experiment name.
98
        output_dir (str): Directory to save results.
99

100
    Returns:
101
        pd.DataFrame: Dataframe of results.
102
    """
103
    os.makedirs(output_dir, exist_ok=True)
2✔
104

105
    param_ranges = {
2✔
106
        param: parse_range(rng_str, param)
107
        for param, rng_str in zip(sweep_params, ranges)
108
    }
109
    combinations = list(
2✔
110
        itertools.product(*[param_ranges[param] for param in sweep_params])
111
    )
112

113
    results = []
2✔
114
    alice_cls, bob_cls = {
2✔
115
        "2_teleportations": (Alice2Teleportations, Bob2Teleportations),
116
        "pingpong": (AlicePingpongTeleportation, BobPingpongTeleportation),
117
        "dqft2": (AliceDQFT2, BobDQFT2),
118
        "dgrover2": (AliceDGrover2, BobDGrover2),
119
    }.get(experiment, (AliceProgram, BobProgram))
120

121
    for comb in combinations:
2✔
122
        for param, value in zip(sweep_params, comb):
2✔
123
            for link in cfg.links:
2✔
124
                if getattr(link, "link_cfg", None) is not None:
2✔
NEW
125
                    link.cfg[param] = value
×
126
            for stack in cfg.stacks:
2✔
127
                if getattr(stack, "qdevice_cfg", None) is not None:
2✔
128
                    stack.qdevice_cfg[param] = value
2✔
129

130
        _, bob_results = run(
2✔
131
            config=cfg,
132
            programs={
133
                "Alice": alice_cls(num_epr_rounds=epr_rounds),
134
                "Bob": bob_cls(num_epr_rounds=epr_rounds),
135
            },
136
            num_times=num_experiments,
137
        )
138
        all_fid_results = [res[0] for res in bob_results]
2✔
139
        all_time_results = [res[1] for res in bob_results]
2✔
140

141
        avg_fid = np.mean(all_fid_results) * 100
2✔
142
        avg_time = np.mean(all_time_results)
2✔
143

144
        results.append(
2✔
145
            {
146
                **dict(zip(sweep_params, comb)),
147
                "Fidelity Results": all_fid_results,
148
                "Simulation Time Results": all_time_results,
149
                "Average Fidelity (%)": avg_fid,
150
                "Average Simulation Time (ms)": avg_time,
151
            }
152
        )
153

154
    df = pd.DataFrame(results)
2✔
155
    path = os.path.join(output_dir, f"{experiment}_results.csv")
2✔
156
    df.to_csv(path)
2✔
157
    return df
2✔
158

159

160
def main():
2✔
161
    """Main entry point for the Distributed Quantum Experiments Script.
162

163
    This function launches the simulation, starting from the parsing
164
    command-line arguments to generating performance plots (Heat maps),
165
    raw results (csv file), and correlation analysis (txt file).
166

167
    """
168
    parser = argparse.ArgumentParser(
×
169
        description="Simulate distributed quantum experiments"
170
    )
171
    parser.add_argument(
×
172
        "--config",
173
        type=str,
174
        default="configurations/perfect.yaml",
175
        help="Path to the configuration.",
176
    )
177
    parser.add_argument(
×
178
        "--experiment",
179
        type=str,
180
        default="cnot",
181
        help="Distributed experiments (e.g., cnot, pingpong, dgrover2, ...).",
182
    )
183
    parser.add_argument(
×
184
        "--epr_rounds", type=int, default=10, help="Number of EPR rounds."
185
    )
186
    parser.add_argument(
×
187
        "--num_experiments",
188
        type=int,
189
        default=10,
190
        help="Number of experiments per combination (default 10).",
191
    )
192
    parser.add_argument(
×
193
        "--sweep_params",
194
        type=str,
195
        default="single_qubit_gate_depolar_prob,two_qubit_gate_depolar_prob",
196
        help="Comma-separated list of configuration parameter names to sweep",
197
    )
198
    parser.add_argument(
×
199
        "--ranges",
200
        nargs="+",
201
        type=str,
202
        default=["0.0,0.8,10", "0.0,0.8,10"],
203
        help="One range string per parameter (format: 'start,end,points').",
204
    )
205
    parser.add_argument(
×
206
        "--output_dir", type=str, default="results", help="Output directory"
207
    )
208
    args = parser.parse_args()
×
209

210
    output_dir = create_subdir(
×
211
        args.output_dir,
212
        args.experiment,
213
        args.sweep_params
214
    )
215
    print(f"Using output directory: {output_dir}")
×
216

217
    cfg = StackNetworkConfig.from_file(args.config)
×
218

NEW
219
    check_sweep_params_input(args.sweep_params, cfg)
×
220

UNCOV
221
    if args.sweep_params and args.ranges:
×
222
        # Ensure the number of parameters matches the number of ranges
223
        sweep_params = [p.strip() for p in args.sweep_params.split(",")]
×
224
        if len(sweep_params) != len(args.ranges):
×
225
            raise ValueError(
×
226
                "Number of sweep parameters must match number of range strings"
227
            )
228

229
        # Run parameter sweep and generate results
230
        df = sweep_parameters(
×
231
            cfg,
232
            args.epr_rounds,
233
            args.num_experiments,
234
            sweep_params,
235
            args.ranges,
236
            args.experiment,
237
            output_dir=output_dir,
238
        )
239
        print("Sweep completed. Preview of results:")
×
240
        print(df.head())
×
241

242
        # Generate a txt file with the correlation values
243
        metric_correlation(
×
244
            df,
245
            sweep_params,
246
            ["Average Fidelity (%)", "Average Simulation Time (ms)"],
247
            output_dir,
248
            args.experiment,
249
        )
250

251
        # Build parameter range dictionary
252
        param_range_dict = {
×
253
            param: parse_range(rng_str, param)
254
            for param, rng_str in zip(sweep_params, args.ranges)
255
        }
256

257
        # Generate heat maps for each metrics or a combined heat map
258
        plot_combined_heatmaps(
×
259
            df,
260
            sweep_params,
261
            param_range_dict,
262
            output_dir,
263
            args.experiment,
264
            args.epr_rounds,
265
            separate_files=True,
266
        )
267

268

269
if __name__ == "__main__":
2✔
270
    main()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc