-
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
Open
Elscrux
wants to merge
20
commits into
develop
Choose a base branch
from
feat/demonstrator/hydrogen
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
1f8fc9b
chore: adjust to new application.properties layout
Elscrux f59035d
feat: Add molecule energy simulator
Elscrux 8649ff2
refactor: Rename from hydrogen to molecule energy
Elscrux 7505df1
feat: Add note about molecule format
Elscrux 623c720
feat: Add molecule energy demonstrator description
Elscrux 0a0a49a
chore: Change arguments to singular argument
Elscrux 36692a5
chore: Use updated application.properties and venv
Elscrux 2409ecf
refactor: Move requirements.txt to solver directory to follow the new…
Elscrux 3a15690
chore: Remove unused imports
Elscrux 24ec469
chore: Change exception type
Elscrux 2b19648
chore: Move imports up
Elscrux e17bf15
chore: fixate python requirement versions based on report in https://…
Elscrux 7c4d29f
chore: remove redundant assignment of optimizer
Elscrux 9198ebf
test: adapt CplexMipDemonstratorTest to general DemonstratorTest
Elscrux a07a76a
chore: remove old debug command
Elscrux 6fa2f8b
fix: put molecule argument in quotes
Elscrux c19b3f2
chore: update build file to remove syntax deprecated in gradle v9
Elscrux 5e3cb4b
feat: add detailed report of used arguments
Elscrux cfe5e9c
fix: remove prints from script as they also end up in the solution re…
Elscrux bc474be
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.