def compare_spectral_dens_to_analytical(self, fctype):
    m = Manager()
    i = 0
    sd_data = numpy.zeros((world.sd.axis.data.shape[0], 2))
    wa = world.ta.get_FrequencyAxis()
    with energy_units("int"):
        sd_data[:, 0] = wa.data
        omega = wa.data
    with energy_units(world.e_units):
        lamb = m.convert_energy_2_internal_u(world.reorg)
    ctime = world.ctime

    if fctype == "OverdampedBrownian":
        # Analytical for for the overdamped Brownian spectral density
        sd_data[:, 1] = (2.0 * lamb / ctime) * omega / (omega**2 +
                                                        (1.0 / ctime)**2)
    else:
        raise Exception()

    data = numpy.zeros((world.sd.axis.data.shape[0], 2))
    for t in world.sd.axis.data:
        data[i, 0] = t
        data[i, 1] = numpy.real(world.sd.data[i])
        #data[i,2] = numpy.imag(world.cf.data[i])
        i += 1
    numpy.testing.assert_allclose(sd_data, data, rtol=1.0e-7)
Beispiel #2
0
def compare_rates_analytical(self, rtols):

    print("Comparison of redfield rates with analytical results")
    m = Manager()

    rtol = float(rtols)

    with energy_units(world.r_units):
        J = m.convert_energy_2_internal_u(world.r_coupl)
    with energy_units(world.e_units):
        lamb = m.convert_energy_2_internal_u(world.reorg)
    tauc = world.ctime
    kBT = kB_int * world.temp

    #print(world.temp, lamb, tauc, J)

    K12 = ((lamb * J / 2.0) * (1.0 + 1.0 / numpy.tanh(J / kBT)) /
           ((J**2) * tauc + 1.0 / (4.0 * tauc)))

    print(K12, 1.0 / K12)
    print(world.K12, 1.0 / world.K12)

    print(K12 / world.K12)

    numpy.testing.assert_allclose(K12, world.K12, rtol=rtol)  #,atol=atol)
def compare_rates_analytical(self, rtols):
    
    print("Comparison of redfield rates with analytical results")
    m = Manager()
    
    rtol = float(rtols)

    with energy_units(world.r_units):
        J = m.convert_energy_2_internal_u(world.r_coupl)
    with energy_units(world.e_units):
        lamb = m.convert_energy_2_internal_u(world.reorg) 
    tauc = world.ctime
    kBT = kB_int*world.temp
    
    #print(world.temp, lamb, tauc, J)    
    
    K12 = ((lamb*J/2.0)
            *(1.0 + 1.0/numpy.tanh(J/kBT))/((J**2)*tauc + 1.0/(4.0*tauc)))
    
    print(K12, 1.0/K12)
    print(world.K12, 1.0/world.K12)
    
    print(K12/world.K12)
    
    numpy.testing.assert_allclose(K12, world.K12 ,rtol=rtol) #,atol=atol)    
def compare_spectral_dens_to_analytical(self, fctype):
    m = Manager()
    i = 0
    sd_data = numpy.zeros((world.sd.axis.data.shape[0],2))
    wa = world.ta.get_FrequencyAxis()
    with energy_units("int"):
        sd_data[:,0] = wa.data
        omega = wa.data
    with energy_units(world.e_units):
        lamb = m.convert_energy_2_internal_u(world.reorg)
    ctime = world.ctime
        
    if fctype == "OverdampedBrownian":
        # Analytical for for the overdamped Brownian spectral density
        sd_data[:,1] = (2.0*lamb/ctime)*omega/(omega**2 + (1.0/ctime)**2)
    else:
        raise Exception()
    
    data = numpy.zeros((world.sd.axis.data.shape[0],2))
    for t in world.sd.axis.data:
        data[i,0] = t
        data[i,1] = numpy.real(world.sd.data[i])
        #data[i,2] = numpy.imag(world.cf.data[i])
        i += 1
    diff = numpy.amax(numpy.abs(sd_data[:,1]-data[:,1]))
    maxv = numpy.amax(numpy.abs(sd_data[:,1]))
    print("Difference: ", diff, " on ", maxv)
    numpy.testing.assert_allclose(sd_data,data,rtol=1.0e-3,atol=1.0e-3)
Beispiel #5
0
    def test_that_Manager_is_a_singleton(self):
        """Testing that Manager object is a singleton
        
        
        """
        m = Manager()
        n = Manager()

        if m is not n:
            raise Exception()
Beispiel #6
0
    def test_saving_and_loading_with_loader(self):
        """Testing loading Saveable objects with load(filename) function
        
        
        """
        if legacy:
            from quantarhei.core.saveable import load, read_info
        else:
            from quantarhei.core.parcel import load_parcel, check_parcel
        from quantarhei import Manager

        obj3 = self.obj3

        if legacy:
            with h5py.File("test_file_2", driver="core",
                           backing_store=False) as f:

                obj3.save(f, test=True)

                obj = load(f, test=True)

                info = read_info(f)
        else:
            with tempfile.TemporaryFile() as f:
                obj3.save(f)

                f.seek(0)
                obj = load_parcel(f)

                f.seek(0)
                info = check_parcel(f)

        liple = obj3.liple
        n = len(liple)
        for i in range(n):
            self.assertEqual(obj3.liple[i], obj.liple[i])

        if legacy:
            self.assertEqual(info["version"], Manager().version)
        else:
            self.assertEqual(info["qrversion"], Manager().version)
Beispiel #7
0
    def qntr_action(self, q):

        if q.text() == "Version info":

            def msgbtn(i):
                print("Button pressed is:", i.text())

            try:

                from quantarhei import Manager
                version = Manager().version

                import quantarhei
                path = os.path.dirname(quantarhei.__file__)
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setText("Quantarhei version info")
                msg.setInformativeText("Package version: " + str(version))
                msg.setWindowTitle("Quantarhei version info")
                msg.setDetailedText("""
Quantarhei package
           
  version: %s
  path: %s
           
""" % (version, path))
                msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
                msg.buttonClicked.connect(msgbtn)

                msg.exec_()

            except Exception as e:

                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setText("Cannot import Quantarhei Package")
                msg.setInformativeText(
                    "Problems with importing Quantarhei" +
                    " package.\nCheck PYTHONPATH system variable.\n" +
                    "See details below")
                msg.setWindowTitle("Quantarhei version info")
                msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
                msg.buttonClicked.connect(msgbtn)
                msg.setDetailedText(str(e))
                msg.exec_()
Beispiel #8
0
    def test_saving_and_loading_with_loader(self):
        """Testing loading Saveable objects with load(filename) function
        
        
        """

        from quantarhei.core.saveable import load, read_info
        from quantarhei import Manager

        obj3 = self.obj3

        with h5py.File("test_file_2", driver="core", backing_store=False) as f:

            obj3.save(f, test=True)

            obj = load(f, test=True)

            info = read_info(f)

        liple = obj3.liple
        n = len(liple)
        for i in range(n):
            self.assertEqual(obj3.liple[i], obj.liple[i])
        self.assertEqual(info["version"], Manager().version)
Beispiel #9
0
"""
print("""
***********************************************************      
*
*
*          Lindblad form demo
*
*
***********************************************************
""")

from quantarhei import Manager
#
# FIXME: temporary fix for version 0.0.34
#
Manager().gen_conf.legacy_relaxation = True

#
# PURELY ELECTRONIC Aggregate of two molecules
#
from quantarhei import Molecule

m1 = Molecule([0.0, 1.0])
m2 = Molecule([0.0, 1.1])
m3 = Molecule([0.0, 1.2])

from quantarhei import Aggregate

agg = Aggregate([m1, m2, m3])
agg.build()
Beispiel #10
0
def main():

    parser = argparse.ArgumentParser(description='Quantarhei Package Driver')

    parser.add_argument("script",
                        metavar='script',
                        type=str,
                        help='script file to be processed')
    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")

    args = parser.parse_args()

    nprocesses = args.nprocesses
    flag_parallel = args.parallel
    flag_silent = args.silent

    #
    # show longer info
    #
    if args.info:
        print("")
        print("qrhei: Quantarhei Package Driver")
        print("")
        print("MPI parallelization enabled: ", flag_parallel)
        if not args.version:
            print("Quantarhei package version: ", Manager().version)

    #
    # show just Quantarhei version number
    #
    if args.version:
        print("Quantarhei package version: ", Manager().version)

    ###########################################################################
    #
    # Running a script
    #
    ###########################################################################

    #
    # Script name
    #
    scr = args.script

    #
    # Greeting
    #
    if not flag_silent:
        print("Running Quantarhei (python) script file: ", scr)

    #
    # 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:

        if not flag_silent:
            print(" --- output below ---")
        # running the script within the same interpreter
        exec(open(scr).read(), globals())

        retval = 0

    #
    # Saying good bye
    #
    if retval == 0:
        if not flag_silent:
            print(" --- output above --- ")
            print("Finshed sucessfully; exit code: ", retval)
    else:
        print("Warning, exit code: ", retval)
Beispiel #11
0
from quantarhei import Molecule
from quantarhei import Aggregate
from quantarhei import energy_units
from quantarhei import TimeAxis
from quantarhei import CorrelationFunction

from quantarhei.spectroscopy.twod2 import TwoDSpectrumCalculator
from quantarhei.spectroscopy.twod2 import TwoDSpectrumContainer
from quantarhei.spectroscopy.twod2 import TwoDSpectrum

from aceto.lab_settings import lab_settings

from quantarhei import Manager

print(Manager().version)

t_fstart = time.time()

# Time axis for t1 and t3 times
Nr = 1000
ta = TimeAxis(0.0, Nr, 2.0)

###############################################################################
#
# Define problem
#
###############################################################################

#
# define molecules
    def test_of_multiple_addition(self):
        """(CorrelationFunction) Testing multiple addition of objects """
        
        t = TimeAxis(0.0, 1000, 1.0)
        
        params1 = dict(ftype="OverdampedBrownian",
                       reorg = 30.0,
                       cortime = 100.0,
                       T = 300.0)
        params2 = dict(ftype="OverdampedBrownian",
                       reorg = 40.0,
                       cortime = 100.0,
                       T = 300.0)
        params3 = dict(ftype="OverdampedBrownian",
                       reorg = 15.0,
                       cortime = 200.0,
                       T = 300.0)
        params4 = dict(ftype="OverdampedBrownian",
                       reorg = 10.0,
                       cortime = 50.0,
                       T = 300.0)     
        
        with energy_units("1/cm"):
            f1 = CorrelationFunction(t, params1)
            f2 = CorrelationFunction(t, params2)
            f3 = CorrelationFunction(t, params3)
            f4 = CorrelationFunction(t, params4)
        
        f = f1 + f2 + f3 + f4
        
        sum_data = f1.data + f2.data + f3.data + f4.data
        sum_lamb = f1.lamb + f2.lamb + f3.lamb + f4.lamb
        sum_cutoff = max(f1.cutoff_time, f2.cutoff_time,
                         f3.cutoff_time, f4.cutoff_time)
        sum_temp = f1.temperature        

        self.assertEqual(f.lamb, sum_lamb)
        numpy.testing.assert_allclose(f.data, sum_data)
        self.assertEqual(f.cutoff_time, sum_cutoff)
        self.assertEqual(f.temperature, sum_temp)
        
        #self.assertFalse(f.is_analytical())
        self.assertTrue(f._is_composed)
        self.assertFalse(f._is_empty)    
        
        #
        # Inplace
        #  
        with energy_units("1/cm"):
            f1 = CorrelationFunction(t, params1)
            f2 = CorrelationFunction(t, params2)
            f3 = CorrelationFunction(t, params3)
            f4 = CorrelationFunction(t, params4)
        fs = f1
        
        sum_data = f1.data + f2.data + f3.data + f4.data
        sum_lamb = f1.lamb + f2.lamb + f3.lamb + f4.lamb
        sum_cutoff = max(f1.cutoff_time, f2.cutoff_time,
                         f3.cutoff_time, f4.cutoff_time)
        sum_temp = f3.temperature 
        
        f1 += f2 + f3
        f1 += f4
        
        f = f1
        
        self.assertEqual(f.lamb, sum_lamb)
        numpy.testing.assert_allclose(f.data, sum_data)
        #print(f.cutoff_time, sum_cutoff)
        self.assertEqual(f.cutoff_time, sum_cutoff)
        self.assertEqual(f.temperature, sum_temp)
        
        #self.assertFalse(f.is_analytical())
        self.assertTrue(f._is_composed)
        self.assertFalse(f._is_empty)        

        # test if inplace addition really happend
        self.assertEqual(fs, f1)
        
        #
        # Loops 
        #
        with energy_units("1/cm"):
            f1 = CorrelationFunction(t, params1)
            f2 = CorrelationFunction(t, params1)
        
        f1_data = f1.data.copy()
        for i in range(5):
            f1 += f1
        
        with energy_units("1/cm"):
            self.assertEqual(f1.lamb, 
              32.0*Manager().convert_energy_2_internal_u(params1["reorg"]))
            
        numpy.testing.assert_allclose(f1.data, 32.0*f1_data)
        self.assertEqual(f1.temperature, params1["T"])  
        
        #self.assertFalse(f1.is_analytical())
        self.assertTrue(f1._is_composed)
        self.assertFalse(f1._is_empty)            
        
        with energy_units("1/cm"):
            f1 = CorrelationFunction(t, params1)
            for i in range(5):
                f1 += f2

            self.assertEqual(f1.lamb, 
                6.0*Manager().convert_energy_2_internal_u(params1["reorg"]))
        numpy.testing.assert_allclose(f1.data, 6.0*f1_data)
        self.assertEqual(f1.temperature, params1["T"])  
        
        #self.assertFalse(f1.is_analytical())
        self.assertTrue(f1._is_composed)
        self.assertFalse(f1._is_empty)  
Beispiel #13
0
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)
Beispiel #14
0
    def test_comparison_of_rates(self):
        """Testing that Redfield tensor and rate matrix are compatible
        
        
        """
        tensor = True
        matrix = True

        print("\n")

        dim = self.H1.dim
        KT = numpy.zeros((dim, dim), dtype=numpy.float64)
        KM = numpy.zeros((dim, dim), dtype=numpy.float64)
        KF = numpy.zeros((dim, dim), dtype=numpy.float64)

        if tensor:

            with energy_units("1/cm"):
                m = Manager()
                cutoff = m.convert_energy_2_internal_u(100.0)
            print(cutoff)
            # Time independent combined tensor
            ham = self.H1
            ham.subtract_cutoff_coupling(cutoff)
            ham.protect_basis()
            with eigenbasis_of(ham):
                RT = \
                         RedfieldFoersterRelaxationTensor(ham, self.sbi1,
                                        coupling_cutoff=cutoff)
                #if secular_relaxation:
                #    relaxT.secularize()
            ham.unprotect_basis()
            #ham.recover_cutoff_coupling()

            #print(self.H1)

            with energy_units("1/cm"):
                print(ham)

            with eigenbasis_of(ham):
                #if True:
                for n in range(2):
                    for m in range(2):
                        #print(n,m,numpy.real(RT.data[n,n,m,m]))
                        KT[n, m] = numpy.real(RT.data[n, n, m, m])

        if matrix:
            #print(self.H2)
            RR = RedfieldRateMatrix(self.H2, self.sbi2)

            for n in range(2):
                for m in range(2):
                    #print(n,m,numpy.real(RR.data[n,m]))
                    KM[n, m] = numpy.real(RR.data[n, m])

            RR = FoersterRateMatrix(self.H2, self.sbi2)

            for n in range(2):
                for m in range(2):
                    #print(n,m,numpy.real(RR.data[n,m]))
                    KF[n, m] = numpy.real(RR.data[n, m])

        #print(self.c_omega_p)
        #print(self.c_omega_m)
        #KM = KT
        print("Combined rate matrix:")
        print(1.0 / KT)
        print("Redfield rate matrix (eigenbasis)")
        print(1.0 / KM)
        print("Foerster rate matrix (site basis): ")
        print(1.0 / KF)
        KT = KM

        numpy.testing.assert_allclose(KT, KM, rtol=1.0e-2)