-
Notifications
You must be signed in to change notification settings - Fork 1
Molecule Energy Simulator #131
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
9d5f0d7
chore: adjust to new application.properties layout
Elscrux 0ed292f
feat: Add molecule energy simulator
Elscrux e6eb5e5
refactor: Rename from hydrogen to molecule energy
Elscrux dcfeaf4
feat: Add note about molecule format
Elscrux 471fbaa
feat: Add molecule energy demonstrator description
Elscrux 9824832
chore: Change arguments to singular argument
Elscrux add7460
chore: Use updated application.properties and venv
Elscrux e82c139
refactor: Move requirements.txt to solver directory to follow the new…
Elscrux 2d0521e
chore: Remove unused imports
Elscrux 45c8311
chore: Change exception type
Elscrux 24f5340
chore: Move imports up
Elscrux 5666829
chore: fixate python requirement versions based on report in https://…
Elscrux 03df7f6
chore: remove redundant assignment of optimizer
Elscrux 0c41bf5
test: adapt CplexMipDemonstratorTest to general DemonstratorTest
Elscrux 544c31b
chore: remove old debug command
Elscrux 5e78b31
fix: put molecule argument in quotes
Elscrux e124884
chore: update build file to remove syntax deprecated in gradle v9
Elscrux bd6a8f7
feat: add detailed report of used arguments
Elscrux 3730ba4
fix: remove prints from script as they also end up in the solution re…
Elscrux 2811a1f
test: increase timeout of timeouted tests
Elscrux File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
demonstrators/qiskit/molecule-energy/molecule-energy.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| from qiskit import QuantumCircuit | ||
| from qiskit_algorithms import VQE | ||
| from qiskit_algorithms.optimizers import L_BFGS_B, SLSQP | ||
| from qiskit.circuit.library import TwoLocal | ||
| from qiskit_nature.second_q.algorithms import GroundStateEigensolver | ||
| from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD | ||
| from qiskit_nature.second_q.drivers import PySCFDriver | ||
| from qiskit_nature.second_q.mappers import JordanWignerMapper, ParityMapper | ||
| from qiskit.primitives import Estimator | ||
| import matplotlib.pyplot as plt | ||
| from io import StringIO | ||
| import numpy as np | ||
| import sys | ||
|
|
||
| arg_count = len(sys.argv) - 1 | ||
| if arg_count != 1: | ||
| raise ValueError(f'This script expects exactly 1 argument: the molecule, but got {arg_count}: {sys.argv[1:]}') | ||
| molecule = sys.argv[1] | ||
|
|
||
| driver = PySCFDriver(atom=molecule) | ||
| problem = driver.run() | ||
|
|
||
| mapper = ParityMapper(num_particles=problem.num_particles) | ||
|
|
||
| optimizer = L_BFGS_B() | ||
|
|
||
| estimator = Estimator() | ||
|
|
||
| ansatz = UCCSD( | ||
| problem.num_spatial_orbitals, | ||
| problem.num_particles, | ||
| mapper, | ||
| initial_state=HartreeFock( | ||
| problem.num_spatial_orbitals, | ||
| problem.num_particles, | ||
| mapper, | ||
| ), | ||
| ) | ||
|
|
||
| vqe = VQE(estimator, ansatz, optimizer) | ||
| vqe.initial_point = [0] * ansatz.num_parameters | ||
|
|
||
| algorithm = GroundStateEigensolver(mapper, vqe) | ||
|
|
||
| electronic_structure_result = algorithm.solve(problem) | ||
| electronic_structure_result.formatting_precision = 6 | ||
|
|
||
| driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.74279') | ||
| problem = driver.run() | ||
|
|
||
| mapper = JordanWignerMapper() | ||
|
|
||
| optimizer = SLSQP(maxiter=10000, ftol=1e-9) | ||
|
|
||
| estimator = Estimator() | ||
|
|
||
| var_forms = [['ry', 'rz'], 'ry'] | ||
| entanglements = ['full', 'linear'] | ||
| entanglement_blocks = ['cx', 'cz', ['cx', 'cz']] | ||
| depths = list(range(1, 11)) | ||
|
|
||
| reference_circuit = QuantumCircuit(4) | ||
| reference_circuit.x(0) | ||
| reference_circuit.x(2) | ||
|
|
||
| results = np.zeros((len(depths), len(entanglements), len(var_forms), len(entanglement_blocks))) | ||
|
|
||
| for i, d in enumerate(depths): | ||
| for j, e in enumerate(entanglements): | ||
| for k, vf in enumerate(var_forms): | ||
| for l, eb in enumerate(entanglement_blocks): | ||
| variational_form = TwoLocal(4, rotation_blocks=vf, entanglement_blocks=eb, entanglement=e, reps=d) | ||
|
|
||
| ansatz = reference_circuit.compose(variational_form) | ||
|
|
||
| vqe = VQE(estimator, ansatz, optimizer) | ||
| vqe.initial_point = [0] * ansatz.num_parameters | ||
|
|
||
| algorithm = GroundStateEigensolver(mapper, vqe) | ||
|
|
||
| electronic_structure_result = algorithm.solve(problem) | ||
|
|
||
| results[i, j, k, l] = electronic_structure_result.total_energies[0] | ||
|
|
||
| fig1, axs1 = plt.subplots(2, 3, sharey=True, sharex=True) | ||
| fig2, axs2 = plt.subplots(2, 3, sharey=True, sharex=True) | ||
|
|
||
| fig1.supxlabel('Depth') | ||
| fig1.supylabel('Estimated ground state energy') | ||
| fig2.supxlabel('Depth') | ||
| fig2.supylabel('Estimated ground state energy') | ||
|
|
||
| for j, e in enumerate(entanglements): | ||
| for l, eb in enumerate(entanglement_blocks): | ||
| axs1[j, l].plot(depths, results[:, j, 0, l]) | ||
| axs1[j, l].set_title(f'{e}, ryrz, {eb}') | ||
| axs1[j, l].text(0.90, 0.75, f'Min: {np.min(results[:, j, 0, l]):.3f}') | ||
|
|
||
| for j, e in enumerate(entanglements): | ||
| for l, eb in enumerate(entanglement_blocks): | ||
| axs2[j, l].plot(depths, results[:, j, 1, l]) | ||
| axs2[j, l].set_title(f'{e}, ry, {eb}') | ||
| axs2[j, l].text(0.90, 0.75, f'Min: {np.min(results[:, j, 1, l]):.3f}') | ||
|
|
||
|
|
||
| def print_fig(fig): | ||
| string_io = StringIO() | ||
| fig.savefig(string_io, format='svg') | ||
| print(string_io.getvalue()) | ||
|
|
||
|
|
||
| print_fig(fig1) | ||
| print_fig(fig2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # This file describes the python package requirements for all Qiskit demonstrator scripts | ||
| # supported by ProvideQ | ||
|
|
||
| # required for molecule energy solver | ||
| qiskit==1.1.0 | ||
| qiskit-aer==0.14.2 | ||
| qiskit-algorithms==0.3.0 | ||
| qiskit-ibm-runtime==0.25.0 | ||
| qiskit-machine-learning==0.7.2 | ||
| qiskit-nature==0.7.2 | ||
| qiskit-nature-pyscf==0.4.0 | ||
| qiskit-qasm3-import==0.5.0 | ||
| qiskit-transpiler-service==0.4.5 | ||
| matplotlib==3.9.2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
src/main/java/edu/kit/provideq/toolbox/demonstrators/MoleculeEnergySimulator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| package edu.kit.provideq.toolbox.demonstrators; | ||
|
|
||
| import edu.kit.provideq.toolbox.Solution; | ||
| import edu.kit.provideq.toolbox.meta.SolvingProperties; | ||
| import edu.kit.provideq.toolbox.meta.SubRoutineResolver; | ||
| import edu.kit.provideq.toolbox.meta.setting.SolverSetting; | ||
| import edu.kit.provideq.toolbox.meta.setting.basic.TextSetting; | ||
| import edu.kit.provideq.toolbox.process.PythonProcessRunner; | ||
| import java.util.List; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.ApplicationContext; | ||
| import org.springframework.stereotype.Component; | ||
| import reactor.core.publisher.Mono; | ||
|
|
||
| /** | ||
| * Demonstrator for the Molecule Energy simulation. | ||
| * Note that its python dependencies can only be installed on Linux and macOS. | ||
| * Based on this <a href="https://github.com/qiskit-community/qiskit-community-tutorials/blob/master/chemistry/h2_var_forms.ipynb">Jupyter Notebook</a> | ||
| */ | ||
| @Component | ||
| public class MoleculeEnergySimulator implements Demonstrator { | ||
| private final String scriptPath; | ||
| private final String venv; | ||
| private final ApplicationContext context; | ||
|
|
||
| private static final String SETTING_MOLECULE = "Molecule"; | ||
| private static final String DEFAULT_MOLECULE = "H .0 .0 .0; H .0 .0 0.74279"; | ||
|
|
||
| @Autowired | ||
| public MoleculeEnergySimulator( | ||
| @Value("${path.demonstrators.qiskit.molecule-energy}") String scriptPath, | ||
| @Value("${venv.demonstrators.qiskit.molecule-energy}") String venv, | ||
| ApplicationContext context) { | ||
| this.scriptPath = scriptPath; | ||
| this.venv = venv; | ||
| this.context = context; | ||
| } | ||
|
|
||
| @Override | ||
| public String getName() { | ||
| return "Molecule Energy Simulator"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Computes the ground state energy for a given molecule using VQE algorithm."; | ||
| } | ||
|
|
||
| @Override | ||
| public List<SolverSetting> getSolverSettings() { | ||
| return List.of( | ||
| new TextSetting( | ||
| false, | ||
| SETTING_MOLECULE, | ||
| "The molecule to be simulated in XYZ format - a di-hydrogen molecule by default", | ||
| DEFAULT_MOLECULE | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Override | ||
| public Mono<Solution<String>> solve(String input, SubRoutineResolver subRoutineResolver, | ||
| SolvingProperties properties) { | ||
| var solution = new Solution<>(this); | ||
|
|
||
| var molecule = properties.<TextSetting>getSetting(SETTING_MOLECULE) | ||
| .map(TextSetting::getText) | ||
| .orElse(DEFAULT_MOLECULE); | ||
|
|
||
| var processResult = context | ||
| .getBean(PythonProcessRunner.class, scriptPath, venv) | ||
| .withArguments('"' + molecule + '"') | ||
| .readOutputString() | ||
| .run(getProblemType(), solution.getId()); | ||
|
|
||
| return Mono.just(processResult.applyTo(solution)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 0 additions & 41 deletions
41
src/test/java/edu/kit/provideq/toolbox/api/CplexMipDemonstratorTest.java
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.