Exemple #1
0
def calc_bondacf(args):
    """
    calculates persitence length using bond correlation function
    bondacf: bond correlation function analysis for L_p, when this
                parameter is provided, then program analyzes first points
                and fits them, to understand persistance length.
                C(n) = <u_0 u_n >
    method: create an array C,
    loop trajectory:
        loop residues:
            loop bonds:
                analyze angle between first bond vector and i
    average results
    plot using save_plots
    """
    psffile = get_path_names.get_filename(args.psffile)
    u = MDAnalysis.Universe(psffile + '.psf', args.traj)
    Nbonds = len(u.residues[0]) - 1
    Nres = len(u.residues)
    print "Nres = %r" % Nres
    print "Nbonds = %r" % Nbonds
    bonds = np.array((Nbonds, 3))
    C = np.zeros(Nbonds)
    k = 0
    for ts in u.trajectory[args.startframe:args.endframe:args.trajskip]:
        print "time = %r" % ts.frame
        for res in u.residues:
            bonds = AnalyzeChain.get_bondlist_coords(res)
            k += 1
            for ui in range(0, Nbonds):
                C[ui] += np.dot(bonds[0], bonds[ui])
    C /= float(k)
    ui_array = np.arange(Nbonds)
    save_plots.save_plot(ui_array, C, plotname='bondacf')
def main(args):
    """
    main func
    """
    u = MDAnalysis.Universe(args.psffile, args.traj)
    psffile = get_path_names.get_filename(args.psffile)
    SimData(u, args)
def calc_sq(args):
    """
    input: args obtained from read_traj_vmd
    calculates sq static parameter to analyze trajectories
    output:
    """
    # psffile = os.path.splitext(args.psffile)[0]
    u = Universe(args.psffile, args.traj)
    psffile = get_path_names.get_filename(u.filename)

    # Ndiv = args.nsub
    Natoms = len(u.atoms)
    # Ndiv = int(Natoms**1/3.)
    Ndiv = 201
# create arrays of positions, get the box dimenstions
    u.trajectory[args.startframe]
    u.SYSTEM.packIntoBox()
    X = u.atoms.positions
    box = u.trajectory.ts.dimensions[:-3]
    length_x = box[-1]  # be careful here
# x = np.arange(-length_x,length_x,dx)
    x = np.linspace(-length_x, length_x, Ndiv+1, endpoint=True)

    f, edges = np.histogramdd(X, bins=(Ndiv, Ndiv, Ndiv))
    delta = x[1]-x[0]

# fast fourier transform, go to reciporal space

    ftk = (fftshift(fftn(fftshift(f))*delta))
    # sk = np.abs(ftk**2) / float(Natoms)
    sk = np.abs(ftk**2) / float(Natoms)
# / float(ndata) probably number of atoms

    # plt.cla()

# basis in reciporal space
    omega = 2*np.pi*np.arange(Ndiv-1) / (length_x)
    omega -= omega[int(Ndiv/2)-1]
    k1, k2, k3 = np.meshgrid(omega, omega, omega)
    kmax = np.sqrt(3.)*omega[-1]
    # print "dk =" , dk, " kmax = ", kmax
    C = norm_sq(sk, k1, k2, k3, Ndiv, kmax)
# we are interested in spherically symmetric case,
# i.e only the module of [k1,k2,k3] = normk is important
    # print C[:,1]
    # plt.plot(C[:,1], C[:,2])
    Nfirst = 10
    save_plots.save_plot(C[Nfirst:-Nfirst, 1],
                         C[Nfirst:-Nfirst, 2],
                         xlabel='q, 1/sigma',
                         ylabel='sq',
                         title='static structure factor',
                         plotname='sq',
                         name=psffile+'f'+str(args.startframe),
                         ymax=1.0, ymin=0.)
    return None
def calc_cryst(args):
    """
    Analyzes crystallinity
    """
    u = MDAnalysis.Universe(args.psffile, args.traj)
    psffile = get_path_names.get_filename(args.psffile)
    Nres = len(u.residues)
    frame = []
    g2 = []
    res_g2 = 0.
    # key parameter is the parameter used for parsing the files
    # keyparameter = get_path_names.get_filename(args.traj)
    keyparameter = args.keyparameter
    if args.filedumpskip:
        dumpskip = AnalyzeLog.get_dumpskip(filename='dumpskip.txt',
                                           keyparameter="dump" + keyparameter +
                                           "skip")
        timestep = AnalyzeLog.get_timestep(filename='dumpskip.txt',
                                           keyparameter="time" + keyparameter +
                                           "step")
    else:
        print "using given parameters"
        dumpskip = args.dumpskip
        timestep = args.timestep

    for ts in u.trajectory[args.startframe:args.endframe:args.trajskip]:
        all_g2 = 0.
        frame.append(ts.frame)
        for res in u.residues:
            chords = get_bondlist_coords(res)
            res_g2 = get_chain_crystallinity(chords,
                                             threshold=args.threshold,
                                             neigh=args.neigh)
            all_g2 += res_g2
        print('frame {frame} , g2 = {cryst}'.format(frame=ts.frame,
                                                    cryst=all_g2 /
                                                    float(Nres)))
        g2.append(all_g2 / float(Nres))
    frame = np.array(frame)
    g2 = np.array(g2)
    save_plots.save_plot(frame,
                         g2,
                         plotname='ICC',
                         name=psffile,
                         logplot=args.logplot,
                         dumpskip=dumpskip,
                         timestep=timestep,
                         duplicate=False)
    # save_plots.save_plot_cryst(frame, g2, psffile,
    #                            logplot=args.logplot,
    #                            dumpskip=dumpskip,
    #                            timestep=timestep)
    return None
Exemple #5
0
def SimData(u, args):
    """
    input: u, args
    plot through trajectory and plot frames
    get chaintype, histogram, chaincounts for current frame
    then we plot a histogram

    """
    name = get_path_names.get_filename(args.psffile)
    total_frames, total_crystallinity = [], []
    for ts in u.trajectory[args.startframe:args.endframe:args.trajskip]:
        print " frame = %d " % ts.frame
        # chaintype, histogram, chaincounts
        x, y, counts = get_diff_chain_cryst(u, args)
        total_frames.append(ts.frame)
        total_crystallinity.append(y)  # y = histogram
        # if it is a histogram how do I calculate total crystallinty
        plt.axhline(y=y.min(),
                    xmin=x.min(),
                    xmax=x.max(),
                    linewidth=0.8,
                    color='k',
                    ls='--')
        plt.bar(x,
                y,
                width=0.2 * (x.max() - x.min()) / float(len(x)),
                facecolor='green',
                alpha=0.7,
                align='center')
        yield x, y

    if args.filedumpskip:
        dumpskip = AnalyzeLog.get_dumpskip(filename='dumpskip.txt',
                                           keyparameter="dump" +
                                           args.keyparameter + "skip")
        timestep = AnalyzeLog.get_timestep(filename='dumpskip.txt',
                                           keyparameter="time" +
                                           args.keyparameter + "step")
    else:
        print "using given parameters"
        dumpskip = args.dumpskip
        timestep = args.timestep
    total_frames = np.asarray(total_frames, dtype='float32')
    total_crystallinity = np.asarray(total_crystallinity, dtype='float32')
    factor = 1e6
    total_frames *= dumpskip * timestep / float(factor)
    for j in range(total_crystallinity.shape[1]):
        np.savez(
            'indchainc' + str(x[j]) + 'n' + str(counts[j]) + 'PDI1.0' +
            'extra' + name, total_frames, total_crystallinity[:, j])
def SimData(u, args):
    """
    input: u, args
    plot through trajectory and plot frames
    get chaintype, histogram, chaincounts for current frame
    then we plot a histogram

    """
    name = get_path_names.get_filename(args.psffile)
    total_frames, total_crystallinity, tmp_array = [], [], []
    for ts in u.trajectory[args.startframe:args.endframe:args.trajskip]:
        print " frame = %d " % ts.frame
        # chaintype, histogram, chaincounts
        x, y, counts = get_diff_chain_cryst(u, args)
        total_frames.append(ts.frame)
        tmp = 0.
        for i in range(len(y)):
            tmp += y[i] * counts[i]
        tmp /= counts.sum()
        tmp_array.append(tmp)
        total_crystallinity.append(y)  # y = histogram
        # if it is a histogram how do I calculate total crystallinty
        print "frame = ", ts.frame, "total cryst = ", tmp
    if args.filedumpskip:
        dumpskip = AnalyzeLog.get_dumpskip(filename='dumpskip.txt',
                                           keyparameter="dump" +
                                           args.keyparameter + "skip")
        timestep = AnalyzeLog.get_timestep(filename='dumpskip.txt',
                                           keyparameter="time" +
                                           args.keyparameter + "step")
    else:
        print "using given parameters"
        dumpskip = args.dumpskip
        timestep = args.timestep
    total_frames = np.asarray(total_frames, dtype='float32')
    tmp_array = np.asarray(tmp_array, dtype='float32')
    total_crystallinity = np.asarray(total_crystallinity, dtype='float32')
    factor = 1e6
    total_frames *= dumpskip * timestep / float(factor)
    np.savez('inchain_full', total_frames, tmp_array)
    print "total_crystallinity"
    print total_crystallinity
    for j in range(total_crystallinity.shape[1]):
        np.savez('indchainc' + str(x[j]) + 'n'
                 'PDI1.0' + 'extra' + name, total_frames,
                 total_crystallinity[:, j])
    # total_crystallinity = np.asarray(total_crystallinity)
    return None
def plot_bars(args):
    """plots different histgrams"""
    filenames = [get_path_names.get_filename(x) for x in args.collection]
    parameters = {
        'title': args.titlename,
        'xlabel': args.xlabel,
        'ylabel': args.ylabel,
        'dumpskip': args.dumpskip
    }

    if args.logplot:
        plt.xscale('log')
        parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
        print "xlogscale"
    else:
        print "regular xscale"

    plt.ylabel('${0[ylabel]}$'.format(parameters))
    plt.xlabel('${0[xlabel]}$'.format(parameters))
    plt.title('${0[title]}$'.format(parameters))

    widths = [4, 6, 8, 10, 12]
    colors = ['k', 'y', 'm', 'c', 'b', 'g', 'r', '#aaaaaa']

    colorcycler = itertools.cycle(colors)
    widthscycler = itertools.cycle(widths)

    for (i, j) in itertools.izip(args.collection, filenames):
        npz = np.load(i)
        t = npz[args.name_x]
        p = npz[args.name_y]
        clr = next(colorcycler)
        w = next(widthscycler)
        plt.bar(t,
                p,
                width=w,
                facecolor=clr,
                alpha=0.4,
                label=j,
                align='center')
    if args.legend:
        plt.legend(loc='best')
    plt.savefig(args.titlename + ".pdf")
    return None
Exemple #8
0
def main(args):
    """
    main func
    """
    u = MDAnalysis.Universe(args.psffile, args.traj)
    psffile = get_path_names.get_filename(args.psffile)

    # Now call the animation package:
    # (simData is the user function
    # serving as the argument for simPoints):
    ani = animation.FuncAnimation(FIG,
                                  SimPoints,
                                  SimData(u, args),
                                  blit=True,
                                  interval=150,
                                  repeat=True)

    ani.save('Cryst{filename}.mp4'.format(filename=psffile))
    plt.close()
def main(args):
    """main func"""
    psffile = get_path_names.get_filename(args.psffile)
    u = MDAnalysis.Universe(psffile + '.psf', args.traj)

    bonds = AnalyzeChain.get_bondlist_coords(u.residues[0])
    L = 0.  # number of lamellae
    # the skip on the left and on the right,
    nleft, nright = int(args.neigh) / 2, int(args.neigh) / 2
    Nbonds = len(bonds)
    Nres = len(u.residues)
    timeframes, L_array = [], []

    if args.filedumpskip:
        dumpskip = AnalyzeLog.get_dumpskip(filename='dumpskip.txt',
                                           keyparameter="dump" +
                                           args.keyparameter + "skip")
        timestep = AnalyzeLog.get_timestep(filename='dumpskip.txt',
                                           keyparameter="time" +
                                           args.keyparameter + "step")
    else:
        print "using given parameters"
        dumpskip = args.dumpskip
        timestep = args.timestep

    for ts in u.trajectory[args.startframe:args.endframe:args.trajskip]:
        print "frame = {frame}, percent of lamellae={num_of_lam}"\
               .format(frame=ts.frame,
                       num_of_lam=L/float(Nres))
        timeframes.append(ts.frame)
        L = 0.
        for myres in u.residues:
            bonds = AnalyzeChain.get_bondlist_coords(myres)
            Flag = True  # assume we hit the straight segment of the chain
            atom_indices = []  # indices of atoms in the current lamellae
            for i in xrange(nleft, Nbonds - nright - 1):
                if not Flag:  # if we ended a straight segment, check the len
                    Nlam = len(atom_indices)
                    if Nlam > 9:
                        L += 1.


# print colored( 'lamellae size is %d ' % Nlam, 'green')
# start looking for a new lamellae
                    atom_indices = []
                    Flag = True
                else:
                    # if we still are hitting straight segments
                    ci = get_seg_cryst(i,
                                       bonds,
                                       threshold=args.threshold,
                                       neigh=args.neigh)
                    if ci > args.threshold:
                        # print "segment = %d, | ci = %4.3f" % (i,ci)
                        Flag = True
                        atom_indices.append(i)
                    elif ci > 0.0:
                        # print "segment = %d, > ci = %4.3f" % (i,ci)
                        Flag = False
                    else:
                        ValueError("crystallinity is negative")
        L_array.append(L / float(Nres))
    timeframes = np.array(timeframes)
    L_array = np.array(L_array)
    save_plots.save_plot(timeframes,
                         L_array,
                         plotname='lamellae',
                         name=psffile,
                         logplot=args.logplot,
                         dumpskip=dumpskip,
                         timestep=timestep,
                         ylabel='frac{N_{stems}}{N_{chains}}')
def plot_points(args):
    """
    plots stuff with points
    #algorithm for induction time.
    filenames will represent the mol weight, and will be the X axis
    the flag = False will represent that the crystallization has started
    the tcryst = will be the time of crystallization, it will be appended
    to tcryst_array list
    """
    filenames = [get_path_names.get_filename(x) for x in args.collection]
    parameters = {
        'title': args.titlename,
        'xlabel': args.xlabel,
        'ylabel': args.ylabel,
        'dumpskip': args.dumpskip
    }

    if args.logplot:
        plt.xscale('log')
        parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
        print "xlogscale"
    else:
        print "regular xscale"

    lines = [
        u'D-', u'o-', u'^-', u'>-', u's', u'8', u'<', u'>', u'*', u'H', u'h',
        u'p', u'v', u'D', u'd', "-", "--", "-.", ":"
    ]
    # widths = [4, 6, 8, 10, 12]
    colors = ['k', 'y', 'm', 'c', 'b', 'g', 'r', '#aaaaaa']

    linecycler = itertools.cycle(lines)
    colorcycler = itertools.cycle(colors)

    plt.figure()
    plt.ylabel('${0[ylabel]}$'.format(parameters))
    plt.xlabel(r'${0[xlabel]}$'.format(parameters))
    # plt.title('${0[title]}$'.format(parameters))
    # plt.ylim(0,1)
    # plt.xlim(10,210)
    for (i, j) in itertools.izip(args.collection, filenames):
        # ChainLength = int(re.search('(\d+)n(\d+)', j).group(1))
        # NumOfChains = int(re.search('(\d+)n(\d+)', j).group(2))
        print j
        # Extra_string = (re.findall('fit(\S+)', j))
        npz = np.load(i)
        t = npz[args.name_x]
        p = npz[args.name_y]
        # p_err = npz[args.name_z]
        p_err = t * 0.
        # p = p - p[0]
        clr = next(colorcycler)
        # namefile=get_path_names.get_filename(j)
        # namefile = Extra_string[0]
        namefile = j
        plt.errorbar(t,
                     p,
                     yerr=p_err,
                     color=clr,
                     fmt='o-',
                     linewidth=1.4,
                     label=namefile)
        # plt.plot(t, p, 'go-',color=clr,linewidth=1.4,label=namefile)
        # plt.plot(t, p, next(linecycler),
        #          color=clr,
        #          linewidth=1.2,
        #          label=namefile)
        #,
        # label=r'$M_n = %d,\ N_{chains} = %d$'
        # % (ChainLength, NumOfChains))
    # if args.legend:
    plt.legend(loc='best')
    plt.savefig('{0[title]}.pdf'.format(parameters))
    return None
matplotlib.use('pgf')
matplotlib.rcParams.update(pgf_with_latex)

args = read_parameters.read_plot()

# def plot_points(args):
#     """
#     plots stuff with points
#     #algorithm for induction time.
#     filenames will represent the mol weight, and will be the X axis
#     the flag = False will represent that the crystallization has started
#     the tcryst = will be the time of crystallization, it will be appended
#     to tcryst_array list
#     """
filenames = [get_path_names.get_filename(x) for x in args.collection]
parameters = {
    'title': args.titlename,
    'xlabel': args.xlabel,
    'ylabel': args.ylabel,
    'dumpskip': args.dumpskip
}

if args.logplot:
    plt.xscale('log')
    parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
    print "xlogscale"
else:
    print "regular xscale"

lines = [
def main():
    args = read_parameters.read_traj_vmd()
    print args
    u = MDAnalysis.Universe(args.psffile, args.traj)
    psffile = get_path_names.get_filename(u.filename)
    n_atoms_per_box = args.nAtomsPerBox
    Natoms = u.trajectory.numatoms
    Nx_atoms = Natoms**(1./3.) # how many atoms in a line
    Nsub = int(Nx_atoms / float(n_atoms_per_box)) # how many segements of 3 atoms
    cryst_all = 0.0
    # box = u.trajectory.ts.dimensions[:-3]
    # length_x = box[-1]
    u.SYSTEM.packIntoBox()
    a = u.selectAtoms("all")
    c = a.coordinates()
    print c
    length_x = a.bbox().max()
    grid_1d = np.linspace(0.0, length_x, Nsub+1, endpoint=True)
    delta = grid_1d[1] - grid_1d[0]
    frame = []
    g2 = []

    if args.filedumpskip:
        dumpskip = AnalyzeLog.get_dumpskip(filename='dumpskip.txt',
                                           keyparameter="dump" +
                                           args.keyparameter+"skip")
        # dumpskip = args.dumpskip
        timestep = AnalyzeLog.get_timestep(filename='dumpskip.txt',
                                           keyparameter="time" +
                                           args.keyparameter
                                           + "step")
    else:
        print "using given parameters"
        dumpskip = args.dumpskip
        timestep = args.timestep

    # decide the skipping information
    if args.auto_traj_skip:
        trajskip = int(u.trajectory.numframes/120.)
        if trajskip < 1:
            trajskip = 1
    elif args.auto_traj_skip:
        trajskip = args.trajskip
    else:
        raise ValueError("trajskip needs to be provided")
    for ts in u.trajectory[args.startframe:args.endframe:trajskip]:
        # ar_z is a planar selection
        u.SYSTEM.packIntoBox()
        for i, z in enumerate(grid_1d[0:-1]):
            ar_z = u.selectAtoms("prop  z >= "
                                 + str(z) +
                                 "  and  prop z < "
                                 + str(z+delta))
            # print " I am in z ", z
            # print len(ar_z)
            # ater this step ar_y is a line
            for j, y in enumerate(grid_1d[0:-1]):
                ar_y = ar_z.selectAtoms("prop  y >= "
                                        + str(y) +
                                        "  and  prop y < "
                                        + str(y+delta))
                # print " I am in y ", y
                # print len(ar_y)
                # ater this step ar_x is a dot
                for k, x in enumerate(grid_1d[0:-1]):
                    ar_x = ar_y.selectAtoms("prop  x >= "
                                            + str(x)
                                            + "  and  prop x < "
                                            + str(x+delta))
                    # print " I am in x ", x
                    # print len(ar_x)
                    bonds = AnalyzeChain.get_bondlist_coords(ar_x)
                    cryst_all += get_cryst(bonds, get_eigvec(bonds),
                                           threshold=args.threshold)
        frame.append(ts.frame)
        cryst_all /= float(Nsub**3.0)

        g2.append(cryst_all)
        print "frame ", ts.frame, " cryst = ", cryst_all
    frame = np.array(frame)
    g2 = np.array(g2)
    # os.system("convert -delay ")

    save_plots.save_plot(frame, g2,
                         plotname='YC',
                         name=psffile,
                         logplot=args.logplot,
                         dumpskip=dumpskip,
                         timestep=timestep)
    return None
def plot_points(args):
    """
    plots stuff with points
    #algorithm for induction time.
    filenames will represent the mol weight, and will be the X axis
    the flag = False will represent that the crystallization has started
    the tcryst = will be the time of crystallization, it will be appended
    to tcryst_array list
    """
    def plot_settings(parameters):
        plt.ylim(parameters['ymin'], parameters['ymax'])
        if parameters['xlog']:
            plt.xscale('log')
            parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
            print "xlogscale"
        else:
            print "regular xscale"
        if parameters['ylog']:
            plt.yscale('log')
            parameters['ylabel'] = ''.join(('log', 'parameters[\'ylabel\']'))
            print "ylogscale"
        else:
            print "regular yscale"
        plt.ylabel('${0[ylabel]}$'.format(parameters))
        plt.xlabel('${0[xlabel]}$'.format(parameters))
        # plt.title('{0[title]}'.format(parameters))

        # if parameters['plot_style'] is 'lines':
        # points = ["-", "--", "-.", ":"]
        # elif parameters['plot_style'] is 'points':
        # points = [u'D', u'o', u'^', u'>', u's', u'8',
        #           u'<', u'>',  u'*',
        #           u'H', u'h', u'p', u'v', u'D',
        #           u'd', "-", "--", "-.", ":"]
        # # # else:
        points = [
            u'D-', u'o-', u'^-', u'>-', u's-', u'8-', u'<-', u'>-', u'*-',
            u'H', u'h', u'p', u'v', u'D', u'd', "-", "--", "-.", ":"
        ]
        colors = ['k', 'y', 'm', 'c', 'b', 'g', 'r', '#aaaaaa']
        lines = ["-", "--", "-.", ":"]
        return points, lines, colors

    # read file.param for the plot parameters and put them to parameters
    parameters = plot_read_file.read_plot_parameters(args)

    # read file.in, maybe parse the chain info, reutrn the chain_info_parse
    chain_info_parse = parameters['parse_chain_info']
    if chain_info_parse is True:
        all_files_info_list = plot_read_file.parse_file_info(args.input)
    elif chain_info_parse is False:
        all_files_info_list = plot_read_file.simple_parse_file_info(args.input)
    else:
        raise ValueError('specify whether you need to parse chain info?')

    # initialize figure, do the plot parameters, and specify lines, ..
    plt.figure(figsize=(8, 7))
    points, lines, colors = plot_settings(parameters)
    linecycler = itertools.cycle(lines)
    pointscycler = itertools.cycle(points)
    colorcycler = itertools.cycle(colors)
    chi0_array, kappa_array, n_avrami_array, mw_array = [], [], [], []
    chi0_array_error = []
    chis_array = []
    # loop through files listed and do the plotting
    for i, file_i in enumerate(all_files_info_list):
        # print "doing", file_i
        filename_i = all_files_info_list[i]['npzfile']

        npz = np.load(filename_i)
        t = npz['arr_0']
        x = npz['arr_1']
        x -= x[0]
        # t =
        # normalizing t to be from 0, 0.3
        # t /= t.max()
        # t *= 0.3
        print x
        if parameters['scale_dump'] is True:
            # then scale the result data
            # so the final data represents to the 10^6 lj untis values
            t *= parameters['timestep'] * parameters['dumpskip'] / 1e6
        else:
            print "Using raw data without time scaling"
        #x = x - x[0]
        # print p
        print t

        clr, llr, plr = next(colorcycler), next(linecycler), next(pointscycler)

        if parameters['parse_chain_info'] is True:
            fileNinfo_i = all_files_info_list[i]['chains_info']
            extrainfo_i = all_files_info_list[i]['extrastring']
            # pdiinfo_i = all_files_info_list[i]['PDI']
            result_name = ''
            for Mn, Nch in fileNinfo_i:
                result_name += 'M_n = '
                result_name += str(Mn)
                result_name += 'N_{chains} = '
                result_name += str(Nch)
                result_name += ';'
            # label_i = '${result_name}\ PDI={PDI};{extra}$'.format(
            # result_name=result_name, PDI=pdiinfo_i, extra=extrainfo_i)
            label_i = '${result_name}{extra}$'.format(result_name=result_name,
                                                      extra=extrainfo_i)
            # label_i = '${result_name}$'.format(
            #     result_name=result_name)
        else:
            result_name = all_files_info_list[i]['npzfile']
            result_name = get_path_names.get_filename(result_name)
            label_i = '${result_name}$'.format(result_name=result_name)
        mw, _ = fileNinfo_i[0]  # append M_w info to the list
        mw_array.append(mw)
        x0 = x.max()
        xs = max(get_x0_extrapolation(t[-10:], x[-10:]), x.max())
        chi0_array.append(x0)
        chis_array.append(xs)
        chi0_array_error.append(abs(xs - x0))

        # if parameters['fit'] is True:
        #     #  fitting
        #     #  deltaf/f <= sqrt(deltachi/chi^2 + chi0^2deltakappa/kappa
        #     #  chi0^2deltan/n)
        #     #  chi0 < = 1, thererfore i need just module of the whole thing
        #     #  this is the estimate of the partial derivatives df/dx
        #     #
        #     print "fitting data"
        #     if parameters['parse_chain_info'] is False:
        #         raise ValueError('specify that\
        #          you need to parse chain info, to get M_w information')
        #
        #     # x0 = x.max()
        #     x0 = max(get_x0_extrapolation(t[-10:], x[-10:]),x.max())
        #     # plt.clf()
        #     x0_err = 0.
        #     x /= x0
        #     t0 = t[np.where(x>0.01)[0][0]]
        #     print "t0 = ", t0
        #     # (tfitted, xfitted), fit_params, fit_params_err, fit_chi = fit.fit(fitting_function, t, x, default_pars = [20., 3.])
        #     (tfitted, xfitted), fit_params, fit_params_err, fit_chi = fit.fit(fitting_function, t[x>0.01], x[x>0.01], default_pars = [10.])
        #
        #
        #     print "total error %f" % fit_chi
        #     # print "errors", np.sqrt(np.diag(pcov_p))
        #     print "x0 = ", x0, " +- ", x0_err
        #     print "kappa = ", fit_params[0], " +- ", fit_params_err[0]
        #     # print "n_avrami = ", fit_params[1], " +- ", fit_params_err[1]
        #     chi0_array.append(x0)
        #     kappa_array.append(fit_params[0])
        #     # n_avrami_array.append(fit_params[1])
        #     mw, _ = fileNinfo_i[0]  # append M_w info to the list
        #     mw_array.append(mw)

        # if parameters['normalize'] is True:
        #     print "normalizing data"
        #     # if parameters['fit'] is True:
        #     #     raise ValueError('fit and normalize are non-compatible')
        #     p /= p.max()
        #     if chain_info_parse is True:
        #         plt.plot(t, p, plr,
        #                  color=clr,
        #                  linewidth=1.8,
        #                  alpha=0.9,
        #                  label=label_i)
        #     else:
        #         plt.plot(t, p, llr,
        #                  color=clr,
        #                  linewidth=2.3,
        #                  alpha=0.95,
        #                  label=label_i)

        if chain_info_parse is True:
            plt.plot(t,
                     x,
                     llr,
                     color=clr,
                     linewidth=2.4,
                     markevery=100,
                     alpha=0.99,
                     label="n = " + str(mw))

        if parameters['fit'] is True:
            if parameters['normalize'] is True:
                raise ValueError('fit and normalize are non-compatible')
            plt.plot(t,
                     fitting_function(fit_params, t),
                     '-',
                     color=clr,
                     linewidth=4.2)
            # plt.fill_between(t,
            #                  func(t, chi0, kappa, n_avrami)*(1.-tot_fit_err),
            #                  func(t, chi0, kappa, n_avrami)*(1.+tot_fit_err),
            #                  alpha=0.08, color=clr)
            if chain_info_parse is True:
                plt.plot(t,
                         x,
                         plr,
                         color=clr,
                         linewidth=1.8,
                         alpha=0.7,
                         label=label_i)
            else:
                plt.plot(t,
                         x,
                         llr,
                         color=clr,
                         linewidth=2.0,
                         alpha=0.95,
                         label=label_i)
    if parameters['legend'] is True:
        # plt.legend(loc='best', prop={'size': 12})
        plt.legend(loc='best')
    print parameters

    if parameters['fit'] is True:
        chi0_array, kappa_array, n_avrami_array, mw_array =\
                                         np.asarray(chi0_array),\
                                         np.asarray(kappa_array),\
                                         np.asarray(n_avrami_array),\
                                         np.asarray(mw_array)
        print "chi0", chi0_array
        print "kappa", kappa_array
        print "n_avrami", n_avrami_array
        print "mw", mw_array
        np.savez('fit_data_chi0', mw_array, chi0_array)
        np.savez('fit_data_kappa', mw_array, kappa_array)
        np.savez('fit_data_n', mw_array, n_avrami_array)
        # np.savetxt('myfile.txt', np.c_[x,y,z])
        # np.savetxt('parameters_{0[name]}.txt'.format(parameters),
        # np.c_[mw_array, chi0_array, kappa_array, n_avrami_array],
        # delimiter='\t', newline='\n', fmt='%.4f')
    chi0_array, chis_array, chi0_array_error, mw_array =\
                                         np.asarray(chi0_array),\
                                         np.asarray(chis_array),\
                                         np.asarray(chi0_array_error),\
                                         np.asarray(mw_array)

    np.savetxt(extrainfo_i + 'fit_data_Mn_chi0_delta.csv',
               np.c_[mw_array, chi0_array, chis_array, chi0_array_error],
               delimiter=',')

    plt.savefig('{0[plotname]}{0[name]}.pdf'.format(parameters))

    return None
def plot_points(args):
    """
    plots stuff with points
    #algorithm for induction time.
    filenames will represent the mol weight, and will be the X axis
    the flag = False will represent that the crystallization has started
    the tcryst = will be the time of crystallization, it will be appended
    to tcryst_array list
    """
    def plot_settings(parameters):
        plt.ylim(parameters['ymin'], parameters['ymax'])
        if parameters['xlog']:
            plt.xscale('log')
            parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
            print "xlogscale"
        else:
            print "regular xscale"
        if parameters['ylog']:
            plt.yscale('log')
            parameters['ylabel'] = ''.join(('log', 'parameters[\'ylabel\']'))
            print "ylogscale"
        else:
            print "regular yscale"
        plt.ylabel('${0[ylabel]}$'.format(parameters))
        plt.xlabel('${0[xlabel]}$'.format(parameters))
        # plt.title('{0[title]}'.format(parameters))

        # if parameters['plot_style'] is 'lines':
        # points = ["-", "--", "-.", ":"]
        # elif parameters['plot_style'] is 'points':
        # points = [u'D', u'o', u'^', u'>', u's', u'8',
        #           u'<', u'>',  u'*',
        #           u'H', u'h', u'p', u'v', u'D',
        #           u'd', "-", "--", "-.", ":"]
        # # # else:
        points = [
            u'D-', u'o-', u'^-', u'>-', u's-', u'8-', u'<-', u'>-', u'*-',
            u'H', u'h', u'p', u'v', u'D', u'd', "-", "--", "-.", ":"
        ]
        colors = ['k', 'y', 'm', 'c', 'b', 'g', 'r', '#aaaaaa']
        lines = ["-", "--", "-.", ":"]
        return points, lines, colors

    # read file.param for the plot parameters and put them to parameters
    parameters = read_plot_parameters(args)

    # read file.in, maybe parse the chain info, reutrn the chain_info_parse
    chain_info_parse = parameters['parse_chain_info']
    if chain_info_parse is True:
        all_files_info_list = parse_file_info(args.input)
    elif chain_info_parse is False:
        all_files_info_list = simple_parse_file_info(args.input)
    else:
        raise ValueError('specify whether you need to parse chain info?')

    # initialize figure, do the plot parameters, and specify lines, ..
    plt.figure(figsize=(8, 7))
    points, lines, colors = plot_settings(parameters)
    linecycler = itertools.cycle(lines)
    pointscycler = itertools.cycle(points)
    colorcycler = itertools.cycle(colors)
    chi0_array, kappa_array, n_avrami_array, mw_array = [], [], [], []

    # loop through files listed and do the plotting
    for i, file_i in enumerate(all_files_info_list):
        # print "doing", file_i
        filename_i = all_files_info_list[i]['npzfile']

        # Extra_string = int(re.search('ICC(\s)(\d+)n(\d+)', j).group(1))
        npz = np.load(filename_i)
        t = npz['arr_0']
        p = npz['arr_1']
        if parameters['scale_dump'] is True:
            # then scale the result data
            # so the final data represents to the 10^6 lj untis values
            t *= parameters['timestep'] * parameters['dumpskip'] / 1e6
        else:
            print "Using raw data without time scaling"
        p = p - p[0]
        # print p
        print t

        clr, llr, plr = next(colorcycler), next(linecycler), next(pointscycler)

        if parameters['parse_chain_info'] is True:
            fileNinfo_i = all_files_info_list[i]['chains_info']
            extrainfo_i = all_files_info_list[i]['extrastring']
            # pdiinfo_i = all_files_info_list[i]['PDI']
            result_name = ''
            for Mn, Nch in fileNinfo_i:
                result_name += 'M_n = '
                result_name += str(Mn)
                result_name += 'N_{chains} = '
                result_name += str(Nch)
                result_name += ';'
            # label_i = '${result_name}\ PDI={PDI};{extra}$'.format(
            # result_name=result_name, PDI=pdiinfo_i, extra=extrainfo_i)
            label_i = '${result_name}{extra}$'.format(result_name=result_name,
                                                      extra=extrainfo_i)
            # label_i = '${result_name}$'.format(
            #     result_name=result_name)
        else:
            result_name = all_files_info_list[i]['npzfile']
            result_name = get_path_names.get_filename(result_name)
            label_i = '${result_name}$'.format(result_name=result_name)

        if parameters['fit'] is True:
            #  fitting
            #  deltaf/f <= sqrt(deltachi/chi^2 + chi0^2deltakappa/kappa
            #  chi0^2deltan/n)
            #  chi0 < = 1, thererfore i need just module of the whole thing
            #  this is the estimate of the partial derivatives df/dx
            #
            print "fitting data"
            if parameters['parse_chain_info'] is False:
                raise ValueError('specify that\
                 you need to parse chain info, to get M_w information')
            opt_p, pcov_p = scipy.optimize.curve_fit(func, t, p)
            # calculate error of each parameter using variance == diagonal
            # elements of covariance matrix
            chi0_err, kappa_err, n_avrami_err = np.sqrt(np.diag(pcov_p))
            tot_fit_err = np.linalg.norm(np.diag(pcov_p) / opt_p)
            print "total error %f" % tot_fit_err
            print "errors", np.sqrt(np.diag(pcov_p))
            chi0, kappa, n_avrami = opt_p
            chi0_array.append(chi0)
            kappa_array.append(kappa)
            n_avrami_array.append(n_avrami)
            mw, _ = fileNinfo_i[0]  # append M_w info to the list
            mw_array.append(mw)
            print "saturation", chi0
            print "kappa ", kappa

        # if parameters['normalize'] is True:
        #     print "normalizing data"
        #     # if parameters['fit'] is True:
        #     #     raise ValueError('fit and normalize are non-compatible')
        #     p /= p.max()
        #     if chain_info_parse is True:
        #         plt.plot(t, p, plr,
        #                  color=clr,
        #                  linewidth=1.8,
        #                  alpha=0.9,
        #                  label=label_i)
        #     else:
        #         plt.plot(t, p, llr,
        #                  color=clr,
        #                  linewidth=2.3,
        #                  alpha=0.95,
        #                  label=label_i)
        if parameters['fit'] is True:
            if parameters['normalize'] is True:
                raise ValueError('fit and normalize are non-compatible')
            plt.plot(t,
                     func(t, chi0, kappa, n_avrami),
                     '-',
                     color=clr,
                     linewidth=4.2)
            plt.fill_between(
                t,
                func(t, chi0, kappa, n_avrami) * (1. - tot_fit_err),
                func(t, chi0, kappa, n_avrami) * (1. + tot_fit_err),
                alpha=0.08,
                color=clr)
            if chain_info_parse is True:
                plt.plot(t,
                         p,
                         plr,
                         color=clr,
                         linewidth=1.8,
                         alpha=0.7,
                         label=label_i)
            else:
                plt.plot(t,
                         p,
                         llr,
                         color=clr,
                         linewidth=2.0,
                         alpha=0.95,
                         label=label_i)
        else:
            if parameters['normalize'] is True:
                print "normalizing data"
                p /= p.max()
            if chain_info_parse is True:
                plt.plot(t,
                         p,
                         plr,
                         color=clr,
                         linewidth=1.8,
                         alpha=0.6,
                         label=label_i)
            else:
                plt.plot(t,
                         p,
                         plr,
                         color=clr,
                         linewidth=2.8,
                         alpha=0.9,
                         label=label_i)
                # plt.plot(t, p, llr,
                #          color=clr,
                #          linewidth=2.0,
                #          alpha=0.95,
                #          label=label_i)
    if parameters['legend'] is True:
        # plt.legend(loc='best', prop={'size': 12})
        plt.legend(loc='best')
    print parameters

    if parameters['fit'] is True:
        chi0_array, kappa_array, n_avrami_array, mw_array =\
                                         np.asarray(chi0_array),\
                                         np.asarray(kappa_array),\
                                         np.asarray(n_avrami_array),\
                                         np.asarray(mw_array)
        print "chi0", chi0_array
        print "kappa", kappa_array
        print "n_avrami", n_avrami_array
        print "mw", mw_array
        np.savez('fit_data_chi0', mw_array, chi0_array)
        np.savez('fit_data_kappa', mw_array, kappa_array)
        np.savez('fit_data_n', mw_array, n_avrami_array)
        # np.savetxt('myfile.txt', np.c_[x,y,z])
        np.savetxt('parameters_{0[name]}.txt'.format(parameters),
                   np.c_[mw_array, chi0_array, kappa_array, n_avrami_array],
                   delimiter='\t',
                   newline='\n',
                   fmt='%.4f')
    plt.savefig('{0[plotname]}{0[name]}.pdf'.format(parameters))

    return None
Exemple #15
0
def plot_mpl_fig():
    """
    plots stuff with points
    #algorithm for induction time.
    filenames will represent the mol weight, and will be the X axis
    the flag = False will represent that the crystallization has started
    the tcryst = will be the time of crystallization, it will be appended
    to tcryst_array list
    """
    args = read_parameters.read_from_file()

    def plot_settings(parameters):
        # read_files('file.txt')
        # read_files(args)
        plt.ylim(parameters['ymin'], parameters['ymax'])
        if parameters['xlog']:
            plt.xscale('log')
            parameters['xlabel'] = ''.join(('log', 'parameters[\'xlabel\']'))
            print "xlogscale"
        else:
            print "regular xscale"
        if parameters['ylog']:
            plt.yscale('log')
            parameters['ylabel'] = ''.join(('log', 'parameters[\'ylabel\']'))
            print "ylogscale"
        else:
            print "regular yscale"
        plt.ylabel('${0[ylabel]}$'.format(parameters))
        plt.xlabel('${0[xlabel]}$'.format(parameters))

        points = [
            u'D-', u'o-', u'^-', u'>-', u's-', u'8-', u'<-', u'>-', u'*-',
            u'H', u'h', u'p', u'v', u'D', u'd', "-", "--", "-.", ":"
        ]
        colors = ['k', 'y', 'm', 'c', 'b', 'g', 'r', '#aaaaaa']
        lines = ["-", "--", "-.", ":"]
        return points, lines, colors

    # read file.param for the plot parameters and put them to parameters
    parameters = plot_read_file.read_plot_parameters(args)

    # read file.in, maybe parse the chain info, reutrn the chain_info_parse
    chain_info_parse = parameters['parse_chain_info']
    if chain_info_parse is True:
        all_files_info_list = plot_read_file.parse_file_info(args.input)
    elif chain_info_parse is False:
        all_files_info_list = plot_read_file.simple_parse_file_info(args.input)
    else:
        raise ValueError('specify whether you need to parse chain info?')

    # initialize figure, do the plot parameters, and specify lines, ..
    plt.figure(figsize=(8, 7))
    points, lines, colors = plot_settings(parameters)
    linecycler = itertools.cycle(lines)
    pointscycler = itertools.cycle(points)
    colorcycler = itertools.cycle(colors)

    # loop through files listed and do the plotting
    for i, file_i in enumerate(all_files_info_list):
        # print "doing", file_i
        filename_i = all_files_info_list[i]['npzfile']

        npz = np.load(filename_i)
        t = npz['arr_0']
        x = npz['arr_1']
        is_with_error_bars = True
        try:
            error_array = npz['arr_2']
        except Exception:
            print "doing Exception"
            is_with_error_bars = False
            pass
        # t =
        print x
        if parameters['scale_dump'] is True:
            # then scale the result data
            # so the final data represents to the 10^6 lj untis values
            t *= parameters['timestep'] * parameters['dumpskip'] / 1e6
        else:
            print "Using raw data without time scaling"
        # print p
        print t

        clr, llr, plr = next(colorcycler), next(linecycler), next(pointscycler)

        result_name = all_files_info_list[i]['npzfile']
        result_name = get_path_names.get_filename(result_name)
        label_i = '${result_name}$'.format(result_name=result_name)

        if is_with_error_bars:
            # plt.errorbar(t, x,
            #      yerr=error_array,
            #      color=clr,
            #      linewidth=1.8,
            #      label=label_i)
            plt.plot(t, x, color=clr, linewidth=1.8, label=label_i)
            plt.errorbar(t,
                         error_array,
                         color=clr,
                         linewidth=1.8,
                         label='error' + label_i)
        else:
            x = x - x[0]
            plt.plot(t,
                     x,
                     plr,
                     color=clr,
                     linewidth=1.8,
                     alpha=0.7,
                     label=label_i)
    print parameters
    return None