Skip to content

Commit

Permalink
Minor reorganization of code
Browse files Browse the repository at this point in the history
  • Loading branch information
gonfeco committed Oct 31, 2023
1 parent 802b718 commit daa966e
Show file tree
Hide file tree
Showing 9 changed files with 153 additions and 139 deletions.
2 changes: 1 addition & 1 deletion tests/test_btc_02_ae.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def test_ae_rqae():
ae_bench.exe()
filename = folder + benchmark_arguments["summary_results"]
a = pd.read_csv(filename, header=[0, 1], index_col=[0, 1])
print(a["absolute_error_sum"]["mean"])
#print(a["absolute_error_sum"]["mean"])
assert((a["IntegralAbsoluteError"]["mean"] < 0.01).all())
#print(100* list(a['KS']['mean'])[0])
#assert(100* list(a['absolute_error_sum']['mean'])[0] < 1.0)
Expand Down
52 changes: 38 additions & 14 deletions tnbs/BTC_04_PH/PH/launch_vqe_step_fromfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,24 @@
Author: Gonzalo Ferro
"""

import os
import json
from utils_ph import combination_for_list
from vqe_step_fromfile import run_ph_execution
import pandas as pd
from utils_ph import get_filelist
from vqe_step_fromfolder import run_ph_execution

def list_files(folder, filelistname):
#filelist = os.listdir(folder)
filelist = list(pd.read_csv(filelistname, header=None)[0])
final_files = []
for file_ in filelist:
final_files = final_files + get_filelist(folder + file_+"/")
return final_files

def run_id(**configuration):
def run_id(basefn, **configuration):
configuration.update({"base_fn": basefn})
pdf = run_ph_execution(**configuration)
print(pdf)

if __name__ == "__main__":
import logging
Expand All @@ -25,6 +36,20 @@ def run_id(**configuration):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

parser.add_argument(
"-filelist",
dest="filelist",
type=str,
default="./",
help="Filename with folder to use",
)
parser.add_argument(
"-folder",
dest="folder",
type=str,
default="./",
help="Path for searching the folder",
)
parser.add_argument(
"--count",
dest="count",
Expand Down Expand Up @@ -63,25 +88,24 @@ def run_id(**configuration):
)
args = parser.parse_args()
# Load json file
json_file = "vqe_step_fromfile.json"
json_file = "vqe_step_fromfolder.json"
f_ = open(json_file)
conf = json.load(f_)
# Creating Combination list
combination_list = combination_for_list(conf)

print(conf)
files_list = list_files(args.folder, args.filelist)
if args.print:
if args.id is not None:
print(combination_list[args.id])
print(files_list[args.id])
elif args.all:
print(combination_list)
print(files_list)
else:
print("Provide -id or --all")
if args.count:
print("Number of elements: {}".format(len(combination_list)))
print("Number of elements: {}".format(len(files_list)))
if args.execution:
if args.id is not None:
configuration = combination_list[args.id]
run_id(**configuration)
configuration = files_list[args.id]
run_id(configuration, **conf)
if args.all:
for configuration in combination_list:
run_id(**configuration)
for configuration in files_list:
run_id(configuration, **conf)
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
"""
For launching a VQE quantum step execution
For masive execution of VQE step using vqe_step_fromfile.py script
Author: Gonzalo Ferro
"""

import os
import json
import pandas as pd
from utils_ph import get_filelist
from vqe_step_fromfolder import run_ph_execution
from utils_ph import combination_for_list
from vqe_step_fromfile import run_ph_execution

def list_files(folder, filelistname):
#filelist = os.listdir(folder)
filelist = list(pd.read_csv(filelistname, header=None)[0])
final_files = []
for file_ in filelist:
final_files = final_files + get_filelist(folder + file_+"/")
return final_files

def run_id(basefn, **configuration):
configuration.update({"base_fn": basefn})
def run_id(**configuration):
pdf = run_ph_execution(**configuration)
print(pdf)

if __name__ == "__main__":
import logging
Expand All @@ -36,20 +25,6 @@ def run_id(basefn, **configuration):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

parser.add_argument(
"-filelist",
dest="filelist",
type=str,
default="./",
help="Filename with folder to use",
)
parser.add_argument(
"-folder",
dest="folder",
type=str,
default="./",
help="Path for searching the folder",
)
parser.add_argument(
"--count",
dest="count",
Expand All @@ -76,7 +51,7 @@ def run_id(basefn, **configuration):
dest="print",
default=False,
action="store_true",
help="For printing the AE algorihtm configuration."
help="For printing the configuration."
)
#Execution argument
parser.add_argument(
Expand All @@ -88,24 +63,25 @@ def run_id(basefn, **configuration):
)
args = parser.parse_args()
# Load json file
json_file = "vqe_step_fromfolder.json"
json_file = "vqe_step_frominput.json"
f_ = open(json_file)
conf = json.load(f_)
print(conf)
files_list = list_files(args.folder, args.filelist)
# Creating Combination list
combination_list = combination_for_list(conf)

if args.print:
if args.id is not None:
print(files_list[args.id])
print(combination_list[args.id])
elif args.all:
print(files_list)
print(combination_list)
else:
print("Provide -id or --all")
if args.count:
print("Number of elements: {}".format(len(files_list)))
print("Number of elements: {}".format(len(combination_list)))
if args.execution:
if args.id is not None:
configuration = files_list[args.id]
run_id(configuration, **conf)
configuration = combination_list[args.id]
run_id(**configuration)
if args.all:
for configuration in files_list:
run_id(configuration, **conf)
for configuration in combination_list:
run_id(**configuration)
4 changes: 3 additions & 1 deletion tnbs/BTC_04_PH/PH/vqe_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ def run(self):
if self.truncation is not None:
index = abs(self.pauli_ph["PauliCoefficients"]) > self.truncation
self.pauli_pdf = self.pauli_ph[index]
logger.debug("Additional truncation of Pauli Coeficients")
logger.debug(
"Additional truncation of Pauli Coeficients: {}".format(
len(self.pauli_pdf)))
else:
self.pauli_pdf = self.pauli_ph
pauli_coefs = list(self.pauli_pdf["PauliCoefficients"])
Expand Down
19 changes: 7 additions & 12 deletions tnbs/BTC_04_PH/PH/vqe_step_fromfile.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
[
{
"nqubits": [28, 29, 30],
"depth": [1],
"t_inv": [true],
"truncation": [null],
"nb_shots": [0],
"qpu_ph": ["qlmass"],
"save": [true],
"base_fn": ["/home/cesga/gferro/Codigo/TensorNetworks/Zalo"]
}
]
{
"nb_shots": null,
"truncation": null,
"t_inv": true,
"qpu_ph": "c",
"save": false
}
75 changes: 33 additions & 42 deletions tnbs/BTC_04_PH/PH/vqe_step_fromfile.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,65 @@
"""
For executing a VQE quantum step of a ansatz and a given
Parent Hamiltonian
In this case the input are a folder, base_fn, and it is expected
that in the folder exist files with following pattern names
nqubits_{}_depth_{}_parameters.csv
nqubits_{}_depth_{}_pauli.csv
The nqubits and the depth is passed as input (keyowrd arguments)
Parent Hamiltonian.
Here the input is a base file name that should have following pattern:
ansatz_{}_nqubits_{}_depth_{}_qpu_ansatz_{}
From this name following information should be extracted:
* ansatz_{}: the name of the ansatz
* nqubits_{}: the number of qubits for the ansatz
* depth_{}: the depth of the ansatz
* qpu_ansatz_{}: the qpu used for solving the ansatz
For the input base file name following files has to exist:
* {}_parameters.csv
* {}_pauli.csv
Here alwways talk about complete file names. The pattern can be found
in the bare name of the file, or in the folder that contain the file.
Example of valid names:
* ansatz_simple01_nqubits_27_depth_4_qpu_ansatz_qat_qlmass/8b961e30-5fc2-11ee-b12a-080038bfd786
* ansatz_simple01_nqubits_16_depth_4_qpu_c.csv
Author: Gonzalo Ferro
"""

import logging
import ast
import pandas as pd
from utils_ph import get_qpu
from utils_ph import get_info_basefn, get_qpu
from ansatzes import ansatz_selector, angles_ansatz01
from vqe_step import PH_EXE

logger = logging.getLogger("__name__")


def run_ph_execution(**configuration):
"""
Given an ansatz circuit, the parameters and the Pauli decomposition
of the corresponding local PH executes a VQE step for computing
the energy of the ansatz under the Hamiltonian that MUST BE near 0
Given a Folder with following pattern:
* ansatz_{}_nqubits_{}_depth_{}_qpu_ansatz_{}
That contains files with following patter:
* {}_parameters.csv
* {}_pauli.csv
Workflow:
* Getting the nqubits and depth from keyword arguments.
* Using them and the base_fn following file names are created:
base_fn + nqubits_{}_depth_{}_parameters.csv
base_fn + nqubits_{}_depth_{}_pauli.csv
* The Parameter are loading from parameters file.
* The QLM circuit is created (simplest ansatz) using
nqubits and depth.
* Parameters are loading in QLM circuit.
* The Pauli decomposition is loaded from pauli files.
* Create QLM circuit using the ansatz type readed from the folder
* Loading parameters for the circuit from: {}_parameters.csv
* Loading Pauli Decomposition from: {}_pauli.csv
* Executes VQE step.
* Stores the result of the execution: {}_phexe.csv
"""

logger.info("Creating ansatz circuit")
nqubits = configuration["nqubits"]
depth = configuration["depth"]
base_fn = configuration["base_fn"]
print(base_fn)
depth, nqubits, ansatz = get_info_basefn(base_fn)
ansatz_conf = {
"nqubits" :nqubits,
"depth" : depth,
}
circuit = ansatz_selector("simple01", **ansatz_conf)
circuit = ansatz_selector(ansatz, **ansatz_conf)

logger.info("Loading Parameters")
base_fn = configuration["base_fn"] + "/nqubits_{}_depth_{}".format(
str(nqubits).zfill(2), depth)
print(base_fn)
parameters_pdf = pd.read_csv(
base_fn + "_parameters.csv", sep=";", index_col=0)
# Formating Parameters
Expand Down Expand Up @@ -83,7 +89,6 @@ def run_ph_execution(**configuration):
exe_ph.run()
return exe_ph.pdf


if __name__ == "__main__":
import logging
logging.basicConfig(
Expand All @@ -103,20 +108,6 @@ def run_ph_execution(**configuration):
default="",
help="Base Filename for Loading Files",
)
parser.add_argument(
"-nqubits",
dest="nqubits",
type=int,
help="Number of qbits for the ansatz.",
default=None,
)
parser.add_argument(
"-depth",
dest="depth",
type=int,
help="Depth for ansatz.",
default=None,
)
parser.add_argument(
"-nb_shots",
dest="nb_shots",
Expand Down Expand Up @@ -154,4 +145,4 @@ def run_ph_execution(**configuration):
)
args = parser.parse_args()

run_ph_execution(**vars(args))
print(run_ph_execution(**vars(args)))
7 changes: 0 additions & 7 deletions tnbs/BTC_04_PH/PH/vqe_step_fromfolder.json

This file was deleted.

12 changes: 12 additions & 0 deletions tnbs/BTC_04_PH/PH/vqe_step_frominput.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"nqubits": [28, 29, 30],
"depth": [1],
"t_inv": [true],
"truncation": [null],
"nb_shots": [0],
"qpu_ph": ["qlmass"],
"save": [true],
"base_fn": ["/home/cesga/gferro/Codigo/TensorNetworks/Zalo"]
}
]
Loading

0 comments on commit daa966e

Please sign in to comment.