def log_to_file(filename="qrhei.log"): """Set logging to file """ manager = qr.Manager().log_conf #manager.log_on_screen = False manager.log_to_file = True manager.log_file_name = filename
def init_logging(): """Initialization of logging We test if the logging is parallel or not """ manager = qr.Manager().log_conf try: from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() if size == 1: manager.is_serial = True else: manager.is_serial = False manager.log_file_appendix = "." + str(rank) except: manager.is_serial = True manager.initialized = True
def quantarhei_installed(context, version=None): """Tests if quantarhei is installed and sets version to context if it is Parameters ---------- context : context object of behave version : str, None version string, if not none, presence of a specific version is asserted """ import quantarhei as qr context.version = qr.Manager().version if version is None: assert isinstance(context.version, str) else: assert context.version == version
def set_transition_width(self, transition, width): """Sets the width of a given transition Parameters ---------- transition : {tuple, list} Quantum numbers of the states between which the transition occurs width : float The full width at half maximum (FWHM) of a Gaussian lineshape, or half width at half maximum (HWHM) of a Lorentzian lineshape """ cwidth = qr.Manager().convert_energy_2_internal_u(width) if self.widths is None: N = self.elenergies.shape[0] self.widths = numpy.zeros((N, N), dtype=qr.REAL) self.widths[transition[0], transition[1]] = cwidth self.widths[transition[1], transition[0]] = cwidth
def do_command_run(args): """Runs a script """ m = qr.Manager().log_conf dc = qr.Manager().get_DistributedConfiguration() # # analyzing --verbosity option # verb = args.verbosity try: vrbint = int(verb) m.verbosity = vrbint m.fverbosity = vrbint + 2 except: try: vrbint = verb.split(",") m.verbosity = int(vrbint[0]) m.fverbosity = int(vrbint[1]) except: raise Exception( "Integer or two comma separated integers required" + " for -y/--verbosity option") # we set the verbosity lower for other than the leading process if dc.rank != 0: m.verbosity -= 2 m.fverbosity -= 2 # # log into file # m.log_to_file = args.logtofile if m.log_to_file: m.log_file_name = args.filename # # parallel options # nprocesses = args.nprocesses flag_parallel = args.parallel hostfile = "" if len(args.hostfile) > 0: hostfile = args.hostfile # # some other logging option # flag_silent = args.silent flag_quiet = args.quiet if args.silent: m.verbosity = 0 # # Run benchmark # if args.benchmark > 0: import time qr.printlog("Running benchmark no. ", args.benchmark, verbose=True, loglevel=1) import quantarhei.benchmarks.bm_001 as bm t1 = time.time() bm.main() t2 = time.time() qr.printlog("... done in", t2 - t1, "sec", verbose=True, loglevel=1) return # # Script name # if args.script: scr = args.script[0] # # if the file is yaml, look into it to find the script file name # # get the file extension extsplt = os.path.splitext(scr) ext = extsplt[1] # # Reading configuration file # # yaml if ext in [".yaml", ".yml"]: INP = qr.Input(scr) # see if the script name is specified, if not use the conf name + .py try: script = INP.script except: script = extsplt[0] + ".py" # see if path is defined, if not use local directory try: spath = INP.path except: spath = "." scr = os.path.join(spath, script) # # Greeting # if not flag_quiet: qr.printlog("", verbose=True, loglevel=qr.LOG_URGENT) qr.printlog("Running Quantarhei (python) script file: ", scr, verbose=True, loglevel=qr.LOG_URGENT) # # Run serial or parallel # if flag_parallel: # # If this is set to True, we use one more processes than processor # number to steer other processes # # Also set the corresponding flag in the parallel module # use_steerer = False if use_steerer: nsteerer = 1 else: nsteerer = 0 # # get parallel configuration # cpu_count = 0 try: import multiprocessing cpu_count = multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass prl_exec = "mpirun" prl_n = "-n" prl_h = "" if len(hostfile) > 0: prl_h += " --hostfile " + hostfile + " " if cpu_count != 0: prl_np = cpu_count + nsteerer else: prl_np = 4 if nprocesses != 0: prl_np = nprocesses + nsteerer # engine = "qrhei" if m.log_to_file: engine += " -lf " + m.log_file_name engine += " -y " + str(m.verbosity) + "," + str( m.fverbosity) + " run -q " # running MPI with proper parallel configuration prl_cmd = prl_exec + " " + prl_n + " " + str(prl_np) + " " + prl_h cmd = prl_cmd + engine + scr if not flag_silent: qr.printlog("System reports", cpu_count, "processors") qr.printlog("Starting parallel execution with", prl_np, "processes (executing command below)") qr.printlog(">>>", cmd) qr.printlog("") try: p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if not flag_silent and (not flag_quiet): qr.printlog(" --- output below ---\n", verbose=True, loglevel=1) # read and print output for line in iter(p.stdout.readline, b''): #for line in p.stdout.readlines(): ln = line.decode() # line is returned with a \n character at the end # ln = ln[0:len(ln)-2] print(ln, end="", flush=True) retval = p.wait() except SystemExit: qr.printlog("", verbose=True, loglevel=qr.LOG_DETAIL) qr.printlog(" --- Exited by SystemExit --- ", verbose=True, loglevel=qr.LOG_DETAIL) pass else: if not flag_silent and (not flag_quiet): qr.printlog(" --- output below ---\n", verbose=True, loglevel=qr.LOG_URGENT) # running the script within the same interpreter try: # launch this properly, so that it gives information # on the origin of exceptions with open(scr, 'U') as fp: code = fp.read() exec(compile(code, scr, "exec"), globals()) except SystemExit: qr.printlog("", verbose=True, loglevel=qr.LOG_DETAIL) qr.printlog(" --- Exited by SystemExit --- ", verbose=True, loglevel=qr.LOG_DETAIL) except: print(traceback.format_exc()) retval = 0 # # Saying good bye # if retval == 0: if not flag_silent and (not flag_quiet): qr.printlog("", verbose=True, loglevel=1) qr.printlog(" --- output above --- \n", verbose=True, loglevel=qr.LOG_URGENT) qr.printlog("Finished sucessfully; exit code: ", retval, verbose=True, loglevel=1) else: qr.printlog("Warning, exit code: ", retval, verbose=True, loglevel=qr.LOG_URGENT)
ham = agg.get_Hamiltonian() ham.set_name("Hamiltonian") print(">>> Hamiltonian ") with qr.energy_units("1/cm"): print(ham) print(""" ******************************************************************************* Calculating relaxation tensor ******************************************************************************* """) m = qr.Manager() m.warn_about_basis_change = False sb_reference = qr.BasisReferenceOperator(ham.dim, name="site basis reference") # # Calculation of various relaxation tensors # ham.protect_basis() with qr.eigenbasis_of(ham): RRT = qr.qm.RedfieldRelaxationTensor(ham, sbi, name="Tensor 1") print("\nRelaxation times from the full relaxation tensor") for i in range(1, ham.dim):
def makeWidgets(self): self.makeMenuBar() self.makeToolBar() L = Label(self, text="Quantarhei version " + str(qr.Manager().version)) L.config(relief=SUNKEN, width=40, height=5, bg="white") L.pack(expand=YES, fill=BOTH)
# -*- coding: utf-8 -*- _show_plots_ = False import numpy import quantarhei as qr qr.Manager().gen_conf.legacy_relaxation = True print("Preparing a model system:") with qr.energy_units("1/cm"): mol1 = qr.Molecule([0.0, 12010]) mol2 = qr.Molecule([0.0, 12000]) mol3 = qr.Molecule([0.0, 12100]) mol4 = qr.Molecule([0.0, 12110]) agg = qr.Aggregate([mol1, mol2, mol3, mol4]) agg.set_resonance_coupling(2, 3, qr.convert(100.0, "1/cm", "int")) agg.set_resonance_coupling(1, 3, qr.convert(100.0, "1/cm", "int")) agg.set_resonance_coupling(1, 2, qr.convert(0.0, "1/cm", "int")) qr.save_parcel(agg, "agg.qrp") agg2 = qr.load_parcel("agg.qrp") agg2.build() H = agg2.get_Hamiltonian() print("...done") print("Setting up Lindblad form relaxation:") Ndim = 5
# # tags under which the data is saved to the container # tags = ["a", "b", "c", "d", "e", "f", "g"] # container for local calculation cont = dict() # global container to hold the collected results collected_cont = dict() # two membered list of containers containers = [collected_cont, cont] # config holds information about parallel environment config = qr.Manager().get_DistributedConfiguration() # iteration over the list for k, a in qr.block_distributed_list(lst, return_index=True): #print(config.rank, a) # calculation of the data b = numpy.zeros(2, dtype=qr.COMPLEX) b[0] = 2.0 * a b[1] = 3.2 * a + 1.3 # storing data under an appropriate tag cont[tags[k]] = b # here we collect the data to a single container available on the master nod qr.collect_block_distributed_data(containers, setter, retriever, tags=tags)
def bootstrap(self, rwa=0.0, pad=0, lab=None, verbose=False, write_resp=False, keep_resp=False): """Sets up the environment for 2D calculation write_resp takes a string, creates a directory with the name of the string and saves the respoonses and time axis as a npz file keep_resp saves the responses as a list of dictionaries. The list goes through the time points in t2. """ self.verbose = verbose self.pad = pad self.write_resp = write_resp self.keep_resp = keep_resp self.rwa = qr.Manager().convert_energy_2_internal_u(rwa) with qr.energy_units("int"): if self.write_resp: try: os.mkdir(write_resp) except OSError: print( "Creation of the directory failed, it either already " "exists or you didn't give a string") if True: # calculate 2D spectrum using aceto library ############################################################################### # # Create band_system from quantarhei classes # ############################################################################### if isinstance(self.system, Aggregate): pass else: raise Exception("Molecule 2D not implememted") agg = self.system agg.diagonalize() # # hamiltonian and transition dipole moment operators # H = agg.get_Hamiltonian() D = agg.get_TransitionDipoleMoment() # # Construct band_system object # Nb = 3 Ns = numpy.zeros(Nb, dtype=numpy.int) Ns[0] = 1 Ns[1] = agg.nmono Ns[2] = Ns[1] * (Ns[1] - 1) / 2 self.sys = band_system(Nb, Ns) # # Set energies # en = numpy.zeros(self.sys.Ne, dtype=numpy.float64) #if True: with eigenbasis_of(H): for i in range(self.sys.Ne): en[i] = H.data[i, i] self.sys.set_energies(en) # # Set transition dipole moments # dge_wr = D.data[0:Ns[0], Ns[0]:Ns[0] + Ns[1], :] def_wr = D.data[Ns[0]:Ns[0] + Ns[1], (Ns[0] + Ns[1]):(Ns[0] + Ns[1] + Ns[2]), :] dge = numpy.zeros((3, Ns[0], Ns[1]), dtype=numpy.float64) deff = numpy.zeros((3, Ns[1], Ns[2]), dtype=numpy.float64) for i in range(3): dge[i, :, :] = dge_wr[:, :, i] deff[i, :, :] = def_wr[:, :, i] self.sys.set_dipoles(0, 1, dge) self.sys.set_dipoles(1, 2, deff) # # Relaxation rates # if not self._has_rate_matrix: KK = agg.get_RedfieldRateMatrix() else: KK = self._rate_matrix # relaxation rate in single exciton band Kr = KK.data[Ns[0]:Ns[0] + Ns[1], Ns[0]:Ns[0] + Ns[1]] #*10.0 #print(1.0/KK.data) self.sys.init_dephasing_rates() self.sys.set_relaxation_rates(1, Kr) # # Lineshape functions # sbi = agg.get_SystemBathInteraction() cfm = sbi.CC cfm.create_double_integral() # # Transformation matrices # SS = H.diagonalize() SS1 = SS[1:Ns[1] + 1, 1:Ns[1] + 1] SS2 = SS[Ns[1] + 1:, Ns[1] + 1:] H.undiagonalize() self.sys.set_gofts(cfm._gofts) # line shape functions self.sys.set_sitep(cfm.cpointer) # pointer to sites self.sys.set_transcoef( 1, SS1) # matrix of transformation coefficients self.sys.set_transcoef( 2, SS2) # matrix of transformation coefficients # # Finding population evolution matrix # prop = PopulationPropagator(self.t1axis, Kr) # Uee, Uc0 = prop.get_PropagationMatrix(self.t2axis, # corrections=True) self.Uee, cor = prop.get_PropagationMatrix(self.t2axis, corrections=3) # FIXME: Order of transfer is set by hand here - needs to be moved # to some reasonable place #Ucor = Uee self.Uc0 = cor[0] #for ko in range(No+1): # print("Subtracting ", ko) # Ucor[:,:,tc] -= cor[ko] # # define lab settings # if lab is None: self.lab = lab_settings(lab_settings.FOUR_WAVE_MIXING) X = numpy.array([1.0, 0.0, 0.0], dtype=numpy.float64) self.lab.set_laser_polarizations(X, X, X, X) else: self.lab = lab # # Other parameters # #dt = self.t1axis.step self.rmin = 0.0001 self.t1s = self.t1axis.data self.t3s = self.t3axis.data atype = self.t1axis.atype self.t1axis.atype = 'complete' self.oa1 = self.t1axis.get_FrequencyAxis() self.oa1.data += self.rwa self.oa1.start += self.rwa #print(self.oa1.start, self.oa1.data[0]) self.t1axis.atype = atype atype = self.t3axis.atype self.t3axis.atype = 'complete' self.oa3 = self.t3axis.get_FrequencyAxis() self.oa3.data += self.rwa self.oa3.start += self.rwa #print(self.oa3.start, self.oa3.data[0]) self.t3axis.atype = atype else: raise Exception("So far, no 2D outside aceto") self.tc = 0
def loglevels2bool(loglevs, verbose=False): """Converts a list of loglevels to a list of bools This function converts loglevels to books (True or False values). Its primary usage is in logging semi-critical regions of vode by printlog() function efficiently. printlog() returns fast if verbose argument is set to False. Otherwise the function gets Manager instance, asks for current verbosity, and compares it with loglevel - a lot of work! If you want to avoid it say inside a nested loops, you better evaluate the loglevels in advance. Parameters ---------- loglevels : list of int List of logleves to be converted verbose : bool (default False) If False, the function is left immediatel with all values converted to False Returns ------- verb : list of bool List of bools, one fo each loglevel Examples -------- Standard usage: >>> m = qr.Manager() >>> m.verbosity = 5 >>> bools = loglevels2bool([0, 2, 5, 8, 10], verbose=True) >>> print(bools) [True, True, False, False, False] Do not forget to set verbose to True. It is False by default to avoid lengthy evaluation when not required >>> m = qr.Manager() >>> m.verbosity = 5 >>> bools = loglevels2bool([0, 2, 5, 8, 10]) >>> print(bools) [False, False, False, False, False] """ verb = [False] * len(loglevs) if verbose: m = qr.Manager().log_conf k_v = 0 for lev in loglevs: if m.verbosity > lev: verb[k_v] = True k_v += 1 return verb
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 09:12:29 2017 @author: tomas """ import time import os import numpy import quantarhei as qr manager = qr.Manager() # # BENCHMARK SETTINGS # Nthreads = 4 use_mpi = False fix_seed = True N_molecules = 4 # # build an elementary model to propagate # qr.log_report("") qr.log_report("Quantarhei benchmark calculation (task no. 001)", incr_indent=2)
import gc import platform # Numpy library import numpy import matplotlib.pyplot as plt # Quantarhei imports import quantarhei as qr from quantarhei.utils.vectors import X import quantarhei.functions as func from quantarhei.core.units import kB_int from quantarhei import printlog as print print("\n***** RC Simulation Script *****") print("\nUsing Quantarhei version", qr.Manager().version) # # SCRIPT INPUT FILE NAME # input_file = "input.yaml" INP = qr.Input(input_file, show_input=False) ################################################################################ ################################################################################ # # SOME DEFINITIONS AND HELPER FUNCTIONS # ################################################################################ ################################################################################
def main(): parser = argparse.ArgumentParser(description='Quantarhei Remote Launcher') parser.add_argument("directory", metavar='directory', type=str, help='job directory to launch', nargs='?') # # Driver options # parser.add_argument("-v", "--version", action="store_true", help="shows Quantarhei package version") parser.add_argument("-i", "--info", action='store_true', help="shows detailed information about Quantarhei" + " installation") parser.set_defaults(func=do_launch) # # Parsing all arguments # args = parser.parse_args() if len(sys.argv) < 2: parser.print_usage() qr.exit() # # show longer info # if args.info: qr.printlog("\n" + "qrhei: Quantarhei Package Driver\n", verbose=True, loglevel=1) # +"\n" # +"MPI parallelization enabled: ", flag_parallel, # verbose=True, loglevel=0) if not args.version: qr.printlog("Package version: ", qr.Manager().version, "\n", verbose=True, loglevel=1) return # # show just Quantarhei version number # if args.version: qr.printlog("Quantarhei package version: ", qr.Manager().version, "\n", verbose=True, loglevel=1) return
def parsing(): """This function handles parsing command line arguments """ descr = 'Ghenerate, the Gherkin Python Step Generator from Quantarhei' parser = argparse.ArgumentParser(description=descr + ' ...') parser.add_argument("file", metavar='file', type=str, help='feature file to be processed', nargs='?') # # Generator options # parser.add_argument("-v", "--version", action="store_true", help="shows Quantarhei package version") parser.add_argument("-i", "--info", action='store_true', help="shows detailed information about Quantarhei" + " installation") parser.add_argument("-d", "--destination", type=str, help="specifies destination directory for the" + " generated step file") parser.add_argument("-n", "--no-pass", action="store_true", help="empty tests should not pass (default is" + " passing empty tests)") parser.add_argument("-f", "--start-from", type=int, help="step functions will be numberred starting" + " from this value") # # Parsing all arguments # args = parser.parse_args() # # show longer info # if args.info: qr.printlog("\n" + "ghenerate: Quantarhei Gherkin Python Step Generator\n", verbose=True, loglevel=0) if not args.version: qr.printlog("Package version: ", qr.Manager().version, "\n", verbose=True, loglevel=0) return 0 # # show just Quantarhei version number # if args.version: qr.printlog("Quantarhei package version: ", qr.Manager().version, "\n", verbose=True, loglevel=0) return 0 if args.destination: ddir = args.destination else: ddir = "ghen" if args.file: print("") print(descr + " ...") filename = args.file else: print("No file specified: quiting") parser.print_help() return 0 steps_pass = True if args.no_pass: steps_pass = False k_from = 0 if args.start_from: k_from = args.start_from try: with open(filename, 'r') as myfile: data = myfile.read() except: raise Exception("Problems reading file: " + filename) parser = Parser() try: feature_file = parser.parse(TokenScanner(data)) except: raise Exception("Problem parsing file: " + filename + " - is it a feature file?") try: children = feature_file["feature"]["children"] except: raise Exception("No scenarii or scenario outlines") return dict(children=children, ddir=ddir, steps_pass=steps_pass, filename=filename, k_from=k_from)
Author: Tomas Mancal Faculty of Mathematics and Physics Charles University Ke Karlovu 5 CZ-121 16 Prague 2 Czech Republic Email: [email protected] ******************************************************************************* This script should use Quantarhei package ver. 0.0.45 and older """) print(" Current version of Quantarhei:", qr.Manager().version) ############################################################################### # # Simulation settings # ############################################################################### _show_plots_ = True # make a series of calculations with different resonance energies _repeate_ = True # fit selected decays to assign decay time _fit_ = True ############################################################################### #
def main(): global parser_list global parser_fetch parser = argparse.ArgumentParser(description='Quantarhei Package Driver') subparsers = parser.add_subparsers(help="Subcommands") # # Driver options # parser.add_argument("-v", "--version", action="store_true", help="shows Quantarhei package version") parser.add_argument("-i", "--info", action='store_true', help="shows detailed information about Quantarhei" + " installation") parser.add_argument("-y", "--verbosity", type=str, default="5", help="defines verbosity between 0 and 10") parser.add_argument("-f", "--filename", metavar="FILENAME", default="qrhei.log", help="defines verbosity for logging into file") parser.add_argument("-l", "--logtofile", action='store_true', help="copy logging into a file") # # Subparser for command `run` # parser_run = subparsers.add_parser("run", help="Script runner") parser_run.add_argument("script", metavar='script', type=str, help='script file to be processed', nargs=1) parser_run.add_argument("-s", "--silent", action='store_true', help="logging level set to zero") parser_run.add_argument("-q", "--quiet", action='store_true', help="no output from qrhei script itself") parser_run.add_argument("-p", "--parallel", action='store_true', help="executes the code in parallel") parser_run.add_argument("-n", "--nprocesses", type=int, default=0, help="number of processes to start") parser_run.add_argument("-f", "--hostfile", metavar="HOSTFILE", default="", help="list of available" + " host for parallel calculation") parser_run.add_argument("-b", "--benchmark", type=int, default=0, help="run one of the predefined benchmark" + " calculations") parser_run.set_defaults(func=do_command_run) # # Subparser for command `test` # parser_test = subparsers.add_parser("test", help="Test runner") parser_test.set_defaults(func=do_command_test) # # Subparser for command `fetch` # parser_fetch = subparsers.add_parser("fetch", help="Fetches examples," + " benchmarks, tutorials, templates" + " and configuration files") parser_fetch.add_argument("glob", metavar='glob', type=str, help='file name', nargs="?") parser_fetch.add_argument("-e", "--examples", action='store_true', help="fetches a specified example file") parser_fetch.set_defaults(func=do_command_fetch) # # Subparser for command `list` # parser_list = subparsers.add_parser("list", help="Lists examples," + " benchmarks, tutorials and templates") parser_list.add_argument("glob", metavar='glob', type=str, help='file name', nargs="?") parser_list.add_argument("-e", "--examples", action='store_true', help="list all available example files") parser_list.set_defaults(func=do_command_list) # # Subparser for command `config` # parser_conf = subparsers.add_parser("config", help="Configures Quantarhei") parser_conf.set_defaults(func=do_command_config) # # Subparser for command `report` # parser_report = subparsers.add_parser( "report", help="Probes Quantarhei as system configurations") parser_report.set_defaults(func=do_command_report) # # Subparser for command `file` # parser_file = subparsers.add_parser("file", help="Shows information about files" + " created by Quantarhei") parser_file.add_argument("fname", metavar='fname', type=str, help='file to be checked', nargs=1) parser_file.set_defaults(func=do_command_file) # # Parsing all arguments # args = parser.parse_args() # # show longer info # if args.info: qr.printlog("\n" + "qrhei: Quantarhei Package Driver\n", verbose=True, loglevel=1) # +"\n" # +"MPI parallelization enabled: ", flag_parallel, # verbose=True, loglevel=0) if not args.version: qr.printlog("Package version: ", qr.Manager().version, "\n", verbose=True, loglevel=1) return # # show just Quantarhei version number # if args.version: qr.printlog("Quantarhei package version: ", qr.Manager().version, "\n", verbose=True, loglevel=1) return try: if args.func: args.func(args) except: parser.error("No arguments provided")
def printlog(*args, verbose=True, loglevel=5, incr_indent=0, use_indent=True, **kwargs): """Prints logging information Parameters ---------- *args : arguments arguments like in a print function verbose: bool If True, information will be logged, otherwise the function leaves immediately loglevel : int Information will be logged, if loglevel between 0 and 10 is smaller than the value of verbosity set in the Manager class Details ------- The function prints loging information on the screen or into a file depending on global setting the Manager class. The behaviour is controlled by the following Manager attributes. verbosity : int The level of verbosity required to print; 0 means nothing will be printed, 10 means everything is logged log_on_screen : bool If True, logging information is printed on the screen log_to_file : bool If True, logging information is saved to a file log_file_opened : bool Set to True if logging file is opened log_file : file Handle of the logging file log_file_name : str Name of the logging file """ if not verbose: return if (loglevel > 10) or (loglevel < 0): raise Exception("Loglevel must be between 0 and 10") manager = qr.Manager().log_conf if not manager.initialized: init_logging() if not manager.verbose: return manager.log_indent += incr_indent if loglevel <= manager.verbosity: if manager.log_on_screen: if use_indent: indent = " " * manager.log_indent else: indent = "" print(indent, *args, **kwargs) if loglevel <= manager.fverbosity: if manager.log_to_file: if not manager.log_file_opened: manager.log_file = open( manager.log_file_name + manager.log_file_appendix, "w") manager.log_file_opened = True if use_indent: indent = " " * manager.log_indent else: indent = "" if "end" in kwargs.keys(): kwargs["end"] = None print(indent, *args, **kwargs, file=manager.log_file)
def main(): parser = argparse.ArgumentParser(description='Quantarhei Package Driver') parser.add_argument("script", metavar='script', type=str, help='script file to be processed', nargs='?') parser.add_argument("-v", "--version", action="store_true", help="shows Quantarhei package version") parser.add_argument("-i", "--info", action='store_true', help="shows detailed information about Quantarhei" + " installation") parser.add_argument("-s", "--silent", action='store_true', help="no output from qrhei script itself") parser.add_argument("-p", "--parallel", action='store_true', help="executes the code in parallel") parser.add_argument("-n", "--nprocesses", type=int, default=0, help="number of processes to start") parser.add_argument("-b", "--benchmark", type=int, default=0, help="run one of the predefined benchmark" + "calculations") parser.add_argument("-y", "--verbosity", type=int, default=5, help="defines verbosity between 0 and 10") args = parser.parse_args() nprocesses = args.nprocesses flag_parallel = args.parallel flag_silent = args.silent m = qr.Manager() m.verbosity = args.verbosity if args.silent: m.verbosity = 0 # # show longer info # if args.info: qr.printlog("\n" + "qrhei: Quantarhei Package Driver\n" + "\n" + "MPI parallelization enabled: ", flag_parallel, verbose=True, loglevel=0) if not args.version: qr.printlog("Package version: ", Manager().version, "\n", verbose=True, loglevel=0) return # # show just Quantarhei version number # if args.version: qr.printlog("Quantarhei package version: ", Manager().version, "\n", verbose=True, loglevel=0) return # # run benchmark # if args.benchmark > 0: import time qr.printlog("Running benchmark no. ", args.benchmark, verbose=True, loglevel=1) import quantarhei.benchmarks.bm_001 as bm t1 = time.time() bm.main() t2 = time.time() qr.printlog("... done in", t2 - t1, "sec", verbose=True, loglevel=1) return ########################################################################### # # Running a script # ########################################################################### # # Script name # scr = args.script # # Greeting # qr.printlog("Running Quantarhei (python) script file: ", scr, verbose=True, loglevel=3) # # Setting environment to see shared libraries # if True: # fix to get it work on Python 3.4 and earlier if sys.version_info[1] > 4: # home home = str(Path.home()) else: from os.path import expanduser home = expanduser("~") #home = str(Path.home()) slib_path = os.path.join(home, "lib") from sys import platform as _platform if _platform == "linux" or _platform == "linux2": # linux if not flag_silent: print("Running on platform " + _platform + " (linux)") print("Setting shared libraty path to: " + slib_path) os.environ["LD_LIBRARY_PATH"] = slib_path elif _platform == "darwin": # MAC OS X if not flag_silent: print("Running on platform " + _platform + " (macOS)") print("Setting shared libraty path to: " + slib_path) os.environ["DYLD_LIBRARY_PATH"] = slib_path elif _platform == "win32": # Windows print(_platform + " win32") elif _platform == "win64": # Windows 64-bit print(_platform + " win64") else: print(_platform + " unrecognized") raise Exception("Unrecognized platform") # # Run serial or parallel # if flag_parallel: # # get parallel configuration # cpu_count = 0 try: import multiprocessing cpu_count = multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass prl_exec = "mpirun" prl_n = "-n" if cpu_count != 0: prl_np = cpu_count else: prl_np = 4 if nprocesses != 0: prl_np = nprocesses engine = "qrhei -s " # running MPI with proper parallel configuration prl_cmd = prl_exec + " " + prl_n + " " + str(prl_np) + " " cmd = prl_cmd + engine + scr if not flag_silent: print("System reports", cpu_count, "processors") print("Starting parallel execution with", prl_np, "processes (executing command below)") print(cmd) print("") p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if not flag_silent: print(" --- output below ---") # read and print output for line in iter(p.stdout.readline, b''): #for line in p.stdout.readlines(): ln = line.decode() # line is returned with a \n character at the end # ln = ln[0:len(ln)-2] print(ln, end="", flush=True) retval = p.wait() else: qr.printlog(" --- output below ---", verbose=True, loglevel=0) # running the script within the same interpreter exec(open(scr).read(), globals()) retval = 0 # # Saying good bye # if retval == 0: qr.printlog(" --- output above --- ", verbose=True, loglevel=0) qr.printlog("Finshed sucessfully; exit code: ", retval, verbose=True, loglevel=0) else: qr.printlog("Warning, exit code: ", retval, verbose=True, loglevel=0)
# # Purely electronic model of the Reaction Center # # Calculations of absorption spectra with a realistic lineshape theory # and with effective Gaussian lineshapes # # # # # In[1]: import os import numpy import quantarhei as qr print(qr.Manager().version) import matplotlib.pyplot as plt plt.switch_backend('agg') # In[2]: pre_in = "in" pre_out = "out" # check if pre_out exists and is a directory if not os.path.isdir(pre_out): try: os.makedirs(pre_out, exist_ok=True) except: raise Exception("Output directory name '" + pre_out +
def do_command_run(args): """Runs a script """ m = qr.Manager().log_conf m.verbosity = args.verbosity nprocesses = args.nprocesses flag_parallel = args.parallel flag_silent = args.silent if args.silent: m.verbosity = 0 # # Run benchmark # if args.benchmark > 0: import time qr.printlog("Running benchmark no. ", args.benchmark, verbose=True, loglevel=1) import quantarhei.benchmarks.bm_001 as bm t1 = time.time() bm.main() t2 = time.time() qr.printlog("... done in", t2 - t1, "sec", verbose=True, loglevel=1) return # # Script name # if args.script: scr = args.script[0] # # Greeting # qr.printlog("Running Quantarhei (python) script file: ", scr, verbose=True, loglevel=3) # # Run serial or parallel # if flag_parallel: # # get parallel configuration # cpu_count = 0 try: import multiprocessing cpu_count = multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass prl_exec = "mpirun" prl_n = "-n" if cpu_count != 0: prl_np = cpu_count else: prl_np = 4 if nprocesses != 0: prl_np = nprocesses engine = "qrhei -s " # running MPI with proper parallel configuration prl_cmd = prl_exec + " " + prl_n + " " + str(prl_np) + " " cmd = prl_cmd + engine + scr if not flag_silent: print("System reports", cpu_count, "processors") print("Starting parallel execution with", prl_np, "processes (executing command below)") print(cmd) print("") p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if not flag_silent: print(" --- output below ---") # read and print output for line in iter(p.stdout.readline, b''): #for line in p.stdout.readlines(): ln = line.decode() # line is returned with a \n character at the end # ln = ln[0:len(ln)-2] print(ln, end="", flush=True) retval = p.wait() else: qr.printlog(" --- output below ---", verbose=True, loglevel=0) # running the script within the same interpreter exec(open(scr).read(), globals()) retval = 0 # # Saying good bye # if retval == 0: qr.printlog("", verbose=True, loglevel=0) qr.printlog(" --- output above --- ", verbose=True, loglevel=0) qr.printlog("Finished sucessfully; exit code: ", retval, verbose=True, loglevel=0) else: qr.printlog("Warning, exit code: ", retval, verbose=True, loglevel=0)
# -*- coding: utf-8 -*- #<remove> _show_plots_ = False #</remove> import quantarhei as qr en = [0.0, 1.0] M = qr.Molecule(elenergies=en) H = M.get_Hamiltonian() print(H) print("version = ", qr.Manager().version)
print("######################################################################") print("# #") print("# FT VIBRONIC 2D MAPS of REACTION CENTER #") print("# #") print("# Quantarhei simulation script #") print("# #") print("# This script is a part of the supporting information #") print("# of the following publication: #") print("# #") print("# Policht, V.; ..., (2019) #") print("# #") print("# #") print("######################################################################") print("") print("Simulation started at: " + str(datetime.datetime.now())) print("Quantarhei version: ", qr.Manager().version) print("") print("*** Simulation parameters ***") print("\n# This block can be used as an input file for another calculation") print("\n# Input and output directories") tprint("out_dir", default="out") tprint("model", default=os.path.join("..", "model")) print("\n# Waiting time propagation parameters:") tprint("eUt_mode", default="jit") tprint("restart", default=True) tprint("stop_after_propagation", default=False) tprint("pure_deph", messg="Using pure dephasing?", default=True) tprint("t2_N_steps") tprint("t2_time_step") tprint("t2_sub", default=10) tprint("transfer_times")
# coding: utf-8 # In[1]: import quantarhei as qr import quantarhei.spectroscopy as spec import numpy import time print(qr.Manager().version) import matplotlib.pyplot as plt #get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: # # This is needed in version 0.0.36 for propagation with Lindblad form # qr.Manager().gen_conf.legacy_relaxation = True # In[3]: agg = qr.load("fraction_45_2_vibrations_CT_unbuilt.hdf5") agg2 = qr.load("fraction_45_2_vibrations_CT_unbuilt.hdf5") agg_el = qr.load("fraction_40_4_CT_unbuilt.hdf5") # In[4]: # # Aggregate with vibrational states, Hamiltonian generated up to single exciton states in a Two-particle approximation