qubasic 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. qbasic.py +113 -0
  2. qbasic_core/__init__.py +80 -0
  3. qbasic_core/__main__.py +6 -0
  4. qbasic_core/analysis.py +179 -0
  5. qbasic_core/backend.py +76 -0
  6. qbasic_core/classic.py +419 -0
  7. qbasic_core/control_flow.py +576 -0
  8. qbasic_core/debug.py +327 -0
  9. qbasic_core/demos.py +356 -0
  10. qbasic_core/display.py +274 -0
  11. qbasic_core/engine.py +126 -0
  12. qbasic_core/engine_state.py +109 -0
  13. qbasic_core/errors.py +37 -0
  14. qbasic_core/exec_context.py +24 -0
  15. qbasic_core/executor.py +861 -0
  16. qbasic_core/expression.py +228 -0
  17. qbasic_core/file_io.py +457 -0
  18. qbasic_core/gates.py +284 -0
  19. qbasic_core/help_text.py +167 -0
  20. qbasic_core/io_protocol.py +33 -0
  21. qbasic_core/locc.py +10 -0
  22. qbasic_core/locc_commands.py +221 -0
  23. qbasic_core/locc_display.py +61 -0
  24. qbasic_core/locc_engine.py +195 -0
  25. qbasic_core/locc_execution.py +389 -0
  26. qbasic_core/memory.py +369 -0
  27. qbasic_core/mock_backend.py +66 -0
  28. qbasic_core/noise_mixin.py +96 -0
  29. qbasic_core/parser.py +564 -0
  30. qbasic_core/patterns.py +186 -0
  31. qbasic_core/profiler.py +156 -0
  32. qbasic_core/program_mgmt.py +369 -0
  33. qbasic_core/protocol.py +77 -0
  34. qbasic_core/py.typed +0 -0
  35. qbasic_core/scope.py +74 -0
  36. qbasic_core/screen.py +115 -0
  37. qbasic_core/state_display.py +60 -0
  38. qbasic_core/statements.py +387 -0
  39. qbasic_core/strings.py +107 -0
  40. qbasic_core/subs.py +261 -0
  41. qbasic_core/sweep.py +82 -0
  42. qbasic_core/terminal.py +1697 -0
  43. qubasic-0.1.0.dist-info/METADATA +736 -0
  44. qubasic-0.1.0.dist-info/RECORD +48 -0
  45. qubasic-0.1.0.dist-info/WHEEL +5 -0
  46. qubasic-0.1.0.dist-info/entry_points.txt +2 -0
  47. qubasic-0.1.0.dist-info/licenses/LICENSE +21 -0
  48. qubasic-0.1.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,736 @@
1
+ Metadata-Version: 2.4
2
+ Name: qubasic
3
+ Version: 0.1.0
4
+ Summary: Quantum BASIC Interactive Terminal
5
+ Author-email: "Charles C. Norton" <machineelv@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/CharlesCNorton/qbasic
8
+ Project-URL: Repository, https://github.com/CharlesCNorton/qbasic
9
+ Project-URL: Issues, https://github.com/CharlesCNorton/qbasic/issues
10
+ Keywords: quantum,computing,qiskit,basic,repl,simulator
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Physics
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: qiskit>=1.0
24
+ Requires-Dist: qiskit-aer>=0.13
25
+ Requires-Dist: numpy>=1.24
26
+ Requires-Dist: psutil>=5.9
27
+ Requires-Dist: rich>=13.0
28
+ Provides-Extra: charts
29
+ Requires-Dist: plotille>=5.0; extra == "charts"
30
+ Dynamic: license-file
31
+
32
+ # QBASIC
33
+
34
+ Quantum computing in a BASIC REPL.
35
+
36
+ ```
37
+ ] 10 H 0
38
+ ] 20 CX 0,1
39
+ ] 30 MEASURE
40
+ ] RUN
41
+
42
+ RAN 3 lines, 4 qubits, 1024 shots in 0.12s [depth=2, gates=2]
43
+
44
+ State Count % Distribution
45
+ |00> 518 50.6% ██████████████████
46
+ |11> 506 49.4% █████████████████
47
+ ```
48
+
49
+ QBASIC is a quantum computing environment built on Qiskit Aer that uses BASIC syntax for circuit construction, execution, and analysis. It runs as an interactive REPL, as a script interpreter, or as a headless Python engine.
50
+
51
+ **For agents**: minimal syntax, maximum context-window efficiency. `10 H 0 / 20 CX 0,1 / 30 MEASURE / RUN` replaces 8 lines of Qiskit Python. JSON output mode (`--json`) for pipeline integration. `Engine` class for direct API use without subprocess overhead.
52
+
53
+ **For humans**: type `DEMO GROVER` and get a working 3-qubit search algorithm you can LIST, edit, and re-RUN. Type `STEP` to watch the statevector evolve line by line. Type `REWIND 3` to go back. No imports, no boilerplate, no compile step.
54
+
55
+ ---
56
+
57
+ ## Install
58
+
59
+ ```
60
+ pip install -e ".[charts]"
61
+ ```
62
+
63
+ Requires Python >= 3.10, Qiskit >= 1.0, qiskit-aer >= 0.13.
64
+
65
+ ## Usage
66
+
67
+ ```
68
+ python qbasic.py Interactive REPL
69
+ python qbasic.py script.qb Run a script file
70
+ python qbasic.py --quiet script Suppress banner, output results only
71
+ python qbasic.py --json script Machine-readable JSON output
72
+ python qbasic.py --help Show CLI help
73
+ ```
74
+
75
+ Headless (no REPL):
76
+
77
+ ```python
78
+ from qbasic_core.engine_state import Engine
79
+ from qbasic_core.terminal import QBasicTerminal
80
+
81
+ t = QBasicTerminal()
82
+ t.num_qubits = 2
83
+ t.process('10 H 0', track_undo=False)
84
+ t.process('20 CX 0,1', track_undo=False)
85
+ t.process('30 MEASURE', track_undo=False)
86
+ t.cmd_run()
87
+ print(t.last_counts) # {'00': 512, '11': 512}
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Program editing
93
+
94
+ ```
95
+ 10 H 0 Enter a numbered line
96
+ 10 Delete line 10
97
+ LIST Show the program
98
+ LIST SUBS Show subroutine definitions
99
+ LIST VARS Show variables with types
100
+ LIST ARRAYS Show arrays with sizes
101
+ DELETE 10 Delete line 10
102
+ DELETE 10-50 Delete range
103
+ RENUM Renumber lines (10, 20, 30, ...)
104
+ RENUM 100 5 Renumber starting at 100, step 5
105
+ NEW Clear everything
106
+ UNDO Undo last edit
107
+ SAVE file.qb Save program to file
108
+ LOAD file.qb Load program from file
109
+ INCLUDE file.qb Merge lines from file
110
+ IMPORT "lib.qb" Load DEFs with namespace (LIB.NAME)
111
+ CHAIN "file.qb" Load and run, preserving variables
112
+ MERGE "file.qb" Merge without clearing
113
+ DIR List .qb files
114
+ AUTO Auto-generate line numbers
115
+ AUTO 100, 5 Start at 100, step 5
116
+ EDIT 20 Edit a specific line
117
+ COPY 10-50 TO 100 Copy line range
118
+ MOVE 10-50 TO 100 Move line range
119
+ FIND "text" Search program lines
120
+ REPLACE "old" WITH "new"
121
+ BANK 1 Switch to program slot 1
122
+ CHECKSUM MD5 hash of program listing
123
+ ```
124
+
125
+ ## Gates
126
+
127
+ ### 0-parameter, 1-qubit
128
+ | Gate | Description |
129
+ |------|-------------|
130
+ | `H 0` | Hadamard |
131
+ | `X 0` | Pauli-X (NOT) |
132
+ | `Y 0` | Pauli-Y |
133
+ | `Z 0` | Pauli-Z |
134
+ | `S 0` | Phase (pi/2) |
135
+ | `T 0` | T gate (pi/4) |
136
+ | `SDG 0` | S-dagger |
137
+ | `TDG 0` | T-dagger |
138
+ | `SX 0` | Sqrt(X) |
139
+ | `ID 0` | Identity |
140
+
141
+ ### 1-parameter, 1-qubit
142
+ | Gate | Description |
143
+ |------|-------------|
144
+ | `RX theta, 0` | Rotation around X |
145
+ | `RY theta, 0` | Rotation around Y |
146
+ | `RZ theta, 0` | Rotation around Z |
147
+ | `P theta, 0` | Phase gate |
148
+
149
+ ### 3-parameter, 1-qubit
150
+ | Gate | Description |
151
+ |------|-------------|
152
+ | `U theta, phi, lambda, 0` | General single-qubit unitary |
153
+
154
+ ### 0-parameter, 2-qubit
155
+ | Gate | Description |
156
+ |------|-------------|
157
+ | `CX 0,1` | CNOT (aliases: CNOT) |
158
+ | `CZ 0,1` | Controlled-Z |
159
+ | `CY 0,1` | Controlled-Y |
160
+ | `CH 0,1` | Controlled-H |
161
+ | `SWAP 0,1` | Swap |
162
+ | `DCX 0,1` | Double-CNOT |
163
+ | `ISWAP 0,1` | iSWAP |
164
+
165
+ ### 1-parameter, 2-qubit
166
+ | Gate | Description |
167
+ |------|-------------|
168
+ | `CRX theta, 0, 1` | Controlled-RX |
169
+ | `CRY theta, 0, 1` | Controlled-RY |
170
+ | `CRZ theta, 0, 1` | Controlled-RZ |
171
+ | `CP theta, 0, 1` | Controlled-Phase |
172
+ | `RXX theta, 0, 1` | XX interaction |
173
+ | `RYY theta, 0, 1` | YY interaction |
174
+ | `RZZ theta, 0, 1` | ZZ interaction |
175
+
176
+ ### 0-parameter, 3-qubit
177
+ | Gate | Description |
178
+ |------|-------------|
179
+ | `CCX 0,1,2` | Toffoli (aliases: TOFFOLI) |
180
+ | `CSWAP 0,1,2` | Fredkin (aliases: FREDKIN) |
181
+
182
+ ### Modifiers
183
+ ```
184
+ CTRL H 0, 1 Controlled version of any gate
185
+ INV RX 0.5, 0 Inverse/dagger of any gate
186
+ UNITARY NAME = [[..]] Define gate from unitary matrix
187
+ BARRIER Optimization barrier
188
+ RESET 0 Reset qubit to |0>
189
+ ```
190
+
191
+ ### Multi-gate lines
192
+ ```
193
+ 10 H 0 : CX 0,1 : RZ PI/4, 0 Colon-separated
194
+ ```
195
+
196
+ ## Configuration
197
+
198
+ ```
199
+ QUBITS 8 Set qubit count (1-32)
200
+ SHOTS 2048 Set measurement shots
201
+ METHOD statevector Set simulation method
202
+ METHOD GPU Set simulation device
203
+ ```
204
+
205
+ ### Simulation methods
206
+ `automatic`, `statevector`, `density_matrix`, `stabilizer`, `matrix_product_state`, `extended_stabilizer`, `unitary`, `superop`
207
+
208
+ Automatic selection: stabilizer for Clifford-only circuits, MPS for >28 qubits, statevector otherwise.
209
+
210
+ ## Variables and expressions
211
+
212
+ ```
213
+ LET angle = PI/4
214
+ LET x = sin(angle) * 2
215
+ 10 RX angle, 0 Use in gate parameters
216
+ VARS List all variables
217
+ CLEAR x Remove a variable
218
+ ```
219
+
220
+ ### Constants
221
+ `PI`, `TAU`, `E`, `SQRT2`, `True`, `False`
222
+
223
+ ### Math functions
224
+ `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `sqrt`, `log`, `exp`, `abs`, `int`, `float`, `min`, `max`, `round`, `ceil`, `floor`, `len`
225
+
226
+ ### Runtime functions
227
+ `RND(x)` random, `TIMER` elapsed seconds, `FRE(0)` free RAM bytes, `POS(0)` cursor column, `PEEK(addr)` memory read, `USR(addr)` call routine
228
+
229
+ ### String functions
230
+ `LEFT$(s,n)`, `RIGHT$(s,n)`, `MID$(s,n,len)`, `CHR$(n)`, `STR$(n)`, `HEX$(n)`, `BIN$(n)`, `ASC(c)`, `VAL(s)`, `INSTR(haystack,needle)`, `LEN(s)`
231
+
232
+ ### Operators
233
+ Arithmetic: `+`, `-`, `*`, `/`, `//`, `%`, `**`
234
+ Comparison: `==`, `!=`, `<>`, `<`, `>`, `<=`, `>=`
235
+ Logical: `AND`, `OR`, `NOT`, `XOR`
236
+ Bitwise: `AND`, `OR`, `XOR`, `NOT` (on integers)
237
+ Hex/binary literals: `&HFF`, `&B10110`
238
+
239
+ ## Arrays
240
+
241
+ ```
242
+ DIM data(10) 1D array
243
+ DIM matrix(3, 3) Multi-dimensional (flat storage)
244
+ LET data(0) = PI
245
+ REDIM data(20) Resize (preserves existing data)
246
+ ERASE data Delete array
247
+ OPTION BASE 1 Set array index base
248
+ ```
249
+
250
+ ## Control flow
251
+
252
+ ```
253
+ 10 GOTO 50
254
+ 10 GOSUB 100 / RETURN
255
+ 10 FOR I = 0 TO 3
256
+ 20 H I
257
+ 30 NEXT I
258
+ 10 FOR theta = 0 TO PI STEP 0.1
259
+ 10 WHILE n < 10 / WEND
260
+ 10 DO WHILE x > 0 / LOOP
261
+ 10 DO / LOOP UNTIL x == 0
262
+ 10 IF flag == 1 THEN H 0 ELSE X 0
263
+ 10 SELECT CASE x / CASE 1 / CASE 2 / CASE ELSE / END SELECT
264
+ 10 ON n GOTO 100, 200, 300
265
+ 10 ON n GOSUB 100, 200
266
+ 10 DATA 1, 2, 3, "hello"
267
+ 10 READ x, y, z
268
+ RESTORE
269
+ EXIT FOR / EXIT WHILE / EXIT DO
270
+ END
271
+ ```
272
+
273
+ ## Subroutines
274
+
275
+ ```
276
+ DEF BELL = H 0 : CX 0,1
277
+ DEF ROT(angle, q) = RX angle, q : RZ angle, q
278
+ 10 BELL Call subroutine
279
+ 10 BELL @2 Call with qubit offset
280
+
281
+ DEF BEGIN TELEPORT(q) Multi-line definition
282
+ H q
283
+ CX q, q+1
284
+ DEF END
285
+
286
+ SUB PREPARE(n) Structured subroutine
287
+ LOCAL i
288
+ FOR i = 0 TO n
289
+ H i
290
+ NEXT i
291
+ END SUB
292
+ CALL PREPARE(3)
293
+
294
+ FUNCTION DOUBLE(x) Function with return value
295
+ LET DOUBLE = x * 2
296
+ END FUNCTION
297
+
298
+ CIRCUIT_DEF BELL 10-20 Capture line range as macro
299
+ APPLY_CIRCUIT BELL @4 Apply with qubit offset
300
+ ```
301
+
302
+ Scope: `LOCAL`, `STATIC`, `SHARED` inside SUB/FUNCTION.
303
+
304
+ ## I/O
305
+
306
+ ```
307
+ PRINT "hello" Output text
308
+ PRINT x Output expression value
309
+ PRINT x; Suppress newline
310
+ PRINT x, Advance to next tab zone (14 columns)
311
+ PRINT SPC(5) Insert spaces
312
+ PRINT TAB(20) Tab to column
313
+ PRINT USING "##.##"; x Formatted output
314
+ PRINT STATE Dirac notation of statevector
315
+ PRINT QUBIT(0) Single-qubit Bloch info
316
+ PRINT ENTANGLEMENT(0,1) Entanglement entropy between qubits
317
+ PRINT @A LOCC register state (Dirac notation)
318
+ INPUT "name", x Prompt and read (retries on bad input)
319
+ LINE INPUT "text", s$ Read full line including spaces
320
+ GET k$ Single keypress without enter
321
+ LPRINT expr Output to stderr/log
322
+ ```
323
+
324
+ ### File handles
325
+ ```
326
+ OPEN "data.txt" FOR OUTPUT AS #1
327
+ PRINT #1, "hello"
328
+ CLOSE #1
329
+ OPEN "data.txt" FOR INPUT AS #1
330
+ INPUT #1, line$
331
+ EOF(1) Returns 1 at end of file
332
+ CLOSE #1
333
+ OPEN "db.txt" FOR RANDOM AS #2
334
+ OPEN "log.txt" FOR APPEND AS #3
335
+ ```
336
+
337
+ ### Export
338
+ ```
339
+ EXPORT Print OpenQASM to screen
340
+ EXPORT file.qasm Save OpenQASM to file
341
+ CSV Print results as CSV
342
+ CSV file.csv Save results to CSV
343
+ ```
344
+
345
+ ## Display
346
+
347
+ ```
348
+ STATE Full statevector (amplitudes + probabilities)
349
+ HIST Measurement histogram
350
+ PROBS Probability distribution
351
+ BLOCH 0 ASCII Bloch sphere for qubit 0
352
+ BLOCH All qubits (up to 8)
353
+ CIRCUIT Circuit diagram (text)
354
+ DECOMPOSE Gate count breakdown
355
+ DENSITY Density matrix
356
+ ```
357
+
358
+ ### Screen modes
359
+ ```
360
+ SCREEN 0 Text (default)
361
+ SCREEN 1 Histogram
362
+ SCREEN 2 Statevector
363
+ SCREEN 3 Bloch spheres
364
+ SCREEN 4 Density matrix
365
+ SCREEN 5 Circuit diagram
366
+ ```
367
+
368
+ After RUN, the selected screen mode auto-displays.
369
+
370
+ ```
371
+ COLOR green Set foreground color
372
+ COLOR cyan, black Set foreground and background
373
+ CLS Clear screen
374
+ LOCATE 5, 10 Position cursor
375
+ PLAY Terminal bell
376
+ PROMPT "> " Change REPL prompt
377
+ ```
378
+
379
+ ## Analysis
380
+
381
+ ```
382
+ EXPECT Z 0 Expectation value <Z> on qubit 0
383
+ EXPECT ZZ 0 1 Two-qubit observable
384
+ ENTROPY 0 Entanglement entropy (qubit 0 vs rest)
385
+ ENTROPY 0 1 Entropy of partition {0,1} vs rest
386
+ RAM Memory budget and parallelism estimates
387
+ BENCH Benchmark simulation at various qubit counts
388
+ SWEEP var 0 PI 10 Sweep a parameter, show P(top state) vs variable
389
+ SAMPLE 500 Sample via SamplerV2 primitive
390
+ ESTIMATE ZZ 0 1 Observable estimation via EstimatorV2
391
+ ```
392
+
393
+ ### Inline circuit instructions
394
+ ```
395
+ 10 SAVE_EXPECT ZZ 0,1 -> zz_val Expectation value (result in variable after RUN)
396
+ 10 SAVE_PROBS 0,1 -> probs Probability snapshot (result in array after RUN)
397
+ 10 SAVE_AMPS 0,3 -> amps Specific amplitudes by index (array after RUN)
398
+ 10 SET_STATE |+> Inject named state mid-circuit
399
+ 10 SET_STATE |BELL> Bell state
400
+ 10 SET_STATE |GHZ> GHZ state
401
+ 10 SET_STATE [0.707, 0, 0, 0.707] Explicit amplitudes (auto-normalized)
402
+ ```
403
+
404
+ ### Statistics
405
+ ```
406
+ STATS 100 Run 100 trials, collect statistics
407
+ STATS SHOW Show mean/stddev/min/max per state
408
+ STATS CLEAR Reset accumulator
409
+ ```
410
+
411
+ ## Noise models
412
+
413
+ ```
414
+ NOISE depolarizing 0.01 Depolarizing channel (all gates)
415
+ NOISE amplitude_damping 0.01 T1-like decay
416
+ NOISE phase_flip 0.01 T2-like dephasing
417
+ NOISE thermal 50e-6 70e-6 1e-6 T1/T2 decoherence (microseconds)
418
+ NOISE readout 0.05 0.1 Measurement bit-flip (p(0->1), p(1->0))
419
+ NOISE combined 0.01 0.02 Amplitude + phase damping
420
+ NOISE pauli 0.01 0.01 0.01 Pauli channel (px, py, pz)
421
+ NOISE reset 0.01 0.01 Spontaneous reset error
422
+ NOISE OFF Disable noise
423
+ ```
424
+
425
+ ### Per-qubit noise (memory-mapped)
426
+ ```
427
+ POKE $D100, 1 Qubit 0 noise type (0=none, 1=depolarizing, 2=amp_damp, 3=phase)
428
+ POKE $D101, 0.05 Qubit 0 noise parameter
429
+ POKE $D102, 1 Qubit 1 noise type
430
+ POKE $D103, 0.02 Qubit 1 noise parameter
431
+ ```
432
+
433
+ ## LOCC mode
434
+
435
+ Dual-register distributed quantum simulation with classical communication.
436
+
437
+ ```
438
+ LOCC 4 4 SPLIT mode: two independent 4-qubit registers (A, B)
439
+ LOCC JOINT 3 3 JOINT mode: shared entanglement possible
440
+ LOCC 4 4 4 3-party (A, B, C)
441
+ LOCC OFF Return to normal mode
442
+ LOCC STATUS Show register info
443
+ ```
444
+
445
+ ### LOCC commands
446
+ ```
447
+ @A H 0 Gate on register A
448
+ @B CX 0,1 Gate on register B
449
+ @A H 0 : CX 0,1 Colon inheritance within register
450
+ SEND A 0 -> m0 Mid-circuit measure A[0], store classical bit
451
+ IF m0 THEN @B X 0 Conditional gate based on classical bit
452
+ SHARE A 2, B 0 Create Bell pair (JOINT mode only)
453
+ MEAS 0 -> result Mid-circuit measurement within register
454
+ RESET 0 Reset qubit within register
455
+ MEASURE_X 0 X-basis measurement
456
+ MEASURE_Y 0 Y-basis measurement
457
+ SYNDROME ZZ 0 1 -> s0 Stabilizer measurement
458
+ STATE A Inspect register A
459
+ BLOCH A 0 Bloch sphere for register A, qubit 0
460
+ LOCCINFO Protocol metrics
461
+ ```
462
+
463
+ SPLIT: max capacity (31+31+...), no cross-register entanglement. Use SEND/IF for classical coordination.
464
+
465
+ JOINT: shared entanglement via SHARE. Limited to ~32 total qubits.
466
+
467
+ ### Network LOCC
468
+ ```
469
+ CONNECT "host:port" AS C Attach remote register (local simulation stand-in)
470
+ DISCONNECT C Detach
471
+ ```
472
+
473
+ ### LOCC optimization
474
+ Programs with SEND execute the deterministic prefix (before first SEND) once, snapshot the statevector, then re-execute only the suffix per shot. Complexity: O(prefix + shots * suffix) instead of O(shots * total).
475
+
476
+ ## Basis measurement and error correction
477
+
478
+ ```
479
+ MEASURE_X 0 Measure in X basis (stores in mx_0)
480
+ MEASURE_Y 0 Measure in Y basis (stores in my_0)
481
+ MEASURE_Z 0 Measure in Z basis (stores in mz_0)
482
+ SYNDROME ZZ 0 1 -> s0 Non-destructive stabilizer measurement
483
+ ```
484
+
485
+ SYNDROME uses an ancilla (highest qubit index). Pauli string length must match qubit count. I, X, Y, Z supported.
486
+
487
+ ## Memory map
488
+
489
+ ```
490
+ $0000-$003F Zero Page (64 slots, SYS parameter passing)
491
+ $0100-$01FF Qubit State (8 addresses per qubit)
492
+ $D000-$D00B QPU Config (read/write)
493
+ $D010-$D014 QPU Status (read-only)
494
+ $D100-$D1FF Per-Qubit Noise (2 addresses per qubit)
495
+ $E000-$E0B0 SYS Routine Table
496
+ $F000-$FFFF User SYS Routines
497
+ ```
498
+
499
+ ### Qubit state ($0100 + qubit * 8)
500
+ | Offset | Field |
501
+ |--------|-------|
502
+ | +0 | P(\|1>) probability |
503
+ | +1 | Bloch X |
504
+ | +2 | Bloch Y |
505
+ | +3 | Bloch Z |
506
+ | +4 | Re(alpha) |
507
+ | +5 | Im(alpha) |
508
+ | +6 | Re(beta) |
509
+ | +7 | Im(beta) |
510
+
511
+ ### QPU config ($D000-$D00B)
512
+ | Address | Name | Values |
513
+ |---------|------|--------|
514
+ | $D000 | num_qubits | 1-32 |
515
+ | $D001 | shots | 1+ |
516
+ | $D002 | sim_method | 0=auto, 1=statevector, 2=stabilizer, 3=MPS, 4=density |
517
+ | $D003 | sim_device | 0=CPU, 1=GPU |
518
+ | $D004 | noise_type | read-only |
519
+ | $D005 | noise_param | read-only |
520
+ | $D006 | max_iterations | loop limit |
521
+ | $D007 | screen_mode | 0-5 |
522
+ | $D008 | fusion_enable | 0/1 |
523
+ | $D009 | mps_truncation | float threshold |
524
+ | $D00A | sv_parallel_threshold | int |
525
+ | $D00B | es_approx_error | float |
526
+
527
+ ### QPU status ($D010-$D014, read-only)
528
+ | Address | Name |
529
+ |---------|------|
530
+ | $D010 | gate_count |
531
+ | $D011 | circuit_depth |
532
+ | $D012 | run_time_ms |
533
+ | $D013 | total_probability |
534
+ | $D014 | entanglement_entropy |
535
+
536
+ ### Per-qubit noise ($D100 + qubit * 2)
537
+ | Offset | Field |
538
+ |--------|-------|
539
+ | +0 | noise_type (0=none, 1=depolarizing, 2=amp_damp, 3=phase) |
540
+ | +1 | noise_param (float) |
541
+
542
+ ### Bloch sphere POKE
543
+ POKE to qubit state addresses ($0100+q*8) prepares the qubit:
544
+ - Field 0 (P(|1>)): sets probability via RY rotation
545
+ - Fields 1-3 (Bloch x,y,z): stores target coordinates
546
+
547
+ ### SYS routines ($E000-$E0B0)
548
+ | Address | Routine |
549
+ |---------|---------|
550
+ | $E000 | BELL |
551
+ | $E010 | GHZ |
552
+ | $E020 | QFT |
553
+ | $E030 | GROVER |
554
+ | $E040 | TELEPORT |
555
+ | $E050 | DEUTSCH |
556
+ | $E060 | BERNSTEIN |
557
+ | $E070 | SUPERDENSE |
558
+ | $E080 | RANDOM |
559
+ | $E090 | STRESS |
560
+ | $E0A0 | LOCC-TELEPORT |
561
+ | $E0B0 | LOCC-COORD |
562
+
563
+ ### SYS commands
564
+ ```
565
+ SYS $E000 Execute built-in routine (BELL)
566
+ SYS INSTALL $F000, SUB Install user routine at address
567
+ CATALOG List all SYS routines
568
+ DUMP $0000 $003F Hex dump memory range
569
+ MAP Full memory map with values
570
+ MONITOR Interactive hex monitor (type address to PEEK, addr=val to POKE)
571
+ WAIT $D013, 1 Block until (PEEK(addr) AND mask) matches
572
+ ```
573
+
574
+ ## Demos
575
+
576
+ ```
577
+ DEMO BELL Bell state (2 qubits)
578
+ DEMO GHZ GHZ entanglement (up to 8 qubits)
579
+ DEMO TELEPORT Quantum teleportation circuit
580
+ DEMO GROVER Grover's search (3 qubits, target |101>)
581
+ DEMO QFT Quantum Fourier transform (4 qubits)
582
+ DEMO DEUTSCH Deutsch-Jozsa algorithm
583
+ DEMO BERNSTEIN Bernstein-Vazirani (secret=1011)
584
+ DEMO SUPERDENSE Superdense coding (message=11)
585
+ DEMO RANDOM Quantum random number generator
586
+ DEMO STRESS 20-qubit stress test
587
+ DEMO LOCC-TELEPORT Full teleportation with classical correction (JOINT)
588
+ DEMO LOCC-COORD Classical coordination (SPLIT)
589
+ DEMO LIST List all demos
590
+ ```
591
+
592
+ ## Debugging
593
+
594
+ ```
595
+ STEP Step through program with state display
596
+ TRON Trace on (print each line number during execution)
597
+ TROFF Trace off
598
+ STOP Break at this line during execution
599
+ CONT Continue after STOP
600
+ BREAK 20 Set breakpoint at line 20
601
+ BREAK List breakpoints
602
+ BREAK CLEAR Clear all breakpoints
603
+ WATCH x Monitor variable during STOP/STEP
604
+ WATCH CLEAR Clear all watches
605
+ PROFILE ON Enable per-line profiling
606
+ PROFILE OFF Disable
607
+ PROFILE SHOW Show time/calls/gates per line
608
+ ASSERT x > 0 Halt if condition fails
609
+ ```
610
+
611
+ ### Time-travel debugging
612
+ ```
613
+ REWIND 3 Go back 3 statevector checkpoints
614
+ FORWARD 1 Go forward 1 checkpoint
615
+ HISTORY Show all checkpoints with current position
616
+ ```
617
+
618
+ Checkpoints are saved during STEP mode for circuits up to 16 qubits. Each checkpoint stores the full statevector after that gate application.
619
+
620
+ ## Error handling
621
+
622
+ ```
623
+ ON ERROR GOTO 1000 Trap runtime errors
624
+ RESUME Retry the failed line
625
+ RESUME NEXT Skip to next line
626
+ ERROR 42 Raise user-defined error
627
+ ```
628
+
629
+ Variables `ERR` (error code) and `ERL` (error line) are set when an error is trapped.
630
+
631
+ ## Types
632
+
633
+ ```
634
+ TYPE Point
635
+ x AS FLOAT
636
+ y AS FLOAT
637
+ END TYPE
638
+ ```
639
+
640
+ ## Named types
641
+
642
+ Defines a record structure. Fields: `INTEGER`, `FLOAT`, `STRING`, `QUBIT`.
643
+
644
+ ## Quantum DATA
645
+
646
+ ```
647
+ 10 DATA |+>, |0>, |GHZ3>, 3.14, "hello"
648
+ 20 READ state$, state2$, state3$, angle, name$
649
+ ```
650
+
651
+ Quantum state names (`|+>`, `|0>`, `|1>`, `|->`, `|BELL>`, `|GHZ>`, `|GHZ3>`, `|GHZ4>`, `|W>`, `|W3>`) are recognized in DATA statements and stored as `QSTATE:` tokens.
652
+
653
+ ## Performance
654
+
655
+ ### Auto-scaling
656
+ QBASIC detects available RAM, estimates per-instance memory, and reports maximum qubit count and parallelism budget at startup and via the `RAM` command.
657
+
658
+ ### Simulation method selection
659
+ - **automatic**: stabilizer for Clifford-only circuits, MPS for >28 qubits, statevector otherwise
660
+ - **stabilizer**: polynomial-time for Clifford circuits (H, S, CX, SWAP, etc.)
661
+ - **matrix_product_state**: scales to 50+ qubits for low-entanglement circuits
662
+ - **extended_stabilizer**: approximate simulation for near-Clifford circuits
663
+ - **statevector**: exact, limited by RAM (~28 qubits on 16GB)
664
+ - **density_matrix**: includes mixed states, ~14 qubits on 16GB
665
+ - **unitary**: returns the full unitary matrix of the circuit
666
+ - **superop**: returns the superoperator (quantum channel)
667
+
668
+ ### Tuning via memory map
669
+ ```
670
+ POKE $D008, 1 Enable gate fusion (default on)
671
+ POKE $D008, 0 Disable gate fusion
672
+ POKE $D009, 1e-12 MPS truncation threshold (tighter = more accurate)
673
+ POKE $D00A, 16 Statevector parallel threshold
674
+ POKE $D00B, 0.01 Extended stabilizer approximation error
675
+ ```
676
+
677
+ ### Circuit caching
678
+ Transpiled circuits are cached between RUN calls when the program and configuration have not changed. Cache invalidates on any program edit, qubit count change, method change, or tuning parameter change.
679
+
680
+ ### LOCC optimization
681
+ Programs with SEND use prefix/suffix splitting: the deterministic prefix (before first SEND) executes once, the statevector is snapshotted, and only the suffix (from SEND onward) re-executes per shot. Falls back to full re-execution if the prefix contains GOTO/GOSUB.
682
+
683
+ ## JSON output
684
+
685
+ ```
686
+ python qbasic.py --json examples/bell.qb
687
+ ```
688
+
689
+ ```json
690
+ {
691
+ "counts": {"00": 518, "11": 506},
692
+ "num_qubits": 2,
693
+ "shots": 1024
694
+ }
695
+ ```
696
+
697
+ ## Architecture
698
+
699
+ ```
700
+ qbasic.py CLI entry point
701
+ qbasic_core/
702
+ engine_state.py Engine: standalone state container
703
+ terminal.py QBasicTerminal: REPL + command dispatch
704
+ engine.py Constants, gate tables, numpy simulation, LOCCEngine
705
+ parser.py 60+ typed Stmt objects from raw strings
706
+ statements.py Stmt type definitions
707
+ exec_context.py ExecContext: unified execution state
708
+ scope.py Scope: layered variable system
709
+ backend.py QiskitBackend / LOCCRegBackend abstraction
710
+ errors.py Structured error hierarchy
711
+ io_protocol.py IOPort protocol for I/O decoupling
712
+ expression.py AST-based safe expression evaluator (no eval())
713
+ control_flow.py FOR/NEXT, WHILE/WEND, IF/THEN dispatch
714
+ display.py Histograms, statevector, Bloch sphere rendering
715
+ locc.py LOCC commands, execution, display
716
+ analysis.py EXPECT, ENTROPY, DENSITY, BENCH, RAM
717
+ sweep.py Parameter sweep with plotille charts
718
+ memory.py PEEK/POKE/SYS/DUMP/MAP/MONITOR
719
+ strings.py String functions
720
+ screen.py SCREEN/COLOR/CLS/LOCATE
721
+ classic.py DATA/READ, SELECT CASE, DO/LOOP, SWAP, DEF FN
722
+ subs.py SUB/FUNCTION with LOCAL/STATIC/SHARED
723
+ debug.py ON ERROR, TRON/TROFF, breakpoints, time-travel
724
+ program_mgmt.py AUTO/EDIT/COPY/MOVE/FIND/REPLACE/BANK
725
+ profiler.py PROFILE, gate/depth tracking, STATS
726
+ file_io.py SAVE/LOAD/INCLUDE/IMPORT/EXPORT/CSV/OPEN/CLOSE
727
+ demos.py Built-in demo circuits
728
+ protocol.py TerminalProtocol (mixin contract)
729
+ mock_backend.py MockAerSimulator for fast testing
730
+ ```
731
+
732
+ `Engine` holds all program state. `QBasicTerminal` inherits `Engine` + 16 mixins. `Engine` can be used independently for headless/agent execution.
733
+
734
+ ## License
735
+
736
+ MIT