Example #1
0
 def check_value_scalar(self, string, should_be, significance=8, debug=False):
     import pyalps
     val=pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y[0].mean
     err=pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y[0].error
     if debug:
         print('\n')
         print(string+': '+str(val)+' +- '+str(err)+'\t'+str(abs(should_be-val)/max([err,1e-6])))
         print('\n')
     self.assertLess(abs(should_be-val)/max([err,1e-6]),significance)
Example #2
0
def clean(args):
    resfiles = pyalps.getResultFiles(prefix = args.infile)
    for resf in resfiles:
        os.remove(resf)
    infiles = [f for f in os.listdir(os.getcwd()) if re.match('{}.*in.*'.format(args.infile), f)]
    for inf in infiles:
        os.remove(inf)
Example #3
0
def run_dmrg(nsite, J2):
    #prepare the input parameters
    parms = [{
        'LATTICE_LIBRARY': 'j1j2_%d.xml' % nsite,
        'LATTICE': 'J1J2',
        'MODEL': 'spin',
        'local_S0': '0.5',  # local_S0 means type 0 site, right?
        'CONSERVED_QUANTUMNUMBERS': 'N,Sz',
        'Sz_total': 0,
        'J0': 1,
        'J1': J2,
        'SWEEPS': 4,
        'NUMBER_EIGENVALUES': 1,
        'MAXSTATES': 400
    }]

    #write the input file and run the simulation
    prefix = 'data/j1j2_%dJ2%s' % (nsite, J2)
    input_file = pyalps.writeInputFiles(prefix, parms)
    res = pyalps.runApplication('dmrg', input_file, writexml=True)

    #load all measurements for all states
    data = pyalps.loadEigenstateMeasurements(
        pyalps.getResultFiles(prefix=prefix))

    # print properties of the eigenvector for each run:
    for run in data:
        for s in run:
            print('%s : %s' % (s.props['observable'], s.y[0]))
def read_results_from_file(path, prefix, X, Y, ForEach=None):
    """
    Input
    ------------------
    path:  path to result files
    prefix: prefix filenames (ending out.h5), if ending with a dot (.), only one simulation is assumed
                            else the separate simulation are identified and merged.
    X : string, name of parameter
    Y : string, name of observable

    returns
    -----------------
    pyalps X-Y-props list
    """

    if prefix[-1]=='.':
        dataset= pyalps.loadMeasurements(pyalps.getResultFiles(dirname=path,prefix=prefix),Y)

        if ForEach==None:
            return pyalps.collectXY(dataset, x=X, y=Y)
        else:
            return pyalps.collectXY(dataset, x=X, y=Y, foreach=[ForEach])

    else:
        raise ValueError("Not yet implemented for multiple runs.")
def ReadResults(path, prefix, X, Y):
    """
    Input
    ------------------
    path:  path to result files
    prefix: prefix filenames (ending out.h5), if ending with a dot (.), only one simulation is assumed
                            else the separate simulation are identified and merged.
    X : string, name of parameter
    Y : string, name of observable

    returns
    -----------------
    pyalps X-Y-props list
    """

    if prefix[-1]=='.':
        dataset= pyalps.loadMeasurements(pyalps.getResultFiles(dirname=path,prefix=filename),args.Y)

        return pyalps.collectXY(dataset, x=X, y=Y, foreach=['IncNo'])
    else:
        all_prefixes=[]
        for f in os.listdir(path):
            if fnmatch.fnmatch(f, prefix+'*.out.h5'):
                before_first_dot=f.split('.')[0]+'.'
                if before_first_dot not in all_prefixes:
                    all_prefixes.append(before_first_dot)
        datasetsXY = []
        for pre in all_prefixes:
            tmp_dset= pyalps.loadMeasurements(pyalps.getResultFiles(dirname=path,prefix=pre),args.Y)
            datasetsXY.append( pyalps.collectXY(tmp_dset, x=X, y=Y, foreach=['IncNo']) )

        for i,dxy in enumerate(datasetsXY[0]):   #Take the 1st dataset as reference
            rIncNo = dxy.props['IncNo']
            for dslist in datasetsXY[1:]:
                for dxy2nd in dslist:
                    if rIncNo == dxy2nd.props['IncNo']:
                        datasetsXY[0][i] = pyalps.mergeDataSets([datasetsXY[0][i], dxy2nd])   

        return datasetsXY[0]
Example #6
0
def analyze(args):
    print 'running analysis'
    runs = pyalps.getResultFiles(prefix = args.infile)

    chi_data = get_chi(runs)
    T = chi_data['T']
    chi = [c.mean for c in chi_data['chi']]
    chi_err = [c.error for c in chi_data['chi']]

    plt.figure()
    plt.errorbar(T, chi, yerr = chi_err)
    yl = plt.ylim()
    plt.vlines(1. / 0.693035, yl[0], yl[1])
    plt.ylim(yl)
    xl =(min(T), max(T))
    plt.xlim(xl)
    plt.xlabel(r'Temperature $T$')
    plt.ylabel(r'Magnetic Susceptibility $\chi$')
    plt.savefig('{}.plot_chi.pdf'.format(args.infile))

    idx = [1, len(runs)/3, -2]
    T = np.array([p['T'] for p in pyalps.loadProperties(runs)])
    runsorted = np.array(zip(T, runs), dtype=[('T', 'f8'), ('run', object)])
    runsorted.sort(order = 'T')
    corr_data, T = get_corr([runsorted[i]['run'] for i in idx])

    plt.figure()
    for i in range(len(corr_data)):
        temp = T[i]
        corr = corr_data[i]
        x = corr['dist']
        y = [i.mean for i in corr['corr']]
        ye = [i.error for i in corr['corr']]
        plt.errorbar(x, y, yerr = ye, label = 'T = {}'.format(temp))
    plt.ylim((-0.01, 1.01))
    plt.xlabel(r'Distance $r$ in Lattice Units')
    plt.ylabel(r'Pair Correlation Function $g(r)$')
    plt.legend()
    plt.savefig('{}.plot_corr.pdf'.format(args.infile))
Example #7
0
parms = []
parms.append( { 
    'LATTICE'                               : "open ladder",
    'L'                                     : 10,
    'MODEL_LIBRARY'                         : "mymodels.xml",
    'MODEL'                                 : "fermion Hubbard",
    'CONSERVED_QUANTUMNUMBERS'              : 'Nup,Ndown',
    'Nup_total'                             : 10,
    'Ndown_total'                           : 10,
    't0'                                    : "1+0.6*I",
    'ct0'                                   : "1-0.6*I",
    't1'                                    : 0.1,
    'U'                                     : 0.,
    'SWEEPS'                                : 6,
    'MAXSTATES'                             : 400,
    'COMPLEX'                               : 1,
   } )

#write the input file and run the simulation
input_file = pyalps.writeInputFiles(basename,parms)
res = pyalps.runApplication('mps_optim',input_file,writexml=True)

#load all measurements for all states
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename), ['Energy'])

en_exact = -28.1129977
print('Exact energy for MAXSTATES=inf ::', en_exact)
for d in pyalps.flatten(data):
    print(d.props['observable'], '=', d.y)

def main():
    Ws = np.linspace(7.9e10, 1.1e12, 17)#[1e11]#[7.9e10]#np.linspace(2e11,3.2e11,10)#[2e10]
    nW = len(Ws)
    # Ns = [L]#range(0,2*L+1)#range(30,86)#[L]#range(0,2*L+1)#range(40,70)#range(0,2*L+1)#range(24,2*L+1)#range(0,2*L+1)#range(23,27)
    # nN = len(Ns)
    sigmas = [0,2,5,10]#range(0, 11)
    nsigma = len(sigmas)
    Wsigmas = zip(range(nW*nsigma), [[i, j] for i in range(nW) for j in range(nsigma)], [[Wi, sigmai] for Wi in Ws for sigmai in sigmas])
    ntasks = len(Wsigmas)

    start = datetime.datetime.now()

    pbar = progressbar.ProgressBar(widgets=['Res: '+str(resi)+' ', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer()], maxval=ntasks).start()

    with concurrent.futures.ProcessPoolExecutor(max_workers=numthreads) as executor:
        futures = [executor.submit(runmps, task, iW, isigma, Wi, sigma) for (task, [iW, isigma], [Wi, sigma]) in Wsigmas]
        for future in pbar(concurrent.futures.as_completed(futures)):
            future.result()
            sys.stderr.flush()

    end = datetime.datetime.now()

    #load all measurements for all states
    data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename))

    Es = makeres(nW, nsigma)
    ns = makeres(nW, nsigma)
    n2s = makeres(nW, nsigma)
    corrs = makeres(nW, nsigma)
    ncorrs = makeres(nW, nsigma)
    entropy = makeres(nW, nsigma)
    es = makeres(nW, nsigma)
    for d in data:
        for sigma in d:
            iW = int(sigma.props['iW'])
            isigma = int(sigma.props['is'])
            if(sigma.props['observable'] == 'Energy'):
                Es[iW][isigma] = sigma.y[0]
            if(sigma.props['observable'] == 'Local density'):
                ns[iW][isigma] = sigma.y[0]
            if(sigma.props['observable'] == 'Local density squared'):
                n2s[iW][isigma] = sigma.y[0]
            if(sigma.props['observable'] == 'One body density matrix'):
                corrs[iW][isigma] = sparse.coo_matrix((sigma.y[0], (sigma.x[:,0], sigma.x[:,1]))).toarray()
            if(sigma.props['observable'] == 'Density density'):
                ncorrs[iW][isigma] = sparse.coo_matrix((sigma.y[0], (sigma.x[:,0], sigma.x[:,1]))).toarray()
            if(sigma.props['observable'] == 'Entropy'):
                entropy[iW][isigma] = sigma.y[0]
            if(sigma.props['observable'] == 'Entanglement Spectra'):
                es[iW][isigma] = [[sigma for sigma in reversed(sorted(esi[1]))][0:4] for esi in sigma.y[0]]

    resultsfile = open(resdir + resifile(resi), 'w')
    resultsstr = ''
    resultsstr += 'seed['+str(resi)+']='+str(seed)+';\n'
    resultsstr += 'L['+str(resi)+']='+str(L)+';\n'
    resultsstr += 'nmax['+str(resi)+']='+str(nmax)+';\n'
    resultsstr += 'sweeps['+str(resi)+']='+str(sweeps)+';\n'
    resultsstr += 'maxstates['+str(resi)+']='+str(maxstates)+';\n'
    resultsstr += 'Ws['+str(resi)+']='+mathematica(Ws)+';\n'
    resultsstr += 'ts['+str(resi)+']='+mathematica([JWi(Wi) for Wi in Ws])+';\n'
    resultsstr += 'Us['+str(resi)+']='+mathematica([UW(Wi) for Wi in Ws])+';\n'
    resultsstr += 'sigmas['+str(resi)+']='+mathematica(sigmas)+';\n'
    resultsstr += 'Eres['+str(resi)+']='+mathematica(Es)+';\n'
    resultsstr += 'nres['+str(resi)+']='+mathematica(ns)+';\n'
    resultsstr += 'n2res['+str(resi)+']='+mathematica(n2s)+';\n'
    resultsstr += 'corrres['+str(resi)+']='+mathematica(corrs)+';\n'
    resultsstr += 'ncorrres['+str(resi)+']='+mathematica(ncorrs)+';\n'
    resultsstr += 'entropy['+str(resi)+']='+mathematica(entropy)+';\n'
    resultsstr += 'es['+str(resi)+']='+mathematica(es)+';\n'
    resultsstr += 'runtime['+str(resi)+']="'+str(end-start)+'";\n'
    resultsfile.write(resultsstr)
Example #9
0
def runTest(testinputfile, outputs='auto', compMethod='auto', pyexec='auto'):
    """ Run the test according to testinputfile and compare
        its output against reference files

    inputs are:
    -----------
    script: a script to be run

    testinputfile: file containing reference info

    outputs: - default is 'auto' -> assume file names are identical with reference files
           list of script outputs
         - glob pattern
         - explicit list of files ( order has to be the same as in the .testin.xml file )

    compMethod: - default is 'auto' -> try to detect comparison Method
              to be used (e.g. Monte Carlo or epsilon precise data)
    """
    tstart = strftime("%Y-%b-%d %H:%M:%S", gmtime())
    testinputfile = os.path.expandvars(testinputfile)
    props, inputs, refFileList, whatlist = read_testprop_xml(testinputfile)
    script = props['SCRIPT']

    tmpdir = tempfile.mkdtemp()

    # execute given script in tmpdir
    pardir = os.getcwd()
    shutil.copy(script, tmpdir)
    if inputs is not None:
        for f in inputs:
            shutil.copy(f, tmpdir)

    # get python executable
    if pyexec == 'auto':
        pyexec = sys.executable

    os.chdir(tmpdir)
    cmdline = [pyexec, os.path.basename(script)]
    pyalps.executeCommand(cmdline)
    if inputs is not None:
        for f in inputs:
            os.remove(f)

    os.chdir(pardir)

    # copy stylesheet
    pyalps.tools.copyStylesheet(pardir)

    # Guess outputs from reference files
    if outputs == 'auto':
        outputs = [
            os.path.join(tmpdir, os.path.basename(x)) for x in refFileList
        ]

    elif type(outputs) == str:
        print("Using glob '%s' to find outputs" % outputs)
        outputs = pyalps.getResultFiles( pattern=os.path.basename(outputs), \
            dirname=os.path.dirname(outputs) )

    if not outputs:
        print("\nList of output files of %s is empty\n" % script)
        test_success = False

    else:
        missing = [x for x in outputs if not os.path.exists(x)]
        if missing:
            for f in missing:
                print("Output file '%s' does not exist" % f)
            test_success = False
        else:
            # Start test
            test_success = compareTest(testinputfile,
                                       outputs,
                                       tmpdir,
                                       tstart,
                                       compMethod=compMethod)

    # if something goes wrong above, tmpdir will not be removed
    # for the moment this is useful, later maybe use try/except
    shutil.rmtree(tmpdir)
    return test_success
Example #10
0
import numpy as np

#prepare the input parameters
parms = [{
    'LATTICE': "ladder",
    'MODEL': "spin",
    'CONSERVED_QUANTUMNUMBERS': 'Sz',
    'local_S': 0.5,
    'J0': 1,
    'J1': 1,
    'L': 6
}]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('ed06b', parms)
res = pyalps.runApplication('fulldiag', input_file)

#run the evaluation and load all the plots
data = pyalps.evaluateFulldiagVersusT(pyalps.getResultFiles(prefix='ed06b'),
                                      DELTA_T=0.05,
                                      T_MIN=0.05,
                                      T_MAX=5.0)

#make plot
for s in pyalps.flatten(data):
    plt.figure()
    plt.title("Antiferromagnetic Heisenberg ladder")
    pyalps.plot.plot(s)

plt.show()
Example #11
0
File: binning.py Project: DropD/CQP
# Plot binning analysis from all runs of the C++ program pimc in the current directory.

import numpy as np
import matplotlib.pyplot as plt
import pyalps
import pyalps.plot
import pyalps.load

runfiles = pyalps.getResultFiles(prefix='*.run')

loader = pyalps.load.Hdf5Loader()
ebinning = pyalps.flatten(loader.ReadBinningAnalysis(runfiles,measurements=['Energy'],respath='/simulation/realizations/0/clones/0/results'))
tbinning = pyalps.flatten(loader.ReadBinningAnalysis(runfiles,measurements=['KineticEnergy'],respath='/simulation/realizations/0/clones/0/results'))
vbinning = pyalps.flatten(loader.ReadBinningAnalysis(runfiles,measurements=['PotentialEnergy'],respath='/simulation/realizations/0/clones/0/results'))

for o in (ebinning,tbinning,vbinning):
    for d in o:
        d.props['label'] = str(d.props['SWEEPS'])+' sweeps'
    plt.figure()
    plt.title(o[0].props['observable'])
    plt.xlabel('binning level')
    plt.ylabel('error estimate')
    pyalps.plot.plot(o)
    plt.legend()

plt.show()
Example #12
0
    'hz': hz,
    'cg': cg,
    'sg': sg,
    'SWEEPS': sweeps,
    'NUM_WARMUP_STATES': warmup_states,
    'NUMBER_EIGENVALUES': 1,
    'MAXSTATES': max_states,
    'MEASURE_LOCAL[nUP]': 'nUP',
    'MEASURE_LOCAL[nDO]': 'nDO',
    'MEASURE_CORRELATIONS[One-body Correlation UP]': "bdagUP:bUP",
    'MEASURE_CORRELATIONS[One-body Correlation DO]': "bdagDO:bDO",
    'MEASURE_CORRELATIONS[One-body Correlation UPDO]': "bdagUP:bDO",
    'MEASURE_CORRELATIONS[Two-body Correlation UP]': "nUP:nUP",
    'MEASURE_CORRELATIONS[Two-body Correlation DO]': "nDO:nDO",
    'MEASURE_CORRELATIONS[Two-body Correlation UPDO]': "nUP:nDO"
}]

#Write the input file and run the simulation
input_file = pyalps.writeInputFiles(filename, parms)
res = pyalps.runApplication('dmrg', input_file, writexml=False, MPI=None)

#Load measurements for the ground state
data = pyalps.loadEigenstateMeasurements(
    pyalps.getResultFiles(prefix=filename))

#Print the properties of the ground state
if __name__ == '__main__':

    for s in data[0]:
        print s.props['observable'], ' : ', s.y[0]
    parms['t'+str(i)+'[Time]'] = ','.join([mathematica(JW(W)[i]) for W in quench(W_i, W_f, xi, tf, dt)])
for i in range(L):
    parms['U'+str(i)+'[Time]'] = ','.join([mathematica(UW(W)[i]) for W in quench(W_i, W_f, xi, tf, dt)])
parmslist = [parms]

# print mathematica([JW(W)[0] for W in quench(W_i, W_f, xi, tf, dt)])
# print mathematica([UW(W)[0] for W in quench(W_i, W_f, xi, tf, dt)])
# quit()

input_file = pyalps.writeInputFiles(basename+'.dynamic',parmslist)
res = pyalps.runApplication('mps_evolve',input_file,writexml=True)

end = datetime.datetime.now()

## simulation results
data = pyalps.loadIterationMeasurements(pyalps.getResultFiles(prefix=basename+'.dynamic'), what=['Energy', 'Local density', 'Local density squared', 'One body density matrix', 'Density density'])

coords = []
for d1 in data:
    for s1 in d1:
        for d in s1:
            for s in d:
                if(s.props['observable'] == 'One body density matrix'):
                    coords = (s.x[:,0], s.x[:,1])

XY = pyalps.collectXY(data, x='Time', y='Energy', foreach=['tau'])
E = [[[(x + 1)*dt, y] for (x, y) in zip(xy.x, xy.y)] for xy in XY][0]

XY = pyalps.collectXY(data, x='Time', y='Local density', foreach=['tau'])
n = [[[(x + 1)*dt, y] for (x, y) in zip(xy.x, xy.y)] for xy in XY][0]
Example #14
0
try:
  os.mkdir(os.path.join(temp, timestamp))
except:
  pass

input_file = pyalps.writeInputFiles(os.path.join(os.getcwd(), temp, timestamp), parms)

#run the simulation

res = pyalps.runApplication('fulldiag',input_file, writexml=True)

print res
#load all measurements for all states
# data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix='parm1a'))
result_name = 'nx{nx}_ny{ny}_J{J}_J1{J1}_f{f}'.format(nx=Nx, ny=Ny, J=J, f=dilution, J1=J1)
data = pyalps.evaluateFulldiagVersusT(pyalps.getResultFiles(prefix=str(timestamp)),DELTA_T=args.Ts, T_MIN=args.Ti, T_MAX=args.Tf)

# print 'data = ', data

d_xml = data2xml.DataToXML(data=data, ed=True)
results = 'results'

try:
  os.mkdir(results)
except:
  pass

file_name = os.path.join(results, lattice_name + "Ti{Ti}_Tf{Tf}_Ts{Ts}_Nx_{Nx}_Ny_{Ny}_J_{J}_J1_{J1}.xml".format(Ti=Ti, Ts=Ts, Tf=Tf, Nx=Nx, Ny=Ny, J=J, J1=J1))
d_xml.tofile(file_name)
Example #15
0
      'THERMALIZATION': 5000,
      'SWEEPS'         : 50000,
      'ALGORITHM'      : "loop",
      # 'MEASURE[Winding Number]': 1,
      # 'MEASURE_CORRELATIONS[Diagonal spin correlations]':"Sz",
    }
)


#write the input file and run the simulation

input_file = pyalps.writeInputFiles(os.path.join(os.getcwd(), temp, timestamp, lattice_name), parms)

pyalps.runApplication('loop', input_file, writexml=True)

data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix=lattice_name))

results = 'results'

try:
  os.mkdir(results)
except:
  pass

file_name = os.path.join(results, lattice_name + "_beta_{beta}_Nx_{Nx}_Ny_{Ny}_J_{J}_J1_{J1}.xml".format(beta=beta,
                                                                                                         Nx=Nx,
                                                                                                         Ny=Ny,
                                                                                                         J=J,
                                                                                                         J1=J1))

d_xml = data2xml.DataToXML(data=data, looper=True, lattice=LATTICE_LIBRARY)
Example #16
0
resi = 1000
try:
    shutil.rmtree('SingleSite')
    os.mkdir('SingleSite')
except:
    pass

basename = 'SingleSite/ss.'

parms['N_total'] = 14
# parms['initial_local_N'] = '3,2,2,2,2,2,2,2,2,2'#'1,1,1,1,1,1,1,1,0,0'#'2,2,1,1,1,1,1,1,1,1'
input_file = pyalps.writeInputFiles(basename + str(resi), [parms])
pyalps.runApplication('mps_optim', input_file, writexml=True)

#load all measurements for all states
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename))

for d in data:
    for s in d:
        if(s.props['observable'] == 'Energy'):
            print s.y[0]
        if(s.props['observable'] == 'Local density'):
            print s.y[0]

iters = pyalps.loadIterationMeasurements(pyalps.getResultFiles(prefix=basename), what=['Energy'])
# print iters
en_vs_iter = pyalps.collectXY(iters, x='iteration', y='Energy')
# print en_vs_iter
Es = np.array([Ei for (i, Ei) in sorted(zip([int(xi) for xi in en_vs_iter[0].x[0:-1:20]], en_vs_iter[0].y[0:-1:20]))[-40:-1]])
Es2 = Es[1:-1] - Es[0:-2]
print Es2
                    if rIncNo == dxy2nd.props['IncNo']:
                        datasetsXY[0][i] = pyalps.mergeDataSets([datasetsXY[0][i], dxy2nd])   

        return datasetsXY[0]

        


path=os.path.dirname(args.infile)
filename=os.path.basename(args.infile)
if args.verbose:
    print path, filename

if args.verbose:
    print args.X, args.Y
    print pyalps.getResultFiles(prefix=args.infile)
    #print dataset

renyi_dataG = ReadResults(path, filename, args.X, args.Y)
n=args.N


if args.verbose:
    print renyi_dataG

if args.outfile!=None:
    outfile=open(args.outfile,'w')


factor={}
factor['ising2D']=2
Example #18
0
import pyalps

fileheader = 'heisenberg'
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=fileheader),'Energy')

#print data,len(data)

J_En = pyalps.collectXY(data, x='J', y='Energy')
print data 

for x, y in zip(J_En[0].x, J_En[0].y):
    print x, y 
Example #19
0
# DEALINGS IN THE SOFTWARE.
# 
# ****************************************************************************

import pyalps
import numpy as np
import matplotlib.pyplot as plt
import pyalps.plot


## Please run the tutorial5a.py before this one

listobs = ['0', '2']   # we look at convergence of a single flavor (=0) 

## load all results
data = pyalps.loadDMFTIterations(pyalps.getResultFiles(pattern='parm_u_*.h5'), measurements=listobs, verbose=True)

## create a figure for each BETA
grouped = pyalps.groupSets(pyalps.flatten(data), ['U', 'observable'])
for sim in grouped:
    common_props = pyalps.dict_intersect([ d.props for d in sim ])
    
    ## rescale x-axis and set label
    for d in sim:
        d.x = d.x * d.props['BETA']/float(d.props['N'])
        d.y *= -1.
        d.props['label'] = 'it'+d.props['iteration']
    
    ## plot all iterations for this BETA
    plt.figure()
    plt.xlabel(r'$\tau$')
Example #20
0
 def check_data_length(self,string,should_be, output=False):
     import pyalps
     l=len(pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y)
     self.assertEqual(l,should_be)
Example #21
0
          'TAUS' : [20.0],
          'POWS' : [0.0],
          'GS' : ['H'],
          'GIS' : [0.0],
          'GFS' : [0.0],
          'NUMSTEPS' : [500],
          'STEPSFORSTORE' : [5],
          'SIMID': count
            })

baseName='tutorial_2d'
nmlnameList=pyalps.writeTEBDfiles(parms, baseName)
res=pyalps.runTEBD(nmlnameList)

#Get magnetization data
Magdata=pyalps.load.loadTimeEvolution( pyalps.getResultFiles(prefix='tutorial_2d'), measurements=['Local Magnetization'])

#Compute the integrated magnetization across the center
for q in Magdata:
    syssize=q[0].props['L']
    #Compute the integrated flow of magnetization through the center \Delta M=\sum_{n>L/2}^{L} (<S_n^z(t)>+1/2)
    #\Delta M= L/4
    loc=0.5*(syssize/2)
    #\Delta M-=<S_n^z(t)> from n=L/2 to L
    q[0].y=[0.5*(syssize/2)+sum(q[0].y[syssize/2:syssize])]


#Plot the integrated magnetization
Mag=pyalps.collectXY(Magdata, x='Time', y='Local Magnetization', foreach=['Jz'])

plt.figure()
Example #22
0
 def check_has_observable(self,string, output=False):
     import pyalps
     self.assertGreater(len(pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0]), 0)
def main():
    Ws = np.linspace(2e11,3.2e11,10)#[2e10]
    nW = len(Ws)
    Ns = range(0,2*L+1)#range(23,27)
    nN = len(Ns)
    WNs = zip(range(nW*nN), [[i, j] for i in range(nW) for j in range(nN)], [[Wi, Ni] for Wi in Ws for Ni in Ns])
    ntasks = len(WNs)

    start = datetime.datetime.now()

    pbar = progressbar.ProgressBar(widgets=['Res: '+str(resi)+' ', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer()], maxval=ntasks).start()

    with concurrent.futures.ProcessPoolExecutor(max_workers=numthreads) as executor:
        futures = [executor.submit(runmps, task, iW, iN, Wi, N) for (task, [iW, iN], [Wi, N]) in WNs]
        for future in pbar(concurrent.futures.as_completed(futures)):
            future.result()

    end = datetime.datetime.now()

    #load all measurements for all states
    data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename))

    solved = makeres(nW, nN)
    Es = makeres(nW, nN)
    ns = makeres(nW, nN)
    n2s = makeres(nW, nN)
    corrs = makeres(nW, nN)
    ncorrs = makeres(nW, nN)
    for d in data:
        for s in d:
            iW = int(s.props['iW'])
            iN = int(s.props['iN'])
            solved[iW][iN] = s.props['solved']
            if(s.props['observable'] == 'Energy'):
                Es[iW][iN] = s.y[0]
            if(s.props['observable'] == 'Local density'):
                ns[iW][iN] = s.y[0]
            if(s.props['observable'] == 'Local density squared'):
                n2s[iW][iN] = s.y[0]
            if(s.props['observable'] == 'One body density matrix'):
                corrs[iW][iN] = sparse.coo_matrix((s.y[0], (s.x[:,0], s.x[:,1]))).toarray()
            if(s.props['observable'] == 'Density density'):
                ncorrs[iW][iN] = sparse.coo_matrix((s.y[0], (s.x[:,0], s.x[:,1]))).toarray()

    resultsfile = open(resdir + resifile(resi), 'w')
    resultsstr = ''
    resultsstr += 'seed['+str(resi)+']='+str(seed)+';\n'
    resultsstr += 'L['+str(resi)+']='+str(L)+';\n'
    resultsstr += 'nmax['+str(resi)+']='+str(nmax)+';\n'
    resultsstr += 'sweeps['+str(resi)+']='+str(sweeps)+';\n'
    resultsstr += 'maxstates['+str(resi)+']='+str(maxstates)+';\n'
    resultsstr += 'periodic['+str(resi)+']='+str(periodic)+';\n'
    resultsstr += 'twisted['+str(resi)+']='+str(twist)+';\n'
    resultsstr += 'xi['+str(resi)+']='+mathematica(xi)+';\n'
    resultsstr += 'Ws['+str(resi)+']='+mathematica(Ws)+';\n'
    resultsstr += 'ts['+str(resi)+']='+mathematica([JWi(Wi) for Wi in Ws])+';\n'
    resultsstr += 'Us['+str(resi)+']='+mathematica([UW(Wi) for Wi in Ws])+';\n'
    resultsstr += 'Ns['+str(resi)+']='+mathematica(Ns)+';\n'
    resultsstr += 'solved['+str(resi)+']='+mathematica(solved)+';\n'
    resultsstr += 'Eres['+str(resi)+']='+mathematica(Es)+';\n'
    resultsstr += 'nres['+str(resi)+']='+mathematica(ns)+';\n'
    resultsstr += 'n2res['+str(resi)+']='+mathematica(n2s)+';\n'
    resultsstr += 'corrres['+str(resi)+']='+mathematica(corrs)+';\n'
    resultsstr += 'ncorrres['+str(resi)+']='+mathematica(ncorrs)+';\n'
    resultsstr += 'runtime['+str(resi)+']="'+str(end-start)+'";\n'
    resultsfile.write(resultsstr)
Example #24
0
def main():
    ts = [0.01]#[0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01]#[1e-10,1e-9,1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2,1e-1]#[0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01]#[0.01,0.1]#np.linspace(0.01, 0.05, 5).tolist()
    nt = len(ts)
    Us = [1]*nt
    Ns = range(0, 2*L+1)#range(23,27)#range(25,2*L+1)#[35,36,37]#[32]*12#range(32,40)#range(38, 46)#[40,41,42,43]#range(25, 2*L+1)#range(51,70)#[66,66,66,66,66,66,66,66,66]#[66,67,68]#[66,67,68,69,70]#range(0, 2*L+1)
    nN = len(Ns)
    tUNs = zip(range(nt*nN), [[i, j] for i in range(nt) for j in range(nN)], [[Ui, ti, Ni] for (Ui, ti) in zip(Us, ts) for Ni in Ns])
    ntasks = len(tUNs)

    start = datetime.datetime.now()

    pbar = progressbar.ProgressBar(widgets=[progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer()], maxval=ntasks).start()

    # with concurrent.futures.ThreadPoolExecutor(max_workers=numthreads) as executor:
    with concurrent.futures.ProcessPoolExecutor(max_workers=numthreads) as executor:
        futures = [executor.submit(runmps, task, it, iN, Ui, ti, N) for (task, [it, iN], [Ui, ti, N]) in tUNs]
        for future in pbar(concurrent.futures.as_completed(futures)):
            future.result()

    end = datetime.datetime.now()

    #load all measurements for all states
    data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename))

    solved = makeres(nt, nN)
    Es = makeres(nt, nN)
    ns = makeres(nt, nN)
    n2s = makeres(nt, nN)
    corrs = makeres(nt, nN)
    ncorrs = makeres(nt, nN)
    for d in data:
        for s in d:
            it = int(s.props['it'])
            iN = int(s.props['iN'])
            solved[it][iN] = s.props['solved']
            if(s.props['observable'] == 'Energy'):
                Es[it][iN] = s.y[0]
            if(s.props['observable'] == 'Local density'):
                ns[it][iN] = s.y[0]
            if(s.props['observable'] == 'Local density squared'):
                n2s[it][iN] = s.y[0]
            if(s.props['observable'] == 'One body density matrix'):
                corrs[it][iN] = sparse.coo_matrix((s.y[0], (s.x[:,0], s.x[:,1]))).toarray()
            if(s.props['observable'] == 'Density density'):
                ncorrs[it][iN] = sparse.coo_matrix((s.y[0], (s.x[:,0], s.x[:,1]))).toarray()

    resultsfile = open(resdir + 'res.'+str(resi)+'.txt', 'w')
    resultsstr = ''
    resultsstr += 'seed['+str(resi)+']='+str(seed)+';\n'
    resultsstr += 'L['+str(resi)+']='+str(L)+';\n'
    resultsstr += 'nmax['+str(resi)+']='+str(nmax)+';\n'
    resultsstr += 'sweeps['+str(resi)+']='+str(sweeps)+';\n'
    resultsstr += 'maxstates['+str(resi)+']='+str(maxstates)+';\n'
    resultsstr += 'periodic['+str(resi)+']='+str(periodic)+';\n'
    resultsstr += 'twisted['+str(resi)+']='+str(twist)+';\n'
    resultsstr += 'xi['+str(resi)+']='+mathematica(xi)+';\n'
    resultsstr += 'ts['+str(resi)+']='+mathematica(ts)+';\n'
    resultsstr += 'Us['+str(resi)+']='+mathematica(Us)+';\n'
    resultsstr += 'Ns['+str(resi)+']='+mathematica(Ns)+';\n'
    resultsstr += 'solved['+str(resi)+']='+mathematica(solved)+';\n'
    resultsstr += 'Eres['+str(resi)+']='+mathematica(Es)+';\n'
    resultsstr += 'nres['+str(resi)+']='+mathematica(ns)+';\n'
    resultsstr += 'n2res['+str(resi)+']='+mathematica(n2s)+';\n'
    resultsstr += 'corrres['+str(resi)+']='+mathematica(corrs)+';\n'
    resultsstr += 'ncorrres['+str(resi)+']='+mathematica(ncorrs)+';\n'
    resultsstr += 'runtime['+str(resi)+']="'+str(end-start)+'";\n'
    resultsfile.write(resultsstr)

    print 'Res: ' + str(resi)
Example #25
0
    p['TIMESTEPS'] = nsteps
    p['tau'] = tau  # not used in the simulation, but useful in the evaluation below
    p['Jz'] = z
    p['ALWAYS_MEASURE'] = 'Local Magnetization'
    p['chkp_each'] = nsteps
    p['measure_each'] = 5
    p['COMPLEX'] = 1

    parms.append(p)

## write input files and run application
input_file = pyalps.writeInputFiles(basename, parms)
res = pyalps.runApplication('mps_evolve', input_file)

## simulation results
data = pyalps.loadIterationMeasurements(pyalps.getResultFiles(prefix=basename),
                                        what=['Local Magnetization'])

for q in pyalps.flatten(data):
    L = q.props['L']
    #Compute the integrated flow of magnetization through the center \Delta M=\sum_{n>L/2}^{L} (<S_n^z(t)>+1/2)
    #\Delta M= L/4
    loc = 0.5 * (L / 2)
    #\Delta M-=<S_n^z(t)> from n=L/2 to L
    q.y = np.array([0.5 * (L / 2) - sum(q.y[0][L / 2:L])])

#Plot the Error in the magnetization one site to the right of the chain center
Mag = pyalps.collectXY(data, x='Time', y='Local Magnetization', foreach=['Jz'])
for d in Mag:
    d.x = (d.x + 1) * d.props['DT']
Example #26
0
 def check_value_vector(self, string, index, should_be, significance=8):
     import pyalps
     val=pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y.mean[index]
     err=pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y.error[index]
     self.assertLess(abs(should_be-val)/max(err,1e-6),significance)
Example #27
0
            'J0': 1,
            'J1': 1,
            'J2': j2,
            'THERMALIZATION': 5000,
            'SWEEPS': 50000,
            'MODEL': "spin",
            'L': l,
            'W': l / 2
        })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('mc08b', parms)
pyalps.runApplication('loop', input_file)

data = pyalps.loadMeasurements(
    pyalps.getResultFiles(pattern='mc08b.task*.out.h5'),
    ['Binder Ratio of Staggered Magnetization', 'Stiffness'])

binder = pyalps.collectXY(data,
                          x='J2',
                          y='Binder Ratio of Staggered Magnetization',
                          foreach=['L'])
stiffness = pyalps.collectXY(data, x='J2', y='Stiffness', foreach=['L'])

for q in stiffness:
    q.y = q.y * q.props['L']

#make plot
plt.figure()
pyalps.plot.plot(stiffness)
plt.xlabel(r'$J2$')
Example #28
0
 def check_no_double_values(self,string, output=False):
     import pyalps
     from numpy import diff, sort
     val=pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),[string])[0][0].y
     if len(val)>1:
         self.assertGreater(min(diff(sort(abs(val)))),1e-10)
Example #29
0
        'LATTICE': "square lattice",
        'T': t,
        'J': 1,
        'THERMALIZATION': 1000,
        'SWEEPS': 100000,
        'UPDATE': "cluster",
        'MODEL': "Ising",
        'L': 8
    })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm1', parms)
pyalps.runApplication('spinmc', input_file, Tmin=5, writexml=True)

#get the list of result files
result_files = pyalps.getResultFiles(prefix='parm1')
print("Loading results from the files: ", result_files)

#print the observables stored in those files:
print("The files contain the following mesurements:", end=' ')
print(pyalps.loadObservableList(result_files))

#load a selection of measurements:
data = pyalps.loadMeasurements(result_files,
                               ['|Magnetization|', 'Magnetization^2'])

#make a plot for the magnetization: collect Magnetziation as function of T
plotdata = pyalps.collectXY(data, 'T', '|Magnetization|')
plt.figure()
pyalps.plot.plot(plotdata)
plt.xlim(0, 3)
Example #30
0
        parms.append({
            'LATTICE': "chain lattice",
            'MODEL': "spin",
            'local_S': 0.5,
            'J': 1,
            'L': l,
            'CONSERVED_QUANTUMNUMBERS': 'Sz',
            'Sz_total': sz
        })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm2b', parms)
res = pyalps.runApplication('sparsediag', input_file)

#load all measurements for all states
data = pyalps.loadSpectra(pyalps.getResultFiles(prefix='parm2b'))

lengths = []
min_energies = {}

# extract the ground state energies over all momenta for every simulation
for sim in data:
    l = int(sim[0].props['L'])
    if l not in lengths: lengths.append(l)
    sz = int(sim[0].props['Sz_total'])
    all_energies = []
    for sec in sim:
        all_energies += list(sec.y)
    min_energies[(l, sz)] = np.min(all_energies)

# make a plot of the triplet gap as function of system size
Example #31
0
        'SYMMETRIZATION': 0,
        'U': 3,
        't': 0.707106781186547,
        'SWEEPS': int(10000 * b / 16.),
        'THERMALIZATION': 1000,
        'BETA': b
    })

#write the input file and run the simulation
for p in parms:
    input_file = pyalps.writeParameterFile('parm_beta_' + str(p['BETA']), p)
    res = pyalps.runDMFT(input_file)

listobs = ['0', '1']

data = pyalps.loadMeasurements(pyalps.getResultFiles(pattern='parm_beta_*h5'),
                               respath='/simulation/results/G_tau',
                               what=listobs)
for d in pyalps.flatten(data):
    d.x = d.x * d.props["BETA"] / float(d.props["N"])
    d.props['label'] = r'$\beta=$' + str(d.props['BETA']) + '; flavor=' + str(
        d.props['observable'][len(d.props['observable']) - 1])

plt.figure()
plt.xlabel(r'$\tau$')
plt.ylabel(r'$G_{flavor}(\tau)$')
plt.title(
    'DMFT-02: Neel transition for the Hubbard model on the Bethe lattice\n(using the Hybridization expansion impurity solver)'
)
pyalps.plot.plot(data)
plt.legend()
Example #32
0
import matplotlib.pyplot as plt
import pyalps.plot

#prepare the input parameters
parms = [{
    'LATTICE': "chain lattice",
    'MODEL': "spin",
    'local_S': 0.5,
    'L': 40,
    'J': -1,
    'CUTOFF': 1000
}]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm6a', parms)
res = pyalps.runApplication('qwl', input_file)

#run the evaluation and load all the plots
data = pyalps.evaluateQWL(pyalps.getResultFiles(prefix='parm6a'),
                          DELTA_T=0.1,
                          T_MIN=0.1,
                          T_MAX=10.0)

#make plot
for s in pyalps.flatten(data):
    plt.figure()
    plt.title("Ferromagnetic Heisenberg chain")
    pyalps.plot.plot(s)

plt.show()
Example #33
0
		val = 'SEED'
	elif val in ['Sweep', 'Sweeps']:
		val = 'SWEEPS'
	elif val in ['Thermalization']:
		val = 'THERMALIZATION'
	else:
		val = in_val.replace('_', ' ')
	
	return(val)
	
try:
	if args.debug:
		cmd.write(str(args))
	
	#define x-value and y-value 
	read_file = pyalps.getResultFiles(prefix=args.prefix)
	
	x_val = conv_val(args.x)
	y_val = conv_val(args.y)
	
	val_list = pyalps.loadObservableList(read_file)
	val_list = list(set(list(chain.from_iterable(val_list))))
	no_error_val = ['T', 'h', 'L', 'N', 'local_S', 'THERMALIZATION', 'SEED', 'SWEEPS']
	val_list = val_list + no_error_val
	
	if args.debug:
		cmd.write('\nval_list is ' + str(val_list) + '\n')
		cmd.write('no_error_val is ' + str(no_error_val) + '\n')
		cmd.write('x_val is ' + x_val + '\n')
		cmd.write('y_val is ' + y_val + '\n')
	
Example #34
0
File: plot.py Project: DropD/CQP
import sys, os

import numpy as np
import matplotlib.pyplot as plt
import pyalps
from pyalps.plot import plot

files = pyalps.getResultFiles(dirname='data')
data = pyalps.loadMeasurements(files , ['|m|','m^2', 'Connected Susceptibility', 'Binder Cumulant U2'])

for d in pyalps.flatten(data):
    d.props['M/L'] = d.props['M'] / d.props['L']

m = pyalps.collectXY(data, 'Jx', '|m|', foreach=['L', 'M'])
chi = pyalps.collectXY(data, 'Jx', 'Connected Susceptibility', foreach=['L', 'M'])
binder = pyalps.collectXY(data, 'Jx', 'Binder Cumulant U2', foreach=['L', 'M'])


for d in pyalps.flatten(m):
    d.x = np.exp(2.*d.props['Jy'])*d.x
plt.figure()
plot(m)
plt.xlabel('$J/\\Gamma$')
plt.ylabel('magnetization')
plt.legend(loc='best', frameon=False)


for d in pyalps.flatten(chi):
    d.x = np.exp(2.*d.props['Jy'])*d.x
plt.figure()
plot(chi)
Example #35
0
            'J0': 1,
            'J1': 1,
            'J2': j2,
            'THERMALIZATION': 5000,
            'SWEEPS': 50000,
            'MODEL': "spin",
            'L': l,
            'W': l / 2
        })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm8c', parms)
pyalps.runApplication('loop', input_file)

data = pyalps.loadMeasurements(
    pyalps.getResultFiles(pattern='parm8c.task*.out.h5'),
    ['Binder Ratio of Staggered Magnetization', 'Stiffness'])

binder = pyalps.collectXY(data,
                          x='J2',
                          y='Binder Ratio of Staggered Magnetization',
                          foreach=['L'])
stiffness = pyalps.collectXY(data, x='J2', y='Stiffness', foreach=['L'])

for q in stiffness:
    q.y = q.y * q.props['L']

#make plot
plt.figure()
pyalps.plot.plot(stiffness)
plt.xlabel(r'$J2$')
Example #36
0
parms = [ {
        'optimization'              : 'singlesite',
        'LATTICE'                   : 'open chain lattice',
        'L'                         : 20,
        'MODEL'                     : 'spin',
        'local_S0'                  : '0.5',
        'local_S1'                  : '1',
        'CONSERVED_QUANTUMNUMBERS'  : 'N,Sz',
        'Sz_total'                  : 9,
        'J'                         : 1,
        'SWEEPS'                    : 4,
        'NUMBER_EIGENVALUES'        : 1,
        'MAXSTATES'                 : 50,
        'MEASURE_LOCAL[Spin]'       : 'Sz',
        # 'init_state'                : 'local_quantumnumbers',
        # 'initial_local_Sz'          : ','.join(['0.5']*10+['-0.5']*1+['0.5']*9),#'0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,-0.5',#'1,0,0,0,0,0,0,0,0,0',
        # 'initial_local_S'           : ','.join(['0.5']*20+['-0.5']*0),#'0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,-0.5',#'1,0,0,0,0,0,0,0,0,0',
       } ]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('SingleSite3/parm_spin_one',parms)
res = pyalps.runApplication('mps_optim',input_file,writexml=True)

#load all measurements for all states
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix='SingleSite3/parm_spin_one'))

# print properties of the eigenvector:
for s in data[0]:
    print s.props['observable'], ' : ', s.y[0]

Example #37
0
File: plot.py Project: hotta1/LRI
name.append(['Energy_normalized','energynormalized'])
name.append(['Specific Heat','specheat'])
name.append(['Specific Heat Conventional','specheatconv'])
name.append(['Specific Heat by FT','specheatft'])
name.append(['Magnetic Susceptibility connected','magsuscon'])
name.append(['Magnetic Susceptibility connected for Scaling','magsusconsca'])
name.append(['Magnetic Susceptibility disconnected','magsusdis'])
name.append(['Magnetic Susceptibility disconnected for Scaling','magsusdissca'])
name.append(['Binder Ratio of Magnetization connected','bindercon'])
name.append(['Binder Ratio of Magnetization disconnected','binderdis'])
name.append(['Binder Ratio of Magnetization 1 connected','binder1con'])
name.append(['Binder Ratio of Magnetization 1 disconnected','binder1dis'])
name.append(['Specific Heat connected','specheatcon'])

for i in range(0,len(name)):
  data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='LRSW_params'),name[i][0])
  for item in pyalps.flatten(data):
    item.props['L'] = int(item.props['L'])
  graph = pyalps.collectXY(data,x='T',y=name[i][0],foreach=['L'])
  graph.sort(key=lambda item: item.props['L'])
  f1 = open(name[i][1]+'.plt','w')
  f1.write(pyalps.plot.makeGnuplotPlot(graph))
  f1.close()
  f2 = open(name[i][1]+'.dat','w')
  for j in graph:
    L=j.props['L']
    for k in range(0,len(j.x)):
      f2.write(str(L)+' '+str(j.x[k])+' '+str(j.y[k].mean)+' '+str(j.y[k].error)+'\n')
  f2.close()
  print 'finished to output ' + name[i][1] + '.plt and ' + name[i][1] + '.dat'
Example #38
0
                 'THERMALIZATION' : 50000,
                 'SWEEPS'         : 15000,
                 'UPDATE'         : "ssf",
                 'cutoff_distance': 3.0,
                 'L'              : l,
                 'structure_factor': True,
                 'Targeted Acceptance Ratio': 0.4,
                 'Each_Measurement': 15
            }
           )
    #write the input file and run the simulation
    input_file = pyalps.writeInputFiles('parm',parms)
if RUN_SIMULATION:
    pyalps.runApplication('mc++',input_file,Tmin=5,MPI=1)
if ANALYZE:
    data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),['|Structure Factor|^2'])

    def Get_0k_range(L):
        return range(0,L*L,L)
    def Get_k0_range(L):
        return range(0,L,1)
    def Get_kk_range(L):
        return range(0,L*L,L+1)
    def Get_0k_data(data,L):
        return data.flatten()[Get_0k_range(L)]
    def Get_k0_data(data,L):
        return data.flatten()[Get_k0_range(L)]
    def Get_kk_data(data,L):
        return data.flatten()[Get_kk_range(L)]

    data = pyalps.collectXY(data,x='T',y='|Structure Factor|^2')[0]
Example #39
0
    L = 4  # Linear lattice size
    N = 5000  # of simulation steps

    print '# L:', L, 'N:', N

    # Scan beta range [0,1] in steps of 0.1
    for beta in [0., .1, .2, .3, .4, .5, .6, .7, .8, .9, 1.]:
        for l in [4, 6, 8]:
            print '-----------'
            print 'beta =', beta
            sim = Simulation(beta, l)
            sim.run(N / 2, N)
            sim.save('ising.L_' + str(l) + 'beta_' + str(beta) + '.h5')

    #how to calculate the Binder Ratio within Python:
    infiles = pyalps.getResultFiles(pattern='ising.L')

    data = pyalps.loadMeasurements(pyalps.getResultFiles(pattern='ising.L*'),
                                   ['E', 'm^2', 'm^4'])
    m2 = pyalps.collectXY(data, x='BETA', y='m^2', foreach=['L'])
    m4 = pyalps.collectXY(data, x='BETA', y='m^4', foreach=['L'])

    u = []
    for i in range(len(m2)):
        d = pyalps.DataSet()
        d.propsylabel = 'U4'
        d.props = m2[i].props
        d.x = m2[i].x
        d.y = m4[i].y / m2[i].y / m2[i].y
        u.append(d)
#     parmsi['TIMESTEPS'] = int(2*tau / dt)
#     for i in range(L-1):
#         parmsi['t'+str(i)+'[Time]'] = ','.join([mathematica(JW(W)[i]) for W in quench(W_i, W_f, xi, 2*tau, dt)])
#     for i in range(L):
#         parmsi['U'+str(i)+'[Time]'] = ','.join([mathematica(UW(W)[i]) for W in quench(W_i, W_f, xi, 2*tau, dt)])
#     parmslist.append(parmsi)


input_file = pyalps.writeInputFiles(basename + ".dynamic", parmslist)
res = pyalps.runApplication("mps_evolve", input_file, writexml=True)

end = datetime.datetime.now()

## simulation results
data = pyalps.loadIterationMeasurements(
    pyalps.getResultFiles(prefix=basename + ".dynamic"),
    what=["Energy", "Local density", "Local density squared", "One body density matrix", "Density density"],
)

coords = []
for d1 in data:
    for s1 in d1:
        for d in s1:
            for s in d:
                if s.props["observable"] == "One body density matrix":
                    coords = (s.x[:, 0], s.x[:, 1])

XY = pyalps.collectXY(data, x="Time", y="Energy", foreach=["tau"])
E = [[[(x + 1) * dt, y] for (x, y) in zip(xy.x, xy.y)] for xy in XY][0]

# XY = pyalps.collectXY(data, x='Time', y='Overlap', foreach=['tau'])
Example #41
0
              'J'              : 1 ,
              'THERMALIZATION' : 1000,
              'SWEEPS'         : 40000,
              'UPDATE'         : "cluster",
              'MODEL'          : "Ising",
              'L'              : l
            }
    )

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm7a',parms)
pyalps.runApplication('spinmc',input_file,Tmin=5)
# use the following instead if you have MPI
#pyalps.runApplication('spinmc',input_file,Tmin=5,MPI=2)

pyalps.evaluateSpinMC(pyalps.getResultFiles(prefix='parm7a'))

#load the susceptibility and collect it as function of temperature T
data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm7a'),['|Magnetization|', 'Connected Susceptibility', 'Specific Heat', 'Binder Cumulant', 'Binder Cumulant U2'])
magnetization_abs = pyalps.collectXY(data,x='T',y='|Magnetization|',foreach=['L'])
connected_susc = pyalps.collectXY(data,x='T',y='Connected Susceptibility',foreach=['L'])
spec_heat = pyalps.collectXY(data,x='T',y='Specific Heat',foreach=['L'])
binder_u4 = pyalps.collectXY(data,x='T',y='Binder Cumulant',foreach=['L'])
binder_u2 = pyalps.collectXY(data,x='T',y='Binder Cumulant U2',foreach=['L'])

#make plots
plt.figure()
pyalps.plot.plot(magnetization_abs)
plt.xlabel('Temperature $T$')
plt.ylabel('Magnetization $|m|$')
plt.title('2D Ising model')
Example #42
0
basename = 'Tasks/bhstestts3'
# basename = 'Tasks/bhq1'

parmslist = []
for N in range(L+1, 2*L+1):
    parmsi = deepcopy(parms)
    parmsi['N_total'] = N
    parmslist.append(parmsi)


#write the input file and run the simulation
input_file = pyalps.writeInputFiles(basename,parmslist)
res = pyalps.runApplication('mps_optim',input_file,writexml=True)

#load all measurements for all states
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix=basename))

results = []
for d in data:
    for s in d:
        if(s.props['observable'] == 'Energy'):
            results += [(s.props['N_total'], s.y[0])]

Ns = [res[0] for res in sorted(results)]
energies = [res[1] for res in sorted(results)]
# print(energies)

resultsfile = open('/home/ubuntu/Dropbox/Amazon EC2/Simulation Results/ALPS-MPS/Results/'+basename.split('/')[-1]+'.txt', 'w')
resultsstr = '{'+str(L)+',{'+','.join(["{:d}".format(int(N)) for N in Ns]) + '},{' + ','.join(["{:.20f}".format(en) for en in energies]) + '}}'
print(resultsstr)
resultsfile.write(resultsstr)
Example #43
0
input_file = pyalps.writeInputFiles('parm',parms)
#pyalps.runApplication('mc++',input_file,Tmin=5)
# use the following instead if you have MPI
pyalps.runApplication('mc++',input_file,Tmin=5,MPI=1)

def f_alpha(Le, Lo, b=2, d=2):
    return 2-d*log(b)/log(Le)
def f_beta(Le, Lo, b=2, d=2):
    return (d*log(b)-log(Lo))/log(Le) 
def f_gamma(Le, Lo, b=2, d=2):
    return log(b)/log(Le)*(2*log(Lo)/log(b)-d)
def f_nu(Le, Lo, b=2, d=2):
    return log(b)/log(Le)

#load the susceptibility and collect it as function of temperature T
data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm'),['M', 'c_V', 'BinderCumulant', 'susceptibility'])

Tc0=2.269
Tc_min=2
Tc_max=2.5
le0=2
le_min=1.
le_max=10
lo0=3.66802
lo_min=1
lo_max=15
alpha0=f_alpha(le0,lo0,d=2)
beta0 =f_beta(le0,lo0,d=2)
gamma0=f_gamma(le0,lo0,d=2)
nu0   =f_nu(le0,lo0,d=2)
Example #44
0
        p['tau'      ] = tau # not used in the simulation, but useful in the evaluation below
        p['ALWAYS_MEASURE'] = 'Local Magnetization'
        p['chkp_each'     ] = ns
        p['measure_each'  ] = 5
        p['COMPLEX'       ] = 1
        
        parms.append(p)


## write input files and run application
input_file = pyalps.writeInputFiles(basename, parms)
res = pyalps.runApplication('mps_evolve', input_file)


## simulation results
data = pyalps.loadIterationMeasurements(pyalps.getResultFiles(prefix=basename), what=['Local Magnetization'])

numeric_magnetization = []
for d in pyalps.flatten(data):
    L = d.props['L']
    for loc in [1,2]:
        q = deepcopy(d)
        q.x = [0]
        q.y = np.array([ q.y[0][L/2-loc] ])
        q.props['loc'] = loc
        numeric_magnetization.append(q)

mag_vs_time = pyalps.collectXY(numeric_magnetization, x='Time', y='Local Magnetization', foreach=['loc'])
for d in mag_vs_time:
    d.x = (d.x + 1.) * d.props['dt'] # convert time index to real time
    d.props['label'] = 'Numerical at n='+str(d.props['loc'])
    return x_values, y_values, y_errors


parser = argparse.ArgumentParser(description='Evaluate Renyi entropies for range of L', epilog='(C) Johannes Helmes 2014')

parser.add_argument('--infile','-i', help='Prefix of result files',required=True)
parser.add_argument('--foreach','-f',default='h',help='Parameter name, (default h)')
parser.add_argument('--steps','-s',nargs=2,type=int,help='Number of increment steps to complete U and O, (default=1/2 1)')
parser.add_argument('--plot','-p',action='store_true')
parser.add_argument('--verbose','-v',action='store_true')
args=parser.parse_args()

REntropy={}


data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix=args.infile),['EG'])


if args.verbose:
    print data

renyi_dataG = pyalps.collectXY(data, x='IncNo', y='EG', foreach=[args.foreach])

if args.verbose:
    print renyi_dataG

if (args.steps!=None):
    IncNosIItoU=range(args.steps[0])
    IncNosUtoO=range(args.steps[0],args.steps[1])
    #IncNos = [%.1f % i for i in range(args.IncNoRange[0], args.IncNoRange[1])]
    print IncNosIItoU, IncNosUtoO
Example #46
0
#prepare the input parameters
parms = [{
    'LATTICE': "square lattice",
    'MODEL': "spin",
    'MEASURE[Correlations]': True,
    'MEASURE[Structure Factor]': True,
    'MEASURE[Green Function]': True,
    'local_S': 0.5,
    'T': 0.3,
    'J': 1,
    'THERMALIZATION': 10000,
    'SWEEPS': 500000,
    'L': 4,
    'h': 0.1
}]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm4', parms)
res = pyalps.runApplication('dirloop_sse', input_file, Tmin=5)

#load the magnetization and collect it as function of field h
data = pyalps.loadMeasurements(pyalps.getResultFiles())

# print all measurements
for s in pyalps.flatten(data):
    if len(s.x) == 1:
        print(s.props['observable'], ' : ', s.y[0])
    else:
        for (x, y) in zip(s.x, s.y):
            print(s.props['observable'], x, ' : ', y)
Example #47
0
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
# SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
# FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# ****************************************************************************

import pyalps
import numpy as np
import matplotlib.pyplot as plt
import pyalps.plot

data = pyalps.loadSpectra(pyalps.getResultFiles(prefix='ed02a'))
data += pyalps.loadSpectra(pyalps.getResultFiles(prefix='ed02b'))

lengths = []
min_energies = {}

# extract the ground state energies over all momenta for every simulation
for sim in data:
    l = int(sim[0].props['L'])
    if l not in lengths: lengths.append(l)
    sz = int(sim[0].props['Sz_total'])
    s = float(sim[0].props['local_S'])
    all_energies = []
    for sec in sim:
        all_energies += list(sec.y)
    min_energies[(l, s, sz)] = np.min(all_energies)
Example #48
0
       }
   )

input_file = pyalps.writeInputFiles('parm1',parms)

# The queue is loaded from a configuration file which should either be located in the execution directory or in ~/.batchq/configuration
q = load_queue(LSFBSub, "brutus")
desc = runApplicationBackground('spinmc',input_file,Tmin=5,writexml=True, queue = q, force_resubmit = False )

if not desc.finished():
   print "Your simulations has not yet ended, please run this command again later."
else:
    if desc.failed():
        print "Your submission has failed"
        sys.exit(-1)
    result_files = pyalps.getResultFiles(prefix='parm1')
    print result_files
    print pyalps.loadObservableList(result_files)
    data = pyalps.loadMeasurements(result_files,['|Magnetization|','Magnetization^2'])
    print data
    plotdata = pyalps.collectXY(data,'T','|Magnetization|')
    plt.figure()
    pyalps.plot.plot(plotdata)
    plt.xlim(0,3)
    plt.ylim(0,1)
    plt.title('Ising model')
    plt.show()
    print pyalps.plot.convertToText(plotdata)
    print pyalps.plot.makeGracePlot(plotdata)
    print pyalps.plot.makeGnuplotPlot(plotdata)
    binder = pyalps.DataSet()
Example #49
0
              'THERMALIZATION'      : 500,
              'U'                   : u,
              'J'                   : j,
              't0'                  : 0.5,
              't1'                  : 1
        }
        )

# For more precise calculations we propose to enhance the SWEEPS

#write the input file and run the simulation
for p in parms:
    input_file = pyalps.writeParameterFile('parm_u_'+str(p['U'])+'_j_'+str(p['J']),p)
    res = pyalps.runDMFT(input_file)

listobs = ['0', '2']   # flavor 0 is SYMMETRIZED with 1, flavor 2 is SYMMETRIZED with 3
    
data = pyalps.loadMeasurements(pyalps.getResultFiles(pattern='parm_u_*h5'), respath='/simulation/results/G_tau', what=listobs, verbose=True)
for d in pyalps.flatten(data):
    d.x = d.x*d.props["BETA"]/float(d.props["N"])
    d.y = -d.y
    d.props['label'] = r'$U=$'+str(d.props['U'])+'; flavor='+str(d.props['observable'][len(d.props['observable'])-1])
plt.figure()
plt.yscale('log')
plt.xlabel(r'$\tau$')
plt.ylabel(r'$G_{flavor}(\tau)$')
plt.title('DMFT-05: Orbitally Selective Mott Transition on the Bethe lattice')
pyalps.plot.plot(data)
plt.legend()
plt.show()
for i in range(L-1):
    parms['t'+str(i)] = mathematica(JW(W_i*xi)[i])
for i in range(L):
    parms['U'+str(i)] = mathematica(UW(W_i*xi)[i])

resi = 302
basename = 'DynamicsTasks/bhramp.'+str(L)+'.'+str(resi)
# gbasename = basename
gbasename = 'DynamicsTasks/bhramp.'+str(L)+'.300'

start = datetime.datetime.now()

input_file = pyalps.writeInputFiles(gbasename+'.ground',[parms])
res = pyalps.runApplication('mps_optim',input_file,writexml=True)

initstate = pyalps.getResultFiles(prefix=gbasename+'.ground')[0].replace('xml', 'chkp')

parms['initfile'] = initstate
parms['MEASURE_OVERLAP[Overlap]'] = initstate
parms['always_measure'] = 'Overlap,Local density,Local density squared,One body density matrix,Density density'

taus = [1e-6]#np.linspace(1e-7, 2e-7, 2)#[1e-7,1.1e-7,1.2e-7]

parmslist = []
for tau in taus:
    parmsi = deepcopy(parms)
    parmsi['tau'] = tau
    steps = round(2*tau / dt)
    parmsi['TIMESTEPS'] = steps#int(2*tau / dt)
    parmsi['DT'] = 2*tau / steps
    parmsi['measure_each'] = steps#int(2*tau / dt)
Example #51
0
            'T': t,
            'J': 1,
            'THERMALIZATION': 5000,
            'SWEEPS': 150000,
            'UPDATE': "cluster",
            'MODEL': "Ising",
            'L': l
        })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm7b', parms)
pyalps.runApplication('spinmc', input_file, Tmin=5)
# use the following instead if you have MPI
#pyalps.runApplication('spinmc',input_file,Tmin=5,MPI=4)

pyalps.evaluateSpinMC(pyalps.getResultFiles(prefix='parm7b'))

#load the susceptibility and collect it as function of temperature T
# data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm7b'),['|Magnetization|', 'Connected Susceptibility', 'Specific Heat', 'Binder Cumulant', 'Binder Cumulant U2'])
# magnetization_abs = pyalps.collectXY(data,x='T',y='|Magnetization|',foreach=['L'])
# connected_susc = pyalps.collectXY(data,x='T',y='Connected Susceptibility',foreach=['L'])
# spec_heat = pyalps.collectXY(data,x='T',y='Specific Heat',foreach=['L'])
# binder_u4 = pyalps.collectXY(data,x='T',y='Binder Cumulant',foreach=['L'])
# binder_u2 = pyalps.collectXY(data,x='T',y='Binder Cumulant U2',foreach=['L'])
#
# #make a plot of the Binder cumulant:
# plt.figure()
# pyalps.plot.plot(binder_u4)
# plt.xlabel('Temperature $T$')
# plt.ylabel('Binder Cumulant U4 $g$')
# plt.title('2D Ising model')
Example #52
0
def runmain(pipe):
    # ts = np.linspace(0.05, 0.3, 15).tolist()
    ts = np.linspace(5e10, 2.5e11, 5).tolist()
    ts = [ts[0]]
    # ti = int(sys.argv[4])
    # if ti >= 0:
    #     ts = [ts[ti]]
    # ts = [11e10]
    # ts = [2.5e11]
    # ts = [8e10]
    # ts = [np.linspace(0.01, 0.3, 10).tolist()[2]]
    # ts = [0.3]
    # ts = np.linspace(0.3, 0.3, 1).tolist()

    [speckle(t) for t in ts]

    Ns = range(1, 2 * L + 1, 1)
    Ns = range(30, 101, 1)
    Ns = range(50, 80, 1)
    # Ns = [70]
    # Ns = range(2*L-5,2*L+1,1)
    # Ns = [1]
    # Ns = range(1,15,1)
    # Ns = range(1,16,1)
    # Ns = range(1, L, 1)
    # Ns = range(L+1, 2*L+1, 1)
    # Ns = [ 16 ]
    # Ns = range(3,17,1)
    # Ns = range(1, 16, 1)
    # Ns = range(1,7,1)
    # Ns = [7]
    # Ns = [1,2,3,4,5,6]
    # Ns = [1]
    # Ns = range(7,13,1)
    # Ns = range(1,13,1)
    # Ns = [6,7,8,9]
    # Ns = range(1, L+1, 1)
    # Ns = range(L+1,2*L+1,1)
    # Ns = [L+1,L+2]
    # Ns = [L+1]
    # Do L+2 at some point

    dims = [len(ts), len(Ns), neigen]
    ndims = dims + [L]
    Cdims = dims + [L, L]

    trunc = np.zeros(dims)
    E0res = np.zeros(dims)
    nres = np.zeros(ndims)
    n2res = np.zeros(ndims)
    Cres = np.zeros(Cdims)
    cres = np.zeros(Cdims)

    trunc.fill(np.NaN)
    E0res.fill(np.NaN)
    nres.fill(np.NaN)
    n2res.fill(np.NaN)
    Cres.fill(np.NaN)
    cres.fill(np.NaN)

    mindims = [len(ts), len(Ns)]
    nmindims = mindims + [L]
    Cmindims = mindims + [L, L]

    truncmin = np.zeros(mindims)
    E0minres = np.zeros(mindims)
    nminres = np.zeros(nmindims)
    n2minres = np.zeros(nmindims)
    Cminres = np.zeros(Cmindims)
    cminres = np.zeros(Cmindims)

    truncmin.fill(np.NaN)
    E0minres.fill(np.NaN)
    nminres.fill(np.NaN)
    n2minres.fill(np.NaN)
    Cminres.fill(np.NaN)
    cminres.fill(np.NaN)

    # E0res = [[[np.NaN for i in range(reps)] for j in range(len(Ns))] for k in range(len(ts))]
    # E0res = [[[] for j in range(len(Ns))] for k in range(len(ts))]

    start = datetime.datetime.now()

    with concurrent.futures.ThreadPoolExecutor(
            max_workers=numthreads) as executor:
        futures = [
            executor.submit(rundmrg, i, tN[0][0], tN[0][1], tN[1][0], tN[1][1])
            for i, tN in enumerate(
                zip(itertools.product(ts, Ns),
                    itertools.product(range(0, len(ts)), range(0, len(Ns)))))
        ]
        pickle.dump(len(futures), pipe)
        for future in concurrent.futures.as_completed(futures):
            future.result()
            pickle.dump(1, pipe)

    ip = np.zeros([len(ts), len(Ns)])

    res = ''
    res += 'Wres[{0}]={1};\n'.format(resi,
                                     mathformat([speckle(Wi) for Wi in ts]))
    res += 'Jres[{0}]={1};\n'.format(
        resi, mathformat([JW(speckle(Wi)) for Wi in ts]))
    res += 'Ures[{0}]={1};\n'.format(
        resi, mathformat([UW(speckle(Wi)) for Wi in ts]))
    res += 'Wmres[{0}]={1};\n'.format(resi, mathformat([Wi for Wi in ts]))
    res += 'Jmres[{0}]={1};\n'.format(
        resi, mathformat([JW(np.array([Wi, Wi]))[0] for Wi in ts]))
    res += 'Umres[{0}]={1};\n'.format(
        resi, mathformat([UW(np.array([Wi]))[0] for Wi in ts]))
    res += 'neigen[{0}]={1};\n'.format(resi, neigen)
    res += 'delta[{0}]={1};\n'.format(resi, delta)
    res += 'trunc[{0}]={1};\n'.format(resi, mathformat(trunc))
    res += 'Lres[{0}]={1};\n'.format(resi, L)
    res += 'sweeps[{0}]={1};\n'.format(resi, sweeps)
    res += 'maxstates[{0}]={1};\n'.format(resi, maxstates)
    res += 'warmup[{0}]={1};\n'.format(resi, warmup)
    res += 'truncerror[{0}]={1};\n'.format(resi, truncerror)
    res += 'nmax[{0}]={1};\n'.format(resi, nmax)
    res += 'Nres[{0}]={1};\n'.format(resi, mathformat(Ns))
    res += 'tres[{0}]={1};\n'.format(resi, mathformat(ts))
    res += 'mures[{0}]={1};\n'.format(resi, mathformat(mu))

    data = pyalps.loadEigenstateMeasurements(
        pyalps.getResultFiles(prefix=filenameprefix))
    for d in data:
        try:
            it = int(d[0].props['it'])
            iN = int(d[0].props['iN'])
            # ip = int(d[0].props['ip'])
            for s in d:
                for case in switch(s.props['observable']):
                    if case('Truncation error'):
                        # trunc[it][iN][ip] = s.y[0]
                        # trunc[it][iN] = s.y
                        break
                    if case('Energy'):
                        for i, sy in enumerate(s.y):
                            E0res[it][iN][i] = sy
                        # E0res[it][iN][ip] = s.y[0]
                        # E0res[it][iN] = s.y
                        # for sy in s.y
                        break
                    if case('Local density'):
                        for i, sy in enumerate(make2d(s.y)):
                            nres[it][iN][i] = sy
                        # nres[it][iN][ip] = s.y[0]
                        # nres[it][iN] = s.y
                        break
                    if case('Local density squared'):
                        for i, sy in enumerate(make2d(s.y)):
                            n2res[it][iN][i] = sy
                        # n2res[it][iN][ip] = s.y[0]
                        # n2res[it][iN] = s.y
                        break
                    if case('Onebody density matrix'):
                        for i, sy in enumerate(s.y):
                            for x, y in zip(s.x, sy):
                                Cres[it][iN][i][tuple(x)] = y
                        # for x, y in zip(s.x, s.y[0]):
                        # Cres[it][iN][ip][tuple(x)] = y
                        # for x, y in zip(s.x, s.y[0]):
                        #     Cres[it][iN][tuple(x)] = y
                        # for ieig, sy in enumerate(s.y):
                        #     for x, y in zip(s.x, sy):
                        #         Cres[it][iN][ieig][tuple(x)] = y
                        break
            for i in range(neigen):
                Cres[it][iN][i][range(L), range(L)] = nres[it][iN][i]
                cres[it][iN][i] = Cres[it][iN][i] / np.sqrt(
                    np.outer(nres[it][iN][i], nres[it][iN][i]))
            # for ieig in range(neigen):
            #     Cres[it][iN][ieig][range(L), range(L)] = nres[it][iN][ieig]
            #     cres[it][iN][ieig] = Cres[it][iN][ieig] / np.sqrt(np.outer(nres[it][iN][ieig], nres[it][iN][ieig]))
        # except Exception as e:
        except BufferError as e:
            print(e.message)

    # for it in range(len(ts)):
    #     for iN in range(len(Ns)):
    #         try:
    #             m = min(E0res[it][iN])
    #             ieig = np.where(E0res[it][iN] == m)[0][0]
    #             truncmin[it][iN] = trunc[it][iN][ieig]
    #             E0minres[it][iN] = E0res[it][iN][ieig]
    #             nminres[it][iN] = nres[it][iN][ieig]
    #             n2minres[it][iN] = n2res[it][iN][ieig]
    #             Cminres[it][iN] = Cres[it][iN][ieig]
    #             cminres[it][iN] = cres[it][iN][ieig]
    #         except Exception as e:
    #             print(e.message)

    end = datetime.datetime.now()

    res += 'E0res[{0}]={1};\n'.format(resi, mathformat(E0res))
    res += 'nres[{0}]={1};\n'.format(resi, mathformat(nres))
    res += 'n2res[{0}]={1};\n'.format(resi, mathformat(n2res))
    res += 'Cres[{0}]={1};\n'.format(resi, mathformat(Cres))
    res += 'cres[{0}]={1};\n'.format(resi, mathformat(cres))
    # res += 'truncmin[{0}]={1};\n'.format(resi, mathformat(truncmin))
    # res += 'E0minres[{0}]={1};\n'.format(resi, mathformat(E0minres))
    # res += 'nminres[{0}]={1};\n'.format(resi, mathformat(nminres))
    # res += 'n2minres[{0}]={1};\n'.format(resi, mathformat(n2minres))
    # res += 'Cminres[{0}]={1};\n'.format(resi, mathformat(Cminres))
    # res += 'cminres[{0}]={1};\n'.format(resi, mathformat(cminres))
    res += 'runtime[{0}]=\"{1}\";\n'.format(resi, end - start)

    resf.write(res)
    resf.flush()
    os.fsync(resf.fileno())

    if sys.platform == 'linux2':
        shutil.copy(
            resfile,
            '/home/ubuntu/Dropbox/Amazon EC2/Simulation Results/BH-MPS')
Example #53
0
#prepare the input parameters
parms = [{
    'LATTICE': "chain lattice",
    'MODEL': "spin",
    'local_S': 1,
    'J': 1,
    'L': 4,
    'CONSERVED_QUANTUMNUMBERS': 'Sz',
    'MEASURE_STRUCTURE_FACTOR[Structure Factor S]': 'Sz',
    'MEASURE_CORRELATIONS[Diagonal spin correlations]=': 'Sz',
    'MEASURE_CORRELATIONS[Offdiagonal spin correlations]': 'Splus:Sminus'
}]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('ed01a', parms)
res = pyalps.runApplication('sparsediag', input_file)

#load all measurements for all states
data = pyalps.loadEigenstateMeasurements(pyalps.getResultFiles(prefix='ed01a'))

# print properties of ground states in all sectors:
for sector in data[0]:
    print '\nSector with Sz =', sector[0].props['Sz'],
    print 'and k =', sector[0].props['TOTAL_MOMENTUM']
    for s in sector:
        if pyalps.size(s.y[0]) == 1:
            print s.props['observable'], ' : ', s.y[0]
        else:
            for (x, y) in zip(s.x, s.y[0]):
                print s.props['observable'], '(', x, ') : ', y
        'LATTICE': "square lattice",
        'T': 2.269186,
        'J': 1,
        'THERMALIZATION': 1000,
        'SWEEPS': 100000,
        'UPDATE': "cluster",
        'MODEL': "Ising",
        'L': l
    })

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm1b', parms)
pyalps.runApplication('spinmc', input_file, Tmin=5)

#load the binning analysis for the absolute value of the magnetization
binning = pyalps.loadBinningAnalysis(pyalps.getResultFiles(prefix='parm1b'),
                                     '|Magnetization|')
binning = pyalps.flatten(binning)

#make one plot with all data
for dataset in binning:
    dataset.props['label'] = 'L=' + str(dataset.props['L'])

plt.figure()
plt.title('Binning analysis for cluster updates')
plt.xlabel('binning level')
plt.ylabel('Error of |Magnetization|')
pyalps.plot.plot(binning)
plt.legend()
plt.show()
Example #55
0
meas_list = [
    'Energy', 'Truncation error', 'One-body Correlation UP',
    'One-body Correlation DO', 'Two-body Correlation UP',
    'Two-body Correlation DO', 'nUP', 'nDO', 'One-body Correlation UPDO',
    'Two-body Correlation UPDO'
]

for j in indx_list:

    fname = '{}'.format(j)

    try:

        #Load all measurements on ground state
        data = pyalps.loadEigenstateMeasurements(
            pyalps.getResultFiles(prefix=fname), what=meas_list)

        #Save eigenstate properties as a dictionary
        prop = data[0][0].props
        Nmax, L = prop['NMax'], prop['L']

        #Extrach properties
        E0 = data[0][0].y[0]
        trunc = data[0][1].y[0]
        obUP = data[0][2].y[0]
        obDO = data[0][3].y[0]
        tbUP = data[0][4].y[0]
        tbDO = data[0][5].y[0]
        nUP = data[0][6].y[0]
        nDO = data[0][7].y[0]
        obUPDO = data[0][8].y[0]
Example #56
0
import pyalps
import matplotlib.pyplot as plt
import pyalps.plot

#prepare the input parameters
parms = [{ 
          'LATTICE'                   : "double dimer", 
          'LATTICE_LIBRARY'           : "dd-graph.xml", 
          'MODEL'                     : "dimerized spin",
          'MODEL_LIBRARY'             : "model-dspin.xml",
          'CONSERVED_QUANTUMNUMBERS'  : 'Sz',
          'local_S0'                  : 1,
          'local_S1'                  : 0.5,
          'J0'                        : 1,
          'J1'                        : 0.4
        }]

#write the input file and run the simulation
input_file = pyalps.writeInputFiles('parm2c',parms)
res = pyalps.runApplication('fulldiag',input_file)

#run the evaluation and load all the plots
data = pyalps.evaluateFulldiagVersusH(pyalps.getResultFiles(prefix='parm2c'),T = 0.02, DELTA_H=0.025, H_MIN=0., H_MAX=4.0)

#make plot
for s in pyalps.flatten(data):
  plt.figure()
  pyalps.plot.plot(s)

plt.show()
Example #57
0
def createTest(script, inputs=None, outputs=None, prefix=None, refdir='./ref'):
    """ Create reference data, .testin.xml file and execute_test.py

    inputs are:
    -----------
    script: computes results to be tested 

    inputs: Optional list of input files if the application(s)
            called in 'script' rely on them and the input files are in the
            same directory as 'script'. If you specified
            relative paths to another directory, it won't work.

    outputs or prefix: outputs of script can either be specified with
               a complete list of output files or as a prefix 

    creates a script called apptest_name_of_script.py, which can be used to execute the test
    """

    if outputs is not None and prefix is not None:
        raise Exception("Cannot both define outputs and prefix")
    elif outputs is None and prefix is None:
        raise Exception("Script output has to be specified")
    script = os.path.expandvars(script)
    scriptdir = os.path.dirname(script)

    if not os.path.exists(refdir): recursive_mkdir(refdir)

    # Copy input files to refdir to allow execution of script there
    if inputs is not None:

        for f in inputs:
            if not os.path.expandvars(os.path.dirname(f)) == scriptdir:
                print(
                    "Input files to %s should be in the same directory as %s" %
                    (script, script))
                sys.exit(1)

            shutil.copy(f, refdir)

    # execute given script in refdir ( creates reference data )
    pardir = os.getcwd()
    os.chdir(refdir)
    cmdline = [sys.executable, os.path.join(pardir, script)]
    pyalps.executeCommand(cmdline)
    if inputs is not None:
        for f in inputs:
            os.remove(f)
    os.chdir(pardir)

    if prefix is None:
        reffiles = [os.path.join(refdir, os.path.basename(f)) for f in outputs]
    else:
        reffiles = pyalps.getResultFiles(prefix=prefix, dirname=refdir)

    if not reffiles:
        print(
            "Reference files not found. (If you use 'loop' or 'dmrg', try to delete old result files.)"
        )
        sys.exit(1)

    # acquire a list of all observables
    allobs = []
    try:
        eigenstatedata = pyalps.loadEigenstateMeasurements(reffiles)
    except RuntimeError:
        pass
    else:
        try:
            allobs += [o.props['observable'] for o in eigenstatedata[0][0]]

        # DMRG eigenstate data has one level of nesting less
        except TypeError:
            allobs += [o.props['observable'] for o in eigenstatedata[0]]

    try:
        mcdata = pyalps.loadMeasurements(reffiles)
    except RuntimeError:
        pass
    else:
        allobs += [o.props['observable'] for o in mcdata[0]]

    allobs = list(set(allobs))

    scriptname = os.path.basename(script)
    scriptname = os.path.splitext(scriptname)[0]
    scriptname_prefixed = 'apptest_%s.py' % scriptname

    # Write .xml test-input file
    refparms = {
        "TESTNAME": scriptname,
        "TOLERANCE": "auto",
        "WRITE_RESULTS_TO_FILE": "yes",
        "SAVE_OUT_IF_FAIL": "yes"
    }

    testinputfile = writeTestInputFile(script, inputs, refparms, reffiles,
                                       allobs)
    pyalps.tools.copyStylesheet(pardir)

    # Write .py test-start script
    f = open(scriptname_prefixed, 'w')
    f.write('#!/usr/bin/env python\n\n')
    f.write('import sys\n')
    f.write('from pyalps import apptest\n')

    f.write(
        '# Explicitly specify "compMethod=..." and "outputs=..." if needed\n')
    f.write(
        "ret = apptest.runTest( '%s', outputs='auto', compMethod='auto', pyexec='auto' )\n"
        % testinputfile)
    f.write('if not ret: sys.exit(1)\n')

    f.close()
    os.chmod(scriptname_prefixed, 0o755)
Example #58
0
import pyalps
import matplotlib.pyplot as plt
import pyalps.plot

data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='params'),(['Value']))
value = pyalps.collectXY(data,x='T', y='Value')
plt.figure()
pyalps.plot.plot(value)
plt.xlabel('T')
plt.ylabel('Value')
plt.title('Test Plot')
plt.show()
Example #59
0
            'U': 1.0,
            'Nmax': 2,
            'THERMALIZATION': 100000,
            'SWEEPS': 2000000,
            'SKIP': 500,
            'MEASURE[Winding Number]': 1
        })

input_file = pyalps.writeInputFiles('parm1b', parms)
res = pyalps.runApplication('dwa', input_file, Tmin=5, writexml=True)

# Evaluating the simulation and preparing plots using Python
import pyalps
import matplotlib.pyplot as plt
import pyalps.plot as aplt

data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm1b'),
                               'Stiffness')
rhos = pyalps.collectXY(data, x='t', y='Stiffness', foreach=['L'])

for rho in rhos:
    rho.y = rho.y * float(rho.props['L'])

plt.figure()
aplt.plot(rhos)
plt.xlabel('Hopping $t/U$')
plt.ylabel('$\\rho _sL$')
plt.legend()
plt.title('Scaling plot for Bose-Hubbard model')
plt.show()
for i in range(L-1):
    parms['t'+str(i)] = mathematica(JW(W_i*xi)[i])#','.join([mathematica(JW(W_i))])
    # parms['t'+str(i)+'[Time]'] = ','.join([mathematica(JW(W)) for W in quench(W_i, W_f, numsteps, tf / numsteps)])
for i in range(L):
    parms['U'+str(i)] = mathematica(UW(W_i*xi)[i])#','.join([mathematica(UW(W_i))])
    # parms['U'+str(i)+'[Time]'] = ','.join([mathematica(UW(W)) for W in quench(W_i, W_f, numsteps, tf / numsteps)])

resi = 9
basename = 'DynamicsTasks/bhramp.'+str(L)+'.'+str(resi)

start = datetime.datetime.now()

input_file = pyalps.writeInputFiles(basename+'.ground',[parms])
res = pyalps.runApplication('mps_optim',input_file,writexml=True)

initstate = pyalps.getResultFiles(prefix=basename+'.ground')[0].replace('xml', 'chkp')

parms['initfile'] = initstate
parms['MEASURE_OVERLAP[Overlap]'] = initstate
parms['always_measure'] = 'Overlap,Local density,Local density squared,One body density matrix,Density density'
parms['measure_each'] = numsteps

taus = np.linspace(1e-7, 2e-7, 2)#[1e-7,1.1e-7,1.2e-7]

parmslist = []
for tau in taus:
    parmsi = deepcopy(parms)
    parmsi['tau'] = tau
    parmsi['TIMESTEPS'] = int(2*tau / dt)
    for i in range(L-1):
        parmsi['t'+str(i)+'[Time]'] = ','.join([mathematica(JW(W)[i]) for W in quench(W_i, W_f, xi, 2*tau, dt)])