Saving and Loading Objects to Disk

import os
import trueq as tq

Make SRB CircuitCollection on qubit 1, and populate it with results from a simulator.

circuits = tq.make_srb(1, [4, 32, 64])
tq.Simulator().add_overrotation(0.05).run(circuits, n_shots=1024)

Save the circuit collection with all metadata, cycles, and results to disk:

# use a temporary folder so that this example doesn't make a mess
with tq.utils.temp_folder():
    # the extension ".tq" is arbitrary but encouraged
    circuits.save("my_circuits.tq")
    file_size = os.path.getsize("my_circuits.tq")
    print(f"Saved file is {file_size} bytes.")

    # load the circuits back to disk
    loaded_circuits = tq.load("my_circuits.tq")

Out:

Saved file is 57581 bytes.

We have effectively made a deep copy of the original collection:

print(loaded_circuits is not circuits and loaded_circuits == circuits)
print(loaded_circuits[0] is not circuits[0] and loaded_circuits[0] == circuits[0])

Out:

True
True

In particular, all of the results and circuit contents have been preserved:

loaded_circuits.plot.raw()
SRB on [1]

Reducing file size

The filesize can be reduced by choosing to omit all circuit cycles from the saved object, or possibly by saving the fit object instead of the circuits; see the next subsection. This permanently erases this information if the object is also deleted from the active python session. However, this may be worth it if lots of data is routinely being saved to disk since analysis routines depend only on circuit results and metadata contained in circuit keys, and not on cycles or gates in the circuit.

with tq.utils.temp_folder():
    # the extension ".tq" is arbitrary but encouraged
    circuits.save("my_circuits2.tq", include_cycles=False)

    size_ratio = file_size / os.path.getsize("my_circuits2.tq")
    print(f"This file is {size_ratio:.2f}x smaller.")

    # load the circuits back to disk
    loaded_circuits2 = tq.load("my_circuits2.tq")

loaded_circuits2.plot.raw()
SRB on [1]

Out:

This file is 13.13x smaller.

Saving other objects

Many other True-Q™ objects can be stored to disk. Notably, we can store fit results, which may often be an even better method of file size reduction.

with tq.utils.temp_folder():
    tq.utils.save(circuits.fit(), "my_fit.fit")

    size_ratio = file_size / os.path.getsize("my_fit.fit")
    print(f"This file is {size_ratio:.2f}x smaller.")

    loaded_fit = tq.load("my_fit.fit")

loaded_fit
loaded_fit.plot.raw()
SRB on [1]

Out:

This file is 74.68x smaller.

Total running time of the script: ( 0 minutes 0.469 seconds)

Gallery generated by Sphinx-Gallery