예제 #1
0
def touch_with_func():
    plot_data = {}
    read_data = CVMCv1Parser.from_file('cv1.txt')
    for i in range(0, 1):
        data = read_data.data[i]['data']
        temp = read_data.data[i]['temp']
        data.set_free_energy_00_from_logtxt('log.txt')
        data.set_end_energy(0, 0)
        err = make_err_func(func)

        points = []
        for j in range(15):
            pylab.plot(data['comp1'], data['corrected_g'], '+')
            pylab.axvline(x=1/16*(j+1), color='black')
            try:
                p = pylab.ginput(n=1, timeout=2)
                while p == []:
                    p = pylab.ginput(n=1, timeout=2)
                print(1/16*(j+1), p[0][1])
            except KeyboardInterrupt:
                print("座標習得を諦めました")
                exit()
            points.append(p[0])
            pylab.close()
        points = np.array(points)

        param = optimize.leastsq(
            err, [1, 1, 1, 1, 1], args=(points[:, 0],
                                        points[:, 1]))[0]
        judge = np.abs(err(param, data['comp1'], data['corrected_g'])) < 1
        inliersx = data['comp1'][judge]
        inliersy = data['corrected_g'][judge]
        x = inliersx
        y = inliersy
        opt = optimize.leastsq(
            err, [1, 1, 1, 1, 1], args=(x, y))[0]
        fitx = np.linspace(0, 1, 100)
        fity = func(opt, fitx)

        plot_data.update({temp:[data['comp1'], data['corrected_g'], fitx, fity]})
    i = 1
    for temp in plot_data:
        pd = plot_data[temp]
        d = (33 // (len(plot_data) + 1))
        pylab.plot(pd[0], pd[1], '+',
                   color=COLOR_PALETTE[d*i][1])
        pylab.plot(pd[2], pd[3], color=COLOR_PALETTE[d*i][0], linewidth=2)
        save_results(temp, pd)
        i += 1
    pylab.xlim(0, 1)

    pylab.show()
예제 #2
0
def normal_fit(func_order, log_file):
    func = {5: penta, 6: hex}[func_order]
    data = CVMCv1Parser.from_file('cv1.txt').data[0]['data']
    data.set_free_energy_00_from_logtxt(log_file)
    data.set_end_energy(0, 0)
    err = make_err_func(func)
    param = optimize.leastsq(
        err, [1, 1, 1, 1, 1], args=(data['comp1'], data['corrected_g']))[0]
    fitx = np.linspace(0, 1, 100)
    fity = func(param, fitx)
    # plot
    fig = pylab.figure()
    plot1 = fig.add_subplot(111)
    pylab.plot(fitx, fity)
    pylab.plot(data['comp1'], data['corrected_g'], 'p')
    plot1.set_ylabel("Free energy (kJ/mol)", fontsize=16)
    plot1.set_xlabel("Fraction of atom A", fontsize=16)
    pylab.xticks(fontsize=14)
    pylab.yticks(fontsize=14)
    fig.subplots_adjust(bottom=0.15)
    # pylab.savefig("energy.eps")
    pylab.show()
    return
예제 #3
0
def ransac(func):
    for i in range(1):
        data = CVMCv1Parser.from_file('cv1.txt').data[i]['data']
        data.set_free_energy_00_from_logtxt('log.txt')
        data.set_end_energy(0, 0)
        err = make_err_func(func)
        iterations = 0
        residuals = []
        models = []
        num = []

        while len(num) < 1000:
            idx = np.random.choice(len(data['comp1']), 10, False)
            param = optimize.leastsq(
                err, [1, 1, 1, 1, 1], args=(data['comp1'][idx],
                                         data['corrected_g'][idx]))[0]
            inliers = []
            judge = np.abs(err(param, data['comp1'], data['corrected_g'])) < 1
            # print(judge)
            inliersx = data['comp1'][judge]
            inliersy = data['corrected_g'][judge]
            # for i in range(len(data['comp1'])):
            #     if err(param, data['comp1'][i], data['corrected_g'][i])**2 > 5:
            #         continue
            #     else:
            #         inliers.append([data['comp1'][i], data['corrected_g'][i]])

            if len(inliersx) > len(data['comp1']) * 0.5:
                # x = np.array(inliers)[:, 0]
                # y = np.array(inliers)[:, 1]
                x = inliersx
                y = inliersy
                candidate = optimize.leastsq(
                    err, [1, 1, 1, 1, 1], args=(x, y))[0]
                res = (err(candidate, x, y) ** 2).sum() / len(inliersx)
                res = (err(param, x, y) ** 2).sum() / len(inliersx)
                # models.append(candidate)
                models.append(param)
                residuals.append(res)
                num.append(len(inliersx))
            iterations += 1
        best_index = np.argmin(residuals)
        # best_index = np.argmax(num)
        print(num[best_index])
        fitparam = models[best_index]
        fitx = np.linspace(0, 1, 100)
        fity = func(fitparam, fitx)




        # fit = CVMPlt.fit_penta(data['comp1'][idx], data['corrected_g'][idx])
        # print(fit[2])
        # iterations += 1
        # fit = CVMPlt.fit_octa(data['comp1'], data['corrected_g'])

    #yp = None
    #xi = pylab.linspace(0, 1, 100)
    #y1 = pylab.stineman_interp(xi, data['comp1'], data['corrected_g'], yp)

        d = (33//(i+1))

    # c.set_end_energy(0, 348.725971609)
    # c.set_end_energy(0, 0)
        pylab.plot(data['comp1'], data['corrected_g'], '+', color=COLOR_PALETTE[d*i][1])
        pylab.plot(fitx, fity, color=COLOR_PALETTE[d*i][0], linewidth=1)

    pylab.xlim(0, 1)
    #pylab.ylim(-1, 1)
    #pylab.savefig('t{0}.eps'.format(tmp))
    pylab.show()
예제 #4
0
def plot(save, log_file, with_cem, vac_corr, end, wo_zero_zero,
         set_yrange, set_xrange):
    def get_correction(x, vac_corr):
        if Fraction(vac_corr):
            return 1/(x+Fraction(vac_corr))
        else:
            return 1

    def get_slope(x, end):
        return end[0]*(1-x) + end[1]*(x)

    data = CVMCv1Parser.from_file('cv1.txt')
    seaborn.set_style('whitegrid')

    fig = pylab.figure()
    plot1 = fig.add_subplot(111)
    plot1.set_ylabel("Free energy (kJ/mol)", fontsize=16)
    plot1.set_xlabel("Fraction of atom A", fontsize=16)
    pylab.xticks(fontsize=14)
    pylab.ylabel("Free energy (kJ/mol)", fontsize=16)
    pylab.xlabel("Fraction of atom A", fontsize=16)
    pylab.yticks(fontsize=14)
    fig.subplots_adjust(bottom=0.15)
    # seaborn.set_palette("winter", len(data.data))
    dict_data = {}
    for data_tmp in data.data:
        dict_data.update({data_tmp['temp']: data_tmp['data']})

    for i, temp in enumerate(sorted(dict_data.keys())):
        color = pylab.cm.cool(i/len(dict_data)) #pylint: disable=E1101
        if wo_zero_zero:
            dict_data[temp].set_free_energy_00(0, 0)
        else:
            dict_data[temp].set_free_energy_00_from_logtxt(log_file)
        dict_data[temp].set_end_energy(end[0], end[1])
        label = str(temp) + "K"
        x = dict_data[temp]['comp1']
        corr = get_correction(x, vac_corr)

        pylab.plot(x*corr, dict_data[temp]['corrected_g']*corr,
                   'o', label=label, color=color)

    pylab.legend(loc='lower left')

    if with_cem:
        cem = CVMLogEnth.from_file(log_file)
        x = cem.stable['c_a']
        corr = get_correction(x, vac_corr)
        pylab.plot(x * corr,
                   (cem.stable['enth']*96.485/1000+get_slope(x, end))*corr, '*',
                   color='orange')
        x = cem.meta['c_a']
        corr = get_correction(x, vac_corr)
        pylab.plot(x * corr,
                   (cem.meta['enth']*96.485/1000+get_slope(x, end))*corr, '*',
                   color='orange')
        x = cem.unstable['c_a']
        corr = get_correction(x, vac_corr)
        pylab.plot(x * corr,
                   (cem.unstable['enth']*96.485/1000+get_slope(x, end))*corr,
                   '*', color='orange')
        x = cem.exact['c_a']
        corr = get_correction(x, vac_corr)
        pylab.plot(x * corr,
                   (cem.exact['exact']*96.485/1000+get_slope(x, end))*corr,
                   '.', color='magenta')

    if set_yrange != (0, 0):
        pylab.ylim(*set_yrange)
    if set_xrange != (0, 0):
        pylab.xlim(*set_xrange)

    if save:
        pylab.savefig("plot.eps")
    else:
        pylab.show()
예제 #5
0
def touch():
    read_data = CVMCv1Parser.from_file('cv1.txt')
    d = read_data.data[0]['data']
    datax = d['comp1']
    dataz = d['F'] * 8.31 / 1000

    max_x = datax.max()
    min_x = datax.min()
    yp = None
    xi = pylab.linspace(min_x, max_x, 20)
    z1 = pylab.stineman_interp(xi, datax, dataz, yp)

    points = []
    for i, x in enumerate(xi):
        fig = pylab.figure()
        ax = fig.add_subplot(111)
        ax.plot(datax, dataz, '+')
        ax.plot(xi, z1, color='red', linewidth=2)

        ax.axvline(x, color='black', linewidth=1)
        Cursor(ax, vertOn=False, useblit=True, color='black', linewidth=1)
        try:
            p = pylab.ginput(n=1, timeout=2)
            while p == []:
                p = pylab.ginput(n=1, timeout=2)
            print(x, p[0][1])
        except KeyboardInterrupt:
            print("そのまま利用します")
            print(x, z1[i])
            p = [[x, z1[i]]]
        points.append(p[0][1])
        pylab.close()
    z2 = pylab.stineman_interp(datax, xi, points)
    delta = (z2 - dataz)**2
    sl = 5
    # pylab.plot(datax, delta[delta < sl])
    # pylab.show()

    ### interp
    # z3 = pylab.stineman_interp(
    #     xi, datax[delta < sl], dataz[delta < sl])
    # pylab.plot(datax, dataz, '+')
    # pylab.plot(xi, z3)
    # pylab.show()
    ### interp

    err = make_err_func(hex_free_end)
    opt = optimize.leastsq(err, [1, 1, 1, 1, 1, 1, 1],
                           args=(datax[delta<sl], dataz[delta<sl]))[0]
    xi2 = pylab.linspace(min_x, max_x, 200)
    fity = hex_free_end(opt, xi2)
    pylab.plot((datax/(datax+0.5))[::5], (dataz/(datax+0.5))[::5], '+')
    pylab.plot(xi2/(xi2+0.5), fity/(xi2+0.5), linewidth=2)
    print(xi2/(xi2+0.5))
    print(fity/(xi2+0.5))

    # pylab.plot(datax, dataz, '+')
    # pylab.plot(xi, fity, linewidth=2)

    pylab.show()

    lines = ''
    for x, z in zip(datax[::5], dataz[::5]):
        lines += '{0}\t{1}\n'.format(str(x/(x+0.5)), str(z/(x+0.5)))
    with open('data.txt', 'w') as wfile:
        wfile.write(lines)

    lines = ''
    for x, z in zip(xi2, fity):
        lines += '{0}\t{1}\n'.format(str(x/(x+0.5)), str(z/(x+0.5)))
    with open('fit.txt', 'w') as wfile:
        wfile.write(lines)
예제 #6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cv1parser
"""
from parse_cvm import CVMCv1Parser
import pylab

cv1s = CVMCv1Parser.from_file('cv1.txt')
cv1s.data[0]['data'].set_free_energy_00_from_logtxt('log.txt')
pylab.plot(cv1s.data[0]['data']['comp1'], cv1s.data[0]['data']['g00'])
pylab.show()

pylab.close()
예제 #7
0
def plot(seq_num, best, fix_zero, with_fit, select_label):
    """
    cv1.txt を plot する
    """
    seq_dirc = "seq{0}".format(seq_num)
    exe = SequenceCVM.from_dirc(seq_dirc)
    fig = pylab.figure(figsize=(8, 10))

    if not best:
        best = len(exe.results.data)
    exe.results = exe.results.get_best_cv_scores(best)

    if select_label:
        exe.results = exe.results.get_data_selected_labels(select_label.split())

    color = [pylab.cm.cool(i/len(exe.results['label'])) #pylint: disable=E1101
             for i in range(len(exe.results['label']))]
    plot2 = fig.add_subplot(212)
    plot2.scatter(exe.results['MxCls'], exe.results['CV_score'], c=color, s=50)
    plot2.text(exe.results.data[0]['MxCls'] + 0.5, exe.results.data[0]['CV_score'],
               exe.results.data[0]['label'])
    plot2.set_xlim(0, exe.results['MxCls'].max()+1)
    plot2.set_ylim(0, None)


    plot1 = fig.add_subplot(211)
    for i, label in enumerate(exe.results['label'][::-1]):
        print(label)
        cv1txt = os.path.join(exe.seq_dirc, label, "cv1.txt")
        logtxt = os.path.join(exe.seq_dirc, label, "log.txt_cem")
        # cv1.txt が空ファイルの場合の error を除去
        try:
            data = CVMCv1Parser.from_file(cv1txt).data[0]['data']
        except IndexError:
            continue
        label_txt = "{0}: {1:.4f}".format(
            label, exe.results.data[::-1][i]['CV_score'])
        # label_txt = label
        if fix_zero:
            data.set_free_energy_00_from_logtxt(logtxt)
            data['g'] = data['g00']
        else:
            data['g'] = data['F'] * 1.380662 * 6.02 / 1000
        color = pylab.cm.cool(1-i/len(exe.results['label'])) #pylint: disable=E1101
        plot1.plot(data['comp1'], data['g'], '.', label=label_txt, color=color)
        if with_fit:
            fitx, fity = fitting_hex(data['comp1'], data['g'])
            plot1.plot(fitx, fity, color=color)
    # print(help(fig.subplots_adjust))
    pylab.legend(bbox_to_anchor=(1.0, 1.0), loc='upper left', borderaxespad=0,
                 fontsize=12)
    plot1.set_ylabel("Free energy (kJ/mol)", fontsize=16)
    plot1.set_xlabel("Fraction of atom A", fontsize=16)
    plot2.set_ylabel("Predictive Error", fontsize=16)
    plot2.set_xlabel("Num of Max Clusters", fontsize=16)
    pylab.subplot(211)
    pylab.xticks(fontsize=14)
    pylab.yticks(fontsize=14)
    pylab.subplot(212)
    pylab.xticks(fontsize=14)
    pylab.yticks(fontsize=14)
    pylab.tight_layout()
    fig.subplots_adjust(right=0.75)

    pylab.show()