Using Qamuy programatically

Qamuy Client SDK allows you to use Qamuy from a Python program. It is useful for the following applications:

  • Creating many variations of input data and running those calculations simultaneously on the cloud

  • Aggregating and analyzing the result data obtained by the calculation with Python

  • Using Jupyter Notebook to perform interactive calculations and analysis

Check Qamuy Client SDK get_version

You can check the version with get_version() in qamuy.utils package.

import qamuy.utils

qamuy.utils.get_version()

Creating input data

There are several ways to create input data with the Python SDK, and you can use them in different ways depending on your needs and preferences.

Assigning values to each attribute of an input data object

You can create input data in a sequential fashion by first creating an “empty” object and then assigning values to its attributes.

import qamuy.chemistry as qy

input = qy.QamuyChemistryInput()
# Set the molecule to be calculated
molecule = input.target_molecule
molecule.geometry = qy.molecule_geometry(["H", "H"], [[0.0, 0.0, -0.35], [0.0, 0.0, 0.35]])
molecule.basis = "6-31g"
molecule.multiplicity = 1
molecule.num_excited_states = 1
molecule.cas = qy.cas(2, 2)
# Or you can specify a periodic system
ps = input.target_periodic_system
atoms = ["H", "H"]
coords = [
    [0.0, 0.0, 0.0],
    [1.42, 0.0, 0.0]
]
trans_vec = [[2.13, -1.23, 0.0], [2.13, 1.23, 0.0], [0.0, 0.0, 5.0]]
kpt_grid_shape = [2, 1, 1]
ps.geometry = qy.periodic_system_geometry(atoms, coords, trans_vec, kpt_grid_shape)
ps.basis = "sto3g"
ps.num_excited_states = 0
ps.cas = qy.cas_periodic_system(2, 2)
# Set the algorithm
input.solver.type = "VQE"
# ...
# Set the properties to be calculated.
properties = input.output_chemical_properties
properties.append(qy.output_chemical_property(target="dipole_moment", states=[0, 1]))
properties.append(
    qy.output_chemical_property(
        target="gradient", states=[0, 1], type="HAMILTONIAN_NUMERICAL", dx=0.1
    )
)

The QamuyChemistryInput object represents the entire input data.

While many attributes can be set by assigning simple Python values, several functions are provided to simplify the setting of some attributes.

  • molecule_geometry() allows you to create a molecular structure specification.

    qamuy.chemistry.molecule_geometry(atoms, coordinates, geometry_format='CARTESIAN')

    Create an object representing geometry of a molecule.

    Parameters:
    • atoms – A list of nuclei that make up the molecule.

    • coordinates – A list of coordinates of the nuclei specifying a molecular structure, or a list of such lists specifying multiple molecular structure.

    • geometry_format – A notation in which the coordinates are described. Possible values are CARTESIAN (default) and Z_MATRIX.

    Returns:

    A Molecule.Geometry object, which can be substituted in target_molecule.geometry attribute.

  • molecule_geometry_from_xyz() is available to create a molecular structure specification from a string of “xyz format”, a format commonly used in the field of computational chemistry.

    qamuy.chemistry.molecule_geometry_from_xyz(xyz)

    Create an object representing geometry of a molecule from a string of xyz format. See https://en.wikipedia.org/wiki/XYZ_file_format

    Parameters:

    xyz – A string of xyz format.

    Returns:

    A Molecule.Geometry object, which can be substituted in target_molecule.geometry attribute.

  • You can create a CAS (complete active space) with cas().

    qamuy.chemistry.cas(active_ele=None, active_orb=None, cas_list=None)

    Create an object representing a complete active space.

    Parameters:
    • active_ele (int) – Number of electrons in the active space.

    • active_orb (int) – Number of orbitals in the active space.

    • cas_list (list<int>) – List of orbital indices in the active space.

    Returns:

    A Cas object.

For periodic systems,

  • periodic_system_geometry() helps you to create a periodic system specification.

    qamuy.chemistry.periodic_system_geometry(atoms, coordinates, trans_vector, kpt_grid_shape)

    Create an object representing geometry of a periodic system.

    Parameters:
    • atoms – A list of nuclei that make up a cell of a periodic system.

    • coordinates – A list of coordinates of the nuclei specifying a priodic system, or a list of such lists specifying multiple structures.

    • trans_vector – Translation vectors that characterize a periodic boundary condition.

    • kpt_grid_shape – The numbers of k points for each axis of the reciprocal space.

    Returns:

    A PeriodicSystem.Geometry object, which can be substituted in target_periodic_system.geometry attribute.

  • cas_periodic_system() is available to specify a CAS (complete active space).

    qamuy.chemistry.cas_periodic_system(active_ele=None, active_orb=None)

    Create an object representing a complete active space.

    Parameters:
    • active_ele (int) – Number of electrons in the active space for a cell.

    • active_orb (int) – Number of orbitals in the active space for a k-point.

    Returns:

    A Cas object.

  • output_chemical_property() allows you to create a specification of the property to be evaluated.

    qamuy.chemistry.output_chemical_property(target, **kwargs)

    Create an object representing parameters of a chemical property to be calculated. See a description of each target property in the reference page of input data for detail.

    Parameters:
    • target (str) – An identifier of the target property. (e.g. “energy”, “dipole_moment”, etc.)

    • kwargs – Keyword arguments necessary for each target property.

    Returns:

    A TargetChemicalProperty object, which can be put into output_chemical_properties attribute.

  • spin_state() allows you to create a specification of the spin state of each reference state.

    qamuy.chemistry.spin_state(state, multiplicity, sz)

    Create an object representing a spin state for a reference state.

    Parameters:
    • state (int) – The index of a reference state.

    • multiplicity (int) – The multiplicity of a reference state.

    • sz (float) – The value of z component of the total spin of a reference state.

    Returns:

    A SpinState object.

As some of the attributes are list-based, you need to create an object when you add an item to them.

  • output_chemical_properties: Create an object with qamuy.chemistry.output_chemical_property():

    input.output_chemical_properties.append(
      qy.output_chemical_property(
          target="gradient", states=[0, 1], type="HAMILTONIAN_NUMERICAL", dx=0.1
      )
    )
    
  • post_hf_methods: Create an object with qamuy.chemistry.PostHFMethod

    input.post_hf_methods.append(
      qy.PostHFMethod(type="CASCI", excited_state_type="STATE_SPECIFIC")
    )
    
  • spin_state_list: Create an object with qamuy.chemistry.spin_state():

    input.ansatz.spin_state_list.append(
        qy.spin_state(0, 1, 0.0)
    )
    

Note that when you assign a Python object to an attribute, the object being assigned is copied. Even if you change internal data of the assigned object after it is assigned, the change will not be reflected in the assignment target. In the following example, the geometry of input.target_molecule will not be set.

molecule = qy.Molecule()
input.target_molecule = molecule # ← molecule is copied at this point
molecule.geometry = qy.molecule_geometry(["H", "H"], [[0.0, 0.0, -0.35], [0.0, 0.0, 0.35]])
print(input.target_molecule) # => geometry is not set

Create the entire input data at once

For each piece of input data, a corresponding Python class is provided. Constructors of these classes can be used to create the entire input data at once.

import qamuy.chemistry as qy

input = qy.QamuyChemistryInput(
    # The molecule to be calculated
    target_molecule=qy.Molecule(
        geometry=qy.molecule_geometry(
            ["H", "H"], [[0.0, 0.0, -0.35], [0.0, 0.0, 0.35]]
        ),
        basis="6-31g",
        multiplicity=1,
        num_excited_states=1,
        cas=qy.cas(2, 2)
    ),
    # The algorithm
    solver=qy.Solver(type="VQE"),
    # ...
    # The properties to calculate
    output_chemical_properties=[
        qy.output_chemical_property(target="dipole_moment", states=[0, 1]),
        qy.output_chemical_property(
            target="gradient", states=[0, 2], type="HAMILTONIAN_NUMERICAL", dx=0.1
        )
    ]
)

Molecule, Solver, and so on are the classes corresponding to each configuration item. These constructors allow you to specify the value of each attribute with named arguments.

It is also possible to pass a dict argument to the class constructor.

input = qy.QamuyChemistryInput({
    # The molecule to be calculated
    "target_molecule": qy.Molecule({
        "geometry": qy.molecule_geometry(
            ["H", "H"], [[0.0, 0.0, -0.35], [0.0, 0.0, 0.35]]
        ),
        "basis": "6-31g",
        "multiplicity": 1,
        "cas": qy.cas(2, 2)
    })
})

Copy and modify already existing input data

You can copy previously created input data and use it with some changes. This is useful for creating multiple sets of input data with only a few changes.

from copy import deepcopy

# Create input data using hardware efficient ansatz
input1 = qy.QamuyChemistryInput()
input1.ansatz.type = "HARDWARE_EFFICIENT"
# Copy the input data you have created
input2 = deepcopy(input1)
# Change the copied input data to use UCCD ansatz
input2.ansatz.type = "UCCD"

Load and modify already existing input data saved as a file

You can load an already existing input data file and then modify the copy of it. This is useful for creating multiple sets of input data with only a few changes. File formats may be either JSON or YAML.

from qamuy.utils.file_io import load_input

# Load an input data file
input = load_input("input_H2_JW_VQE_HWE_BFGS.yaml")

# Change the copied input data to use UCCD ansatz
input.ansatz.type = "UCCD"

Load and copy already existing output data saved as a file

You can load an already existing output data file and then make use of the part of the copy of it. File formats may be either JSON or YAML.

from qamuy.utils.file_io import load_output

# Load an output data file
output = load_output("output_H2_JW_VQE_HWE_BFGS.yaml")
result = output.molecule_result
# Copy the optimal parameter list of optimization result
opt_params = result.quantum_device_result.vqe_log.opt_params

Save input data as file

You can save your input data as file. File formats may be either JSON or YAML.

from qamuy.utils.file_io import save

input = qy.QamuyChemistryInput()
...
# Save as file
save(input, filename="my_input_file.yaml")

Run a calculation job

In order to run a calculation job on the cloud, you use the qamuy.client.Client class. You create an instance with a constructor of the Client class and use its methods to run the job and get the results.

from qamuy.client import Client

client = Client(email_address="EMAIL_ADDRESS", password="PASSWORD")
job = client.submit(input)
results = client.wait_and_get_job_results([job])
  • You can set your email address and password into arguments email_address and password of Client() to login in your program code. If you have already logined using qamuy command, just using Client() without any arguments is enough.

  • Use submit() method with the input data (input) created in the previous section as an argument to start calculation on the cloud. A Job object representing the calculation job is returned. At this point, the calculation is not yet complete. If there is a problem with the input data (e.g., a required parameter is not specified), an exception may be raised at this point.

  • The wait_and_get_job_results() method waits for the jobs to complete and retrieves the results. It is possible to pass multiple jobs as a list to get results at once. Even when there is only one job, you need to call it with a list of jobs as shown in the sample code. A list of Result object corresponding to each input data is returned.

class qamuy.client.Client

API client for Qamuy.

Client.submit(input)

Submit a calculation job with the input data passed as an argument. May raise an exception if validation of the input or an API request fails. This method does not wait for completion of the submitted job.

Parameters:

input – An input data for calculation.

Returns:

A Job object containing information of the submitted job.

Client.wait_and_get_job_results(jobs, print_progress=True)

Given multiple jobs, wait for completion of jobs and get results of them.

Parameters:
  • jobs – An iterable of Job objects.

  • print_progress (bool) – Print progress to stderr.

Returns:

A list of Result objects containing status, output data and error of each job.

The Result object, which represents the result of a job, has the following attributes:

status

Represents status of a job. Its type is qamuy.client.ResultStatus (enum) and its value is either one of SUCCESS or FAILURE.

output

An object containing the output data of the calculation. If the calculation exits in error, it is set to None. See the next section on how to get information from this object.

error

A dict with information about the error if the calculation terminates with an error. If the calculation succeeds, it is set to None.

result = results[0]
result.status # => <ResultStatus.SUCCESS: 0>
result.output # => {'input': { ... }, 'molecule_result': { ... }, ... }
result.error # => None

Here’s an example of running calculations with multiple inputs simultaneously and then extracting the output.

# Prepare multiple input data
inputs = [input1, input2, ...]
# Create a client
client = Client()
# Start calculation with the input data one by one and make a list of calculation jobs
jobs = [client.submit(input) for input in inputs]
# Wait for all the calculation jobs to complete and get the results
results = client.wait_and_get_job_results(jobs)
# Display an error if there is a calculation that has ended in error
for i, result in enumerate(results):
    if result.status == qamuy.client.ResultStatus.FAILURE:
        print(f"Job {i} has failed: {result.error}")
# Extract output data from Result data
outputs = [result.output for result in results]

Save calculation job information

You can save a Job object, returned when starting a calculation job, as a file. You can get the calculation result with the Job object restored from the file even after the program is terminated.

Saving a job:

from qamuy.utils.file_io import save_job

job = client.submit(input)
# Save the Job object in job.json file
save_job(job, filename="job.json")

Restoring a job:

from qamuy.utils.file_io import load_job

# Restore the Job object from job.json file
job = load_job(filename="job.json")
# Retrieve the calculation result with the restored Job object
results = client.wait_and_get_job_results([job])

Terminate a calculation job

You can terminate a calculation job with terminate_job() method of Client class.

job = client.submit(input)
client.terminate_job(job)
Client.terminate_job(job)

Terminate a calculation job.

Parameters:

job – A job object to be terminated.

Returns:

A job object for the specified job with its status updated.

Save output data as file

You can save your output data (set in the output attribute of the Result class in the previous section) as file. File formats may be either JSON or YAML.

from qamuy.utils.file_io import save

output = results[0].output
# Save as file
save(output, filename="my_output_file.yaml")

Load already existing output data saved as a file

You can load an already existing output data file and analyze it. File formats may be either JSON or YAML.

from qamuy.utils.file_io import load_output

# Load an output data file
output = load_output("output_H2_JW_VQE_HWE_BFGS.yaml")

Extracting information from the output data

The output data contains the same structure as described in output data, and you can retrieve the information using attributes just like for the usual Python classes.

output = result.output
# Extract the result for the first molecular structure
m_result = output.molecule_result
# Extract the result of a quantum computation
q_result = m_result.quantum_device_result
# Retrieving VQE log information
vqe_log = q_result.vqe_log
# Extract the optimized parameters of VQE
list(vqe_log.opt_params) # => [0.0, ...]
# Get the quantum circuit information needed to perform the quantum computation
vqe_log.quantum_resources.circuit # => {'num_qubit': 8, 'num_parameter': 32, 'num_gate': 39, 'num_1qubit_gate': 32, 'num_2qubit_gate': 7}
# Retrieve the object that contains the evaluated properties
evaluated_properties = q_result.evaluated_properties
# Retrieve the object that contains the geometry optimization result
geo_result = output.geometry_optimization_result

While much of the information can be retrieved by simply accessing the attributes, there are functions that make it easier to retrieve some of the information.

Retrieve the evaluated properties

get_evaluated_property() allows you to retrieve the evaluated properties. If you are evaluating for multiple parameters (electronic states, state pairs, etc.), it returns an object containing all of them.

# Specify the name of the property (see a document for output data)
qy.get_evaluated_property(q_result, "energy")
# => {'values': [{'value': -1.1261231613839167, 'state': 0, 'sample_std': 0.0}, {'state': 1, 'value': -0.6254196782618017, 'sample_std': 0.0}], 'metadata': {'elapsed_time': 0.005356331821531057}}
qamuy.chemistry.get_evaluated_property(result, property_name)

Extract evaluated property values from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

Returns:

An object containing values for the specified property, typically contains a list of property values and metadata.

get_evaluated_properties() returns the list of evaluated properties. It is useful when you specified multiple methods for one property.

# Specify the name of the property (see a document for output data)
qy.get_evaluated_properties(q_result, "gradient")
# => [{'values': [{'value': [0.0, 0.0, 0.036077760736360556, 0.0, 0.0, -0.03607776073639941], 'state': 0}, {'state': 1, 'value': [0.0, 0.0, 0.23747779376661535, 0.0, 0.0, -0.237477793766483]}], 'metadata': {'elapsed_time': 0.9695170419999997}, 'type': 'HAMILTONIAN_NUMERICAL'}, {'values': [{'value': [0.0, 0.0, 0.03607675773015902, 0.0, 0.0, -0.036076757730159156], 'state': 0}, {'state': 1, 'value': [0.0, 0.0, 0.23747658698911753, 0.0, 0.0, -0.23747658698911753]}], 'metadata': {'elapsed_time': 0.06478304199999929}, 'type': 'HAMILTONIAN_ANALYTICAL'}]
qamuy.chemistry.get_evaluated_properties(result, property_name)

Extract evaluated property values from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

Returns:

A list of objects containing values for the specified property, typically contains a list of property values and metadata.

You can get properties evaluated with an electronic state specified (energy, dipole_moment, etc.) with get_evaluated_property_for_state(). You can use get_evaluated_property_for_state_pair() to get properties evaluated in terms of an electronic state pair (trasition_dipole_moment, etc.).

Similar to get_evaluated_properties(), you can get all properties evaluated with multiple methods by using get_evaluated_properties_for_state() or get_evaluated_properties_for_state_pair().

# Get the value by specifying the state
energy = qy.get_evaluated_property_for_state(q_result, "energy", state=1)
# => {'state': 1, 'value': -0.6254196782618017, 'sample_std': 0.0}
energy.value # => -0.6254196782618017
# Get the value by specifying the state pair
tdm = qy.get_evaluated_property_for_state_pair(q_result, "transition_dipole_moment", state_pair=(0, 1))
# => {'state_pair': [0, 1], 'value': [{'real': 0.0, 'imag': 0.0}, {'real': 0.0, 'imag': 0.0}, {'real': -0.9847720194759502, 'imag': 0.0}]}
tdm.value[2] # => (-0.9847720194759502+0j)
qamuy.chemistry.get_evaluated_property_for_state(result, property_name, state=0)

Extract an evaluated property value for a state from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

  • state (int) – The index of a state for a property value to be extracted.

Returns:

An object containing a value for the specified property for the specified state, typically contains the state index, the property value and its sample standard deviation.

qamuy.chemistry.get_evaluated_properties_for_state(result, property_name, state=0)

Extract evaluated property values for a state from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

  • state (int) – The index of a state for a property value to be extracted.

Returns:

A list of objects containing a value for the specified property for the specified state, typically contains the state index, the property value and its sample standard deviation.

qamuy.chemistry.get_evaluated_property_for_state_pair(result, property_name, state_pair)

Extract an evaluated property value for a state pair from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

  • state_pair (Iterable[int]) – A pair of indices of the state pair for the property value to be extracted.

Returns:

An object containing a value for the specified property for the specified state pair, typically contains the state pair, the property value and its sample standard deviation.

qamuy.chemistry.get_evaluated_properties_for_state_pair(result, property_name, state_pair)

Extract evaluated property values for a state pair from a quantum/post-HF result object.

Parameters:
  • result – A QuantumDeviceResult or PostHFResult object.

  • property_name (str) – The name of a property to extract.

  • state_pair (Iterable[int]) – A pair of indices of the state pair for the property value to be extracted.

Returns:

A list of objects containing a value for the specified property for the specified state pair, typically contains the state pair, the property value and its sample standard deviation.

Get optimization history

You can use get_cost_history() to get the history of the value of the cost function during the VQE optimization process. When VQD is used, you need to use the function with a state argument since there is an optimization history for each state.

# For a non-VQD solver
qy.get_cost_history(vqe_log)
# => [-2.8676660336874353, -2.8730106287973363, -2.8774113831920385, -2.8776372678569313, -2.87766596449332, -2.877666000913216, -2.877666001029628]
# For VQD
qy.get_cost_history(vqe_log, state=0)
# => [-1.0905990711053306, -1.1224141482846215, -1.126120352809452, -1.126123161339495, -1.126123161383906]
qamuy.chemistry.get_cost_history(vqe_log, state=None)

Extract a history of the cost function in VQE as a list. For a non-VQD solver, state argument should not be passed since there is always only one cost history. For VQD, state argument should be passed to specify which cost history to extract.

Parameters:
  • vqe_log – A VQELog object.

  • state (Optional[int]) – (Only for VQD) The state index for which a cost history is extracted.

Returns:

A list containing a history of cost function value.

You can use get_energy_history_for_state() to get the history of energy values during the VQE optimization process. Since the energy is calculated state-by-state, it can be retrieved with the state argument.

# If you don't specify the state argument, get the history of state=0
qy.get_energy_history_for_state(vqe_log)
# => [-1.0905990711053308, -1.122414148284593, -1.126120352859052, -1.1261231613400429, -1.1261231613839124]
# Specify the state argument
qy.get_energy_history_for_state(vqe_log, state=1)
# => [-0.7980960020626229, -0.8373225307277186, -0.868697141428127, -0.877005924728595, -0.877050254353493, -0.8770502823998373, -0.8770502826217522]
qamuy.chemistry.get_energy_history_for_state(vqe_log, state=0)

Extract a history of energy of a state in VQE as a list.

Parameters:
  • vqe_log – A VQELog object.

  • state (int) – The index of a state for which the energy history it extracted.

Returns:

A list containing a history of energy value for the specified state.

Retrieve the optimized geometry

You can use get_optimized_geometry() to get the structure obtained by geometry optimization as a Molecule.Geometry object (the same format as the molecular structure created by molecule_geometry()).

opt_geo = qy.get_optimized_geometry(geo_result)
print(opt_geo)
# => {'atoms': ['H', 'H'], 'coordinates': [[0.0, 0.0, 0.0], [0.0, 0.0, 0.7414]], 'geometry_format': 'CARTESIAN'}
qamuy.chemistry.get_optimized_geometry(geo_result)

Extract an object representing optimized geometry of molecule.

Parameters:

geo_result – A GeometryOptimizationResult object.

Returns:

A Molecule.Geometry object.

Furthermore, geometry_to_xyz() allows you to output molecular structures represented by Molecule.Geometry object as a string of “xyz format”, a format commonly used in the field of computational chemistry. This is useful for visualization of molecular structures using third-party libraries.

geo_xyz = qy.geometry_to_xyz(opt_geo)
print(geo_xyz)
# =>
# 2
#
# H           0.00000        0.00000        0.00000
# H           0.00000        0.00000        0.74140
qamuy.chemistry.geometry_to_xyz(geometry, vib_mode=None)

Convert molecular geometry to a string of xyz format.

Parameters:
  • geometry – A Molecule.Geometry object.

  • vib_mode (optional) – A list of displacements of each nucleus specifying a vibration mode, whose length is 3 * n_atoms, e.g., [0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] for water molecule

Returns:

A string of xyz format.

Visualize information in output data

It is possible with the SDK to visualize information contained in output data. The following types of visualization are supported.

  • Plot of histories of cost functions/energy values during optimization processes of VQE

Matplotlib is used for visualization and each visualization function returns a tuple of Figure and Axes of Matplotlib. Therefore you can customize the plot or save it to files via functionalities of Matplotlib. Please refer to Matplotlib document for details.

Plot of histories of cost/energy during VQE optimization

Example: Plot with a single calculation result

You can plot cost or energy history based on a calculation result from Qamuy as follows:

import qamuy.plot

# Execute calculation and extract output data
results = client.wait_and_get_job_results([job])
output = results[0].output

# Plot cost function history
fig, ax = qamuy.plot.plot_cost_history(output)
# Save to an image file with Matplotlib feature
fig.savefig("cost_history.png", bbox_inches="tight")

# Plot energy history
fig, ax = qamuy.plot.plot_energy_history(output, state_label_map={0: "S0", 1: "T1"})
# Save to an image file with Matplotlib feature
fig.savefig("energy_history.png", bbox_inches="tight")
Plot example of cost function history

Plot example of cost function history

Plot example of energy history

Plot example of energy history

Example: Plot with multiple calculation results

In order to plot cost or energy histories from multiple calculation results, you need to create a list of qamuy.plot.HistoryPlotOptions objects.

import qamuy.plot

# Execute calculation and extract output data
results = client.wait_and_get_job_results([job])
outputs = [result.output for result in results]

# Define input data for plot
plot_options = [
  qamuy.plot.HistoryPlotOptions(output)
  for output in outputs
]

# Plot cost function history
fig, ax = qamuy.plot.plot_cost_history(plot_options, history_label_template="$ansatz")
# Save to an image file with Matplotlib feature
fig.savefig("cost_history_multiple.png", bbox_inches="tight")

# Plot energy history
fig, ax = qamuy.plot.plot_energy_history(
  plot_options, state_label_map={0: "S0", 1: "T1"}, history_label_template="$ansatz $state"
)
# Save to an image file with Matplotlib feature
fig.savefig("energy_history_multiple.png", bbox_inches="tight")
Plot example of multiple cost function histories

Plot example of multiple cost function histories

Plot example of multiple energy histories

Plot example of multiple energy histories

Options for cost/energy history plot

When plotting a single calculation result, you can pass the output data to the plot functions directly. When plotting multiple calculation results at once, you need to create a list of HistoryPlotOptions objects and pass it to the plot functions.

class qamuy.plot.HistoryPlotOptions

An object containing options for cost function/energy history plot.

Parameters:
  • output (QamuyChemistryOutput) – Output data of a calculation by Qamuy

  • states (List[int], optional) – Specifies states to be included in the plot. All states are included if omitted.

  • history_label_template (str, optional) –

    A string template used to format labels for history entries. You can specify the following variables using $ notation of Python template strings.

    • $state: Label for the state

    • $solver: Eigensolver

    • $ansatz: Ansatz

    • $depth: Depth of ansatz

    • $optimizer: Optimizer

    • $mapping: Fermion-qubit mapping

  • ref_label_template (str, optional) –

    A string template used to format labels for a reference post-HF method. You can specify the following variables using $ notation of Python template strings.

    • $state: Label for the state

    • $method: Post-HF method

Example
options = qamuy.plot.HistoryPlotOptions(
  output,
  states=[0, 1],
  history_label_template="$solver: $state",
  ref_label_template="$method: $state",
)

Plot of cost function history

You can plot cost function history with plot_cost_history function.

qamuy.plot.plot_cost_history(plot_input, *, states=None, history_label_template=None, state_label_map=None, **fig_kwargs)

Plot histories of cost function values evaluated during an optimization process of VQE.

Parameters:
  • plot_input (QamuyChemistryOutput, HistoryPlotOptions or List[HistoryPlotOptions]) – Input data for the plot

  • states (List[int], optional) – Specifies states to be included in the plot. All states are included if omitted.

  • history_label_template (str, optional) –

    A string template used to format labels for history entries. You can specify the following variables using $ notation of Python template strings.

    • $state: Label for the state

    • $solver: Eigensolver

    • $ansatz: Ansatz

    • $depth: Depth of ansatz

    • $optimizer: Optimizer

    • $mapping: Fermion-qubit mapping

  • state_label_map (Dict[int, str], optional) – A dict mapping each state index (int) to a label displayed in plot legend. Zero-based state index is used if omitted.

Returns:

A tuple of Matplotlib’s Figure and Axes.

Example
fig, ax = qamuy.plot.plot_cost_history(
  output,
  states=[0, 1],
  history_label_template="$solver: $state",
  state_label_map={0: "S0", 1: "T1"}
)

Plot of energy history

You can plot energy history with plot_energy_history function.

qamuy.plot.plot_energy_history(plot_input, *, states=None, reference_method='AUTO', history_label_template=None, ref_label_template=None, state_label_map=None, **fig_kwargs)

Plot histories of energy evaluated during an optimization process of VQE.

Parameters:
  • plot_input (QamuyChemistryOutput, HistoryPlotOptions or List[HistoryPlotOptions]) – Input data for the plot

  • states (List[int], optional) – Specifies states to be included in the plot. All states are included if omitted.

  • reference_method (str or PostHFMethod.Type, optional) – Specifies a post-HF method for which energy value is plotted as a reference value. AUTO is used if omitted, which uses the first available post-HF energy is used. Specify None to suppress plotting reference values.

  • history_label_template (str, optional) –

    A string template used to format labels for history entries. You can specify the following variables using $ notation of Python template strings.

    • $state: Label for the state

    • $solver: Eigensolver

    • $ansatz: Ansatz

    • $depth: Depth of ansatz

    • $optimizer: Optimizer

    • $mapping: Fermion-qubit mapping

  • state_label_map (Dict[int, str], optional) – A dict mapping each state index (int) to a label displayed in plot legend. Zero-based state index is used if omitted.

Returns:

A tuple of Matplotlib’s Figure and Axes.

Example
fig, ax = qamuy.plot.plot_energy_history(
  output,
  states=[0, 1],
  reference_method="CASCI",
  history_label_template="$solver: $state",
  state_label_map={0: "S0", 1: "T1"}
)

Advanced customization of history plot

If you want to customize optimization history plot further, you can extend the following classes.

HistoryPlotter is an abstract base class for various kinds of history plot. A concrete class inheriting HistoryPlotter should implement plot_data method. You can use plot method to do the plot.

class qamuy.plot.HistoryPlotter

An abstract base class for history plot.

title

Plot title

Type:

str

x_label

Label of X axis

Type:

str

y_label

Label of Y axis

Type:

str

history_label_template

A string template used to format labels for history entries. You can specify the following variables using $ notation of Python template strings.

  • $state: Label for the state

  • $solver: Eigensolver

  • $ansatz: Ansatz

  • $depth: Depth of ansatz

  • $optimizer: Optimizer

  • $mapping: Fermion-qubit mapping

Type:

str

ref_label_template

A string template used to format labels for a reference post-HF method. You can specify the following variables using $ notation of Python template strings.

  • $state: Label for the state

  • $method: Post-HF method

Type:

str

state_label_map

A dict mapping each state index (int) to a label displayed in plot legend. Zero-based state index is used if omitted.

Type:

Dict[int, str]

legend_kwargs

Keyword arguments passed to Axes.legend method of Matplotlib.

Type:

dict

setup_caption_kwargs

Keyword arguments passed to Axes.text method of Matplotlib when drawing a caption describing the caluclation setup.

Type:

dict

abstract HistoryPlotter.plot_data(fig, ax, mol_result_and_states)

An abstract method to plot data. Subclasses should define this method.

HistoryPlotter.plot(plot_input, states=None, **fig_kwargs)

Plot a history plot with given input data.

Parameters:

CostHistoryPlotter and EnergyHistoryPlotter are concrete classes inheriting HistoryPlotter, which are for plot of cost function and energy history.

class qamuy.plot.CostHistoryPlotter

A concrete class for cost history plot.

class qamuy.plot.EnergyHistoryPlotter(reference_method='AUTO')

A concrete class for energy history plot.