示例#1
0
def load_range_data(infiles, start, end):
    minval = float('inf')
    maxval = float('-inf')
    for f in infiles:
        ds = dr.loadPhi(f)

        # Min, max for this dataset
        tmpmax = ds.max(start=start, end=end)['$\~N$']
        tmpmin = ds.min(start=start, end=end)['$\~N$']

        minval = tmpmin if minval > tmpmin else minval
        maxval = tmpmax if maxval < tmpmax else maxval

    return minval, maxval
示例#2
0
def loadRangeData(infiles, start, end):
    minval = float('inf')
    maxval = float('-inf')
    for f in infiles:
        ds = dr.loadPhi(f)

        # Min, max for this dataset
        tmpmax = ds.max(start=start, end=end)['$\~N$']
        tmpmin = ds.min(start=start, end=end)['$\~N$']

        minval = tmpmin if minval>tmpmin else minval
        maxval = tmpmax if maxval<tmpmax else maxval


    return minval, maxval
示例#3
0
def phiAnalyze(infiles, show, start, end, outfile, conv, S, myrange, nbins):
    phi_vals = np.zeros((len(infiles), 8), dtype=np.float32)
    prev_phi = 0.0
    prev_n = 0
    n_0 = 0
    n_arr = np.empty((len(infiles), 2))

    for i, infile in enumerate(infiles):
        log.debug('loading file: {}'.format(infile))
        ds = dr.loadPhi(infile)
        '''
        with open(infile) as f:
            # Ugh
            for li, line in enumerate(f):
                if (li == 2):
                    phi = float(line.split()[3])
                    break
        '''
        phi = ds.phi
        bphi = phi * conv  #Could be in kT or kJ/mol
        if (args.plotDist):
            #fig = pyplot.figure()
            #mu = ds.data[start:].mean()[0]
            rng = ds.getRange(start=start, end=end)
            mu = ds.getMean(start=start, end=end, bphi=bphi)
            #var = ds.data[start:].var()[0]
            var = ds.getVar(start=start, end=end, bphi=bphi)
            txtstr = "$\mu={:.3f}$\n$\sigma^2={:.3f}$\n$F={:.2f}$".format(
                mu, var, var / mu)
            #print(txtstr)
            hist, bounds = np.histogram(np.array(ds.data[start:end]['$\~N$']),
                                        bins=50)
            ctrs = np.diff(bounds) / 2.0 + bounds[:-1]
            pyplot.bar(ctrs, hist, width=np.diff(ctrs)[0], alpha=0.6)
            #pyplot.annotate(txtstr, xy=(0.2,0.75), xytext=(0.2, 0.75),
            #                xycoords='figure fraction', textcoords='figure fraction')
            #pyplot.suptitle(r'$\beta \phi ={:.2f}$'.format(bphi), fontsize=42)
            #pyplot.legend()
            if outfile:
                stuff = np.zeros((ctrs.shape[0], 2), dtype=float)
                stuff[:, 0] = ctrs
                stuff[:, 1] = hist
                np.savetxt(outfile, stuff)

        log.debug("Beta*Phi: {:.3f}".format(bphi))
        n = ds.getMean(start=start, end=end, bphi=bphi)
        #n = ds.data[start:]['$\~N$'].mean()
        log.debug("    N: {:.2f}".format(n))
        lg_n = np.log(n) + bphi
        log.debug("    lg(N) + beta*phi: {:.2f}".format(lg_n))
        secondCum = ds.getVar(start=start, end=end, bphi=bphi)
        if i == 0:
            dndphi_neg = 0
            n_0 = n
            delta_phi = 0

        try:
            dndphi_neg = (prev_n - n) / (bphi - prev_phi)
        except ZeroDivisionError:
            dndphi_neg = 0
        # Suggested delta phi (adaptive method)
        try:
            delta_phi = (n_0 / S) / secondCum
        except ZeroDivisionError:
            delta_phi = 0
        try:
            lg_n_negslope = (dndphi_neg / n) - 1
        except ZeroDivisionError:
            lg_n_negslope = -1

        phi_vals[
            i] = bphi, n, 0, dndphi_neg, lg_n, lg_n_negslope, delta_phi, secondCum
        prev_phi = bphi
        prev_n = n

    for i in range(phi_vals.shape[0]):
        phi_vals[i, 2] = np.trapz(phi_vals[:i + 1, 1], phi_vals[:i + 1, 0])

    # sort by phi
    phi_vals = phi_vals[phi_vals[:, 0].argsort()]

    # Fill in deriv of lg_beta graph
    # phi_vals[1:,5] = - np.diff(phi_vals[:, 2]) / np.diff(phi_vals[:, 0])
    log.debug("Phi Vals: {}".format(phi_vals))
    if outfile and not args.plotDist:
        np.savetxt(outfile, phi_vals, fmt='%.2f')
    if show:
        if (args.plotDistAll):
            total_stuff = dr.plotHistAll(start=start, end=end, nbins=nbins)
            if outfile:
                np.savetxt(outfile, total_stuff)

            #for ds in dr.datasets.values():
            #    hist, binbounds = np.histogram(ds.data[start:end]['N'],  normed=True)
            #    plt.plot(binbounds[:-1]+np.diff(binbounds)/2.0, -np.log(hist))
            #plt.show()
        if (args.plotN):

            title = r"$\langle{N_V}\rangle_\phi$"
            num = 1
            pyplot.plot(phi_vals[:, 0],
                        phi_vals[:, num],
                        'o-',
                        markersize=12,
                        linewidth=4)
            #pyplot.fill_between(phi_vals[:,0], phi_vals[:,num], color='none', hatch='\\', edgecolor='b')
        if (args.plotInteg):
            #title = r'$\int{\langle{N}\rangle_\phi}d\phi$'
            title = r'$G(\phi)$'
            num = 2
            pyplot.plot(phi_vals[:, 0],
                        phi_vals[:, num],
                        'o-',
                        markersize=12,
                        linewidth=4)
        if (args.plotLogN):
            title = r'$\ln{\langle{N}\rangle_\phi} + \beta\phi$'
            num = 4
            pyplot.plot(phi_vals[:, 0], phi_vals[:, num], 'o-')
        if (args.plotNegSlope):
            title = r'$\langle{\delta N^2}\rangle_\phi / \langle{N}\rangle_\phi - 1$'
            num = 5
            pyplot.plot(phi_vals[:, 0], phi_vals[:, num], 'o-')
        if (args.plotSus):
            title = r"$\langle{\delta N^2}\rangle_\phi$"
            num = 7
            pyplot.plot(phi_vals[:, 0],
                        phi_vals[:, num],
                        'o-',
                        markersize=12,
                        linewidth=4)
        if (args.plotBoth):
            pyplot.close('all')
            f, axarr = pyplot.subplots(2, sharex=True)
            axarr[0].plot(phi_vals[:, 0], phi_vals[:, 1], 'o-')
            axarr[0].set_ylabel(r'$\langle{N}\rangle_\phi$')
            ticks = axarr[0].get_yticks()
            axarr[0].set_yticks(ticks[::2])
            axarr[1].plot(phi_vals[:, 0], phi_vals[:, 7], 'o-')
            axarr[1].set_ylabel(r'$\langle{\delta N^2}\rangle_\phi$')
            ticks = axarr[0].get_yticks()
            axarr[0].set_yticks(ticks[::2])
            if conv == 1:
                pyplot.xlabel(r'$\phi$ (kJ/mol)')
            else:
                pyplot.xlabel(r'$\beta\phi$ ($k_B T$)')
            pyplot.tight_layout()
            pyplot.show()
        if (args.plotDist or args.plotDistAll):
            pyplot.tight_layout()
            pyplot.show()
        else:
            #pyplot.plot(phi_vals[:, 0],phi_vals[:, num])
            #pyplot.title(title + r' vs $\beta\phi$')

            if conv == 1:
                pyplot.xlabel(r'$\phi$ (kJ/mol)')
            else:
                pyplot.xlabel(r'$\beta\phi$ ($k_B T$)')

            pyplot.ylabel(title)

            if myrange:
                pyplot.ylim(myrange)

            pyplot.show()
示例#4
0
    end = args.end
    outfile = args.output
    conv = 1
    if args.T:
        conv /= (args.T * 0.008314)

    S = args.S or len(
        infiles
    )  # Number of phi values - used to suggest delta_phi using adaptive method

    myrange = None
    if args.range:
        myrange = parseRange(args.range)

    if len(infiles) == 1 and args.blockAvg:
        ds = dr.loadPhi(infiles[0], corr_len=1)
        block_vals = ds.blockAvg(start, end=end)
        data_len = np.array(ds.data[start:end]['$\~N$']).shape[0]
        print("Data length:{}".format(data_len))
        pyplot.plot(block_vals[:, 0], np.sqrt(block_vals[:, 2]), 'ro')
        pyplot.xlim(0, block_vals.shape[0] / 2)
        pyplot.xlabel("Block size")
        pyplot.ylabel(r'$\sigma_{{\langle{\~N}\rangle}}$')
        pyplot.show()
        if outfile:
            block = input("Input block size for output: ")
            ds.printOut(outfile, start=start, block=block)
    elif len(infiles) == 1 and not args.plotDist:
        dr.loadPhi(infiles[0])
        dr.plot(start=start, end=end, ylim=myrange)
        dr.show()
示例#5
0
import glob, os, sys
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl

from mdtools import dr

from constants import k

import MDAnalysis

import argparse

from scipy.spatial import cKDTree

ds = dr.loadPhi('phiout.dat')
dat = ds.data[500:]['$\~N$']
mean = dat.mean()
var = dat.var(ddof=1)
std = dat.std(ddof=1)

kt = 300 * k
alpha = 3

kappa = alpha * kt / var
dn = int(np.ceil(4 * (np.sqrt(1 + alpha) / alpha) * std))

neg_nstar = mean / alpha

print('Mean: {:0.2f}  var: {:0.2f}  std: {:0.2f}'.format(mean, var, std))
print('    kappa: {:0.4f}  dn: {:02d}  neg_nstar: {:0.2f}'.format(
示例#6
0
parser.add_argument(
    '--alpha',
    default=3,
    type=float,
    help='Alpha val by which to choose kappa (default: %(default)s)')
parser.add_argument(
    '--temp',
    default=300,
    type=float,
    help='Operating temp for determining kT (default: %(default)s K)')

args = parser.parse_args()

kt = args.temp * k

ds = dr.loadPhi(args.f)
start = args.b
alpha = args.alpha

dat = ds.data[start:]['$\~N$']

mean = dat.mean()
var = dat.var()
std = dat.std()

print('\navg ntwid: {:0.2f}  var ntwid: {:0.2f}   (std: {:0.2f})'.format(
    mean, var, std))
print('  alpha: {:0.1f}'.format(alpha))

kappa = np.round((alpha * kt / var), 3)
dn = int(np.ceil(4 * (np.sqrt(1 + alpha) / alpha) * std))
示例#7
0
psi_stars = []

n_samples = []
uncorr_n_samples = []

nreg_dat = []
ntwid_dat = []
uncorr_nreg_dat = []
uncorr_ntwid_dat = []

start = 500
this_mu = None
for fname in fnames:
    rama = np.loadtxt(fname, usecols=(0,1), comments=['@','#'])
    dirname = os.path.dirname(fname)
    ds = dr.loadPhi('{}/phiout.dat'.format(dirname))
    if this_mu is None:
        this_mu = ds.phi
    else:
        assert this_mu == ds.phi
    n_dat = ds.data[start::10]
    this_nreg_dat = np.array(n_dat['N'])
    this_ntwid_dat = np.array(n_dat['$\~N$'])

    with open("{}/topol.top".format(dirname), "r") as f:
        lines = f.readlines()
        phi_line = lines[-34].strip().split()
        psi_line = lines[-33].strip().split()

        phi_kappas.append(float(phi_line[-1]))
        phi_stars.append(float(phi_line[-2]))
示例#8
0
    parser.add_argument('--fmt', type=str, choices=['phi', 'xvg'], default='phi',
                        help='Format of input data files:  \'phi\' for phiout.dat;' \
                        '\'xvg\' for XVG type files (i.e. from alchemical GROMACS sims)')

    args = parser.parse_args()

    if args.verbose:
        log.setLevel(logging.INFO)
    if args.debug:
        log.setLevel(logging.DEBUG)

    log.info("Loading input files")

    if args.fmt == 'phi':
        for infile in args.input:
            dr.loadPhi(infile)
    elif args.fmt == 'xvg':
        for infile in args.input:
            dr.loadXVG(infile)

    log.info("   ...Done")

    start = args.start
    end = args.end 

    logweights = numpy.loadtxt(args.logweights)
    weights = numpy.exp(logweights)

    logP = numpy.loadtxt(args.logpdist)
    logP[:,1] = -logP[:,1]
    probDist = logP.copy()
示例#9
0
)
parser.add_argument('input',
                    metavar='INPUT',
                    type=str,
                    nargs='+',
                    help='Input file names')
parser.add_argument("--phi",
                    type=float,
                    default=20.0,
                    help="This phi (kJ/mol) (default: 20.0 kJ/mol)")

args = parser.parse_args()

fnames = args.input

ds_0 = dr.loadPhi(fnames[0])
times = np.array(ds_0.data.index)
n_dat = times.size
biases = np.zeros((n_dat, len(fnames) + 1))

biases[:, 0] = times
for i, fname in enumerate(fnames):
    ds = dr.loadPhi(fname)
    assert np.allclose(ds.data.index, ds_0.data.index)

    biases[:, i + 1] = args.phi * ds.data['$\~N$']

np.savetxt("phi_biases.dat",
           biases,
           fmt='%02.6f',
           header='Time(ps) [biases (kJ/mol)...]')
示例#10
0
文件: phianl.py 项目: nrego/mdscripts
def phiAnalyze(infiles, show, start, end, outfile, conv, S, myrange, nbins):
    phi_vals = np.zeros((len(infiles), 8), dtype=np.float32)
    prev_phi = 0.0
    prev_n = 0
    n_0 = 0
    n_arr = np.empty((len(infiles),2))

    for i, infile in enumerate(infiles):
        log.debug('loading file: {}'.format(infile))
        ds = dr.loadPhi(infile)
        '''
        with open(infile) as f:
            # Ugh
            for li, line in enumerate(f):
                if (li == 2):
                    phi = float(line.split()[3])
                    break
        '''
        phi = ds.phi
        bphi = phi*conv #Could be in kT or kJ/mol
        if (args.plotDist):
            #fig = pyplot.figure()
            #mu = ds.data[start:].mean()[0]
            rng = ds.getRange(start=start, end=end)
            mu = ds.getMean(start=start, end=end, bphi=bphi)
            #var = ds.data[start:].var()[0]
            var = ds.getVar(start=start, end=end, bphi=bphi)
            txtstr = "$\mu={:.3f}$\n$\sigma^2={:.3f}$\n$F={:.2f}$".format(mu, var, var/mu)
            #print(txtstr)
            hist, bounds = np.histogram(np.array(ds.data[start:end]['$\~N$']), bins=50, normed=1)
            ctrs = np.diff(bounds)/2.0 + bounds[:-1]
            pyplot.bar(ctrs, hist, width=np.diff(ctrs)[0])
            #pyplot.annotate(txtstr, xy=(0.2,0.75), xytext=(0.2, 0.75),
            #                xycoords='figure fraction', textcoords='figure fraction')
            #pyplot.suptitle(r'$\beta \phi ={:.2f}$'.format(bphi), fontsize=42)
            #pyplot.legend()
            if outfile:
                stuff = np.zeros((ctrs.shape[0], 2), dtype=float)
                stuff[:,0] = ctrs
                stuff[:,1] = hist
                np.savetxt(outfile, stuff)

        log.debug("Beta*Phi: {:.3f}".format(bphi))
        n = ds.getMean(start=start, end=end, bphi=bphi)
        #n = ds.data[start:]['$\~N$'].mean()
        log.debug("    N: {:.2f}".format(n))
        lg_n = np.log(n)+bphi
        log.debug("    lg(N) + beta*phi: {:.2f}".format(lg_n))
        secondCum = ds.getVar(start=start, end=end, bphi=bphi)
        if i == 0:
            dndphi_neg = 0
            n_0 = n
            delta_phi = 0
        
        try:
            dndphi_neg = (prev_n - n) / (bphi - prev_phi)
        except ZeroDivisionError:
            dndphi_neg = 0
        # Suggested delta phi (adaptive method)
        try:
            delta_phi = (n_0/S)/secondCum
        except ZeroDivisionError:
            delta_phi = 0
        try:
            lg_n_negslope = (dndphi_neg/n) - 1
        except ZeroDivisionError:
            lg_n_negslope = -1

        phi_vals[i] = bphi, n, 0, dndphi_neg, lg_n, lg_n_negslope, delta_phi, secondCum
        prev_phi = bphi
        prev_n = n

    for i in xrange(phi_vals.shape[0]):
        phi_vals[i, 2] = np.trapz(phi_vals[:i+1, 1], phi_vals[:i+1, 0])

    # sort by phi
    phi_vals = phi_vals[phi_vals[:,0].argsort()]

    # Fill in deriv of lg_beta graph
    # phi_vals[1:,5] = - np.diff(phi_vals[:, 2]) / np.diff(phi_vals[:, 0])
    log.debug("Phi Vals: {}".format(phi_vals))
    if outfile and not args.plotDist:
        np.savetxt(outfile, phi_vals, fmt='%.2f')
    if show:
        if (args.plotDistAll):
            total_stuff = dr.plotHistAll(start=start, end=end, nbins=nbins)
            if outfile:
                np.savetxt(outfile, total_stuff)
        if (args.plotN):
            title = r"$\langle{\~N}\rangle_\phi$"
            num = 1
            pyplot.plot(phi_vals[:, 0],phi_vals[:, num], 'o-', markersize=12, linewidth=4)
            #pyplot.fill_between(phi_vals[:,0], phi_vals[:,num], color='none', hatch='\\', edgecolor='b')
        if (args.plotInteg):
            title = r'$\int{\langle{N}\rangle_\phi}d\phi$'
            num = 2
            pyplot.plot(phi_vals[:, 0], phi_vals[:, num], 'o-')
        if (args.plotLogN):
            title = r'$\ln{\langle{N}\rangle_\phi} + \beta\phi$'
            num = 4
            pyplot.plot(phi_vals[:, 0],phi_vals[:, num], 'o-')
        if (args.plotNegSlope):
            title = r'$\langle{\delta N^2}\rangle_\phi / \langle{N}\rangle_\phi - 1$'
            num = 5
            pyplot.plot(phi_vals[:, 0],phi_vals[:, num], 'o-')
        if (args.plotSus):
            title = r"$\langle{\delta \~N^2}\rangle_\phi$"
            num = 7
            pyplot.plot(phi_vals[:, 0], phi_vals[:, num], 'o-', markersize=12, linewidth=4)
        if (args.plotBoth):
            pyplot.close('all')
            f, axarr = pyplot.subplots(2, sharex=True)
            axarr[0].plot(phi_vals[:, 0],phi_vals[:, 1], 'o-')
            axarr[0].set_ylabel(r'$\langle{N}\rangle_\phi$')
            ticks = axarr[0].get_yticks()
            axarr[0].set_yticks(ticks[::2])
            axarr[1].plot(phi_vals[:, 0], phi_vals[:, 7], 'o-')
            axarr[1].set_ylabel(r'$\langle{\delta N^2}\rangle_\phi$')
            ticks = axarr[0].get_yticks()
            axarr[0].set_yticks(ticks[::2])            
            if conv == 1:
                pyplot.xlabel(r'$\phi$ (kJ/mol)')
            else:
                pyplot.xlabel(r'$\beta\phi$ ($k_B T$)')
            pyplot.show()
        if (args.plotDist or args.plotDistAll):
            pyplot.show()
        else:
            #pyplot.plot(phi_vals[:, 0],phi_vals[:, num])
            #pyplot.title(title + r' vs $\beta\phi$')

            if conv == 1:
                pyplot.xlabel(r'$\phi$ (kJ/mol)')
            else:
                pyplot.xlabel(r'$\beta\phi$ ($k_B T$)')

            pyplot.ylabel(title)

            if myrange:
                pyplot.ylim(myrange)

            pyplot.show()
示例#11
0
文件: phianl.py 项目: nrego/mdscripts
    log.debug("{} input files".format(len(infiles)))
    start = args.start
    end = args.end
    outfile = args.output
    conv = 1
    if args.T:
        conv /= (args.T * 0.008314)

    S = args.S or len(infiles) # Number of phi values - used to suggest delta_phi using adaptive method

    myrange = None
    if args.range:
        myrange = parseRange(args.range)

    if len(infiles) == 1 and args.blockAvg:
        ds = dr.loadPhi(infiles[0], corr_len=1)
        block_vals = ds.blockAvg(start,end=end)
        data_len = np.array(ds.data[start:end]['$\~N$']).shape[0]
        print "Data length:{}".format(data_len)
        pyplot.plot(block_vals[:,0], np.sqrt(block_vals[:,2]), 'ro')
        pyplot.xlim(0,block_vals.shape[0]/2)
        pyplot.xlabel("Block size")
        pyplot.ylabel(r'$\sigma_{{\langle{\~N}\rangle}}$')
        pyplot.show()
        if outfile:
            block = input("Input block size for output: ")
            ds.printOut(outfile, start=start, block=block)
    elif len(infiles) == 1 and not args.plotDist:
        dr.loadPhi(infiles[0])
        dr.plot(start=start, end=end, ylim=myrange)
        dr.show()
示例#12
0
    start = args.start
    end = args.end

    n_windows = len(args.input)
    all_dat = np.array([])
    n_samples = []

    beta = 1
    if args.T:
        beta /= (args.T * k)

    ts = None
    for infile in args.input:
        log.info("Loading data {}".format(infile))
        ds = dr.loadPhi(infile)
        if ts is None:
            ts = ds.ts
        else:
            assert ts == ds.ts
        dat = np.array(ds.data[start:end]['$\~N$'])
        all_dat = np.append(all_dat, dat)
        n_samples.append(dat.size)

    if args.autocorr is not None:
        autocorr_nsteps = (1 + 2 *
                           (np.loadtxt(args.autocorr) / ts)).astype(int)
    else:
        autocorr_nsteps = np.ones(n_windows, dtype=int)

    n_samples = np.array(n_samples)