Beispiel #1
0
# matplotlib.rcParams.update({'font.size': 18})


# Source: docs.scipy.org/doc/scipy/reference/odr.html
def linear(b, x):
    return b[0] * x + b[1]


mean = (2.5, 2.5)
cov = [[1.5, 0.3], [0.7, 1.5]]
data = np.random.multivariate_normal(mean, cov, 10)

x = [max(0.5, min(s[0], 4.5)) for s in data]
y = [max(0.5, min(s[1], 4.5)) for s in data]

odr_result = odr(linear, [0, 0], y, x, full_output=1)
m, b = odr_result[0]
m = round(m, 6)
b = round(b, 6)
f_odr = np.poly1d((m, b))

ols_result = linregress(x, y)
m, b = ols_result[0:2]
m = round(m, 6)
b = round(b, 6)
f_ols = np.poly1d((m, b))

r = [-1, 6]

fig = figure(figsize=(14, 7))
ax1 = fig.add_subplot(121)
Beispiel #2
0
def plot(args):
    import os, os.path
    import h5py
    from matplotlib import pyplot as plt
    import h5md._plot.label
    from numpy import *
    #from matplotlib import ticker
    # import ssf

    # import pycuda only if required
    if args.cuda:
        import pycuda.autoinit
        make_cuda_kernels()

    ax = plt.axes()
    label = None
    ax.axhline(y=1, color='black', lw=0.5)
    ax.set_color_cycle(args.colors)

    for (i, fn) in enumerate(args.input):
        try:
            f = h5py.File(fn, 'r')
        except IOError:
            raise SystemExit('failed to open HDF5 file: %s' % fn)

        try:
            try:
                param = f['halmd' in f.keys() and 'halmd' or 'parameters'] # backwards compatibility
            except KeyError:
                param = None

            # determine file type, prefer precomputed SSF data
            ssf_path = 'structure/' + '/'.join(args.flavour) + '/static_structure_factor'
            if ssf_path in f:
                # load SSF from file
                H5 = f[ssf_path]
                q = H5['wavenumber'].__array__() # store in memory by conversion to NumPy array
                S_q, S_q_err = load_ssf(H5, args)

            elif 'structure/ssf/' + '/'.join(args.flavour) in f: # backwards compatibility
                # load SSF from file
                H5 = f['structure/ssf/' + '/'.join(args.flavour)]
                q = f['structure/ssf/wavenumber'].__array__() # store in memory by conversion to NumPy array
                S_q, S_q_err = load_ssf(H5, args)

            elif 'trajectory' in f.keys() and param:
                # compute SSF from trajectory data
                H5 = f['trajectory/' + args.flavour[0]]
                q, S_q = ssf_from_trajectory(H5['position'], param, args)
            else:
                raise SystemExit('Input file provides neither SSF data nor a trajectory')

            # before closing the file, store attributes for later use
            if param:
                attrs = h5md._plot.label.attributes(param)
            else:
                attrs = {}

        except IndexError:
            raise SystemExit('invalid phase space sample offset')
        except KeyError as what:
            raise SystemExit(str(what) + '\nmissing simulation data in file: %s' % fn)
        finally:
            f.close()

        if args.label:
            label = args.label[i % len(args.label)] % attrs

        elif args.legend or not args.small:
            basename = os.path.splitext(os.path.basename(fn))[0]
            label = r'%s' % basename.replace('_', r'\_')

        if args.title:
            title = args.title % attrs

        c = args.colors[i % len(args.colors)]
        ax.plot(q, S_q, '-', color=c, label=label)
        if 'S_q_err' in locals():
            ax.errorbar(q, S_q, S_q_err, fmt='o', color=c, markerfacecolor=c, markeredgecolor=c, markersize=2, linewidth=.5)
        else:
            ax.plot(q, S_q, 'o', markerfacecolor=c, markeredgecolor=c, markersize=2)

        # optionally fit Ornstein-Zernike form
        if args.fit_ornstein_zernike:
            import scipy.odr as odr

            density = attrs['density']
            temperature = attrs['temperature']
            idx, = where(q <= args.fit_limit)
            kappa = mean(S_q[idx]) / density / temperature  # initial guess
            # result is a tuple (param, param_err, covariance_matrix)
            param, param_err = odr.odr(
                ornstein_zernike_log                    # fit model
              , (kappa, 1)                              # initial parameter values (kappa, xi)
              , S_q[idx], log(q[idx])                   # data (y, x)
              , extra_args=(density, temperature,), full_output=0
            )[:2]
            kappa, xi = abs(param)
            kappa_err, xi_err = param_err
            if args.verbose:
                print 'Density: {0:g}'.format(density)
                print 'Temperature: {0:g}'.format(temperature)
                print 'Compressibility: {0:g} ± {1:g}'.format(kappa, kappa_err)
                print 'Correlation length: {0:g} ± {1:g}'.format(xi, xi_err)

            if args.axes == 'loglog' or args.axes == 'xlog':
                xmin = args.xlim and args.xlim[0] or 0.01
                x = logspace(log10(xmin), log10(3 * args.fit_limit), num=20)
            else:
                x = linspace(0, 3 * args.fit_limit, num=20)
            y = ornstein_zernike((kappa, xi), x, density, temperature)
            ax.plot(x, y, ':', color=c, linewidth=.8)

        # write plot data to file
        if args.dump:
            f = open(args.dump, 'a')
            print >>f, '# %s, sample %s' % (label.replace(r'\_', '_'), args.sample)
            if 'S_q_err' in locals():
                print >>f, '# q   S_q   S_q_err'
                savetxt(f, array((q, S_q, S_q_err)).T)
            else:
                print >>f, '# q   S_q'
                savetxt(f, array((q, S_q)).T)
            print >>f, '\n'
            f.close()

    # optionally plot power laws
    if args.power_law:
        p = reshape(args.power_law, (-1, 4))
        for (pow_exp, pow_coeff, pow_xmin, pow_xmax) in p:
            px = logspace(log10(pow_xmin), log10(pow_xmax), num=100)
            py = pow_coeff * pow(px, pow_exp)
            ax.plot(px, py, 'k--')

    # adjust axis ranges
    ax.axis('tight')
    if args.xlim:
        plt.setp(ax, xlim=args.xlim)
    if args.ylim:
        plt.setp(ax, ylim=args.ylim)
    else:
        plt.setp(ax, ylim=(0, plt.ylim()[1]))

    # optionally plot with logarithmic scale(s)
    if args.axes == 'xlog':
        ax.set_xscale('log')
    if args.axes == 'ylog':
        ax.set_yscale('log')
    if args.axes == 'loglog':
        ax.set_xscale('log')
        ax.set_yscale('log')

    if args.legend or not args.small:
        l = ax.legend(loc=args.legend)
        l.legendPatch.set_alpha(0.7)

    plt.xlabel(args.xlabel or r'Wavenumber $q\sigma$')
    plt.ylabel(args.ylabel or r'Static structure factor $S(q)$')

    if args.output is None:
        plt.show()
    else:
        plt.savefig(args.output, dpi=args.dpi)
Beispiel #3
0
 def wrap_odr(self, fun, p0, x, y, *args):
     return odr.odr(fun, p0, y, x, extra_args=args)[0]
Beispiel #4
0
def plot(args):
    from matplotlib import pyplot as plt

    # import pycuda only if required
    if args.cuda:
        import pycuda.autoinit
        make_cuda_kernels()

    ax = plt.axes()
    label = None
    ax.axhline(y=1, color='black', lw=0.5)
    ax.set_color_cycle(args.colors)

    for (i, fn) in enumerate(args.input):
        try:
            f = tables.openFile(fn, mode='r')
        except IOError:
            raise SystemExit('failed to open HDF5 file: %s' % fn)

        try:
            H5 = f.root
            param = H5.param

            # determine file type, prefer precomputed SSF data
            if 'structure' in H5._v_groups and 'ssf' in H5.structure._v_groups:
                # load SSF from file
                H5ssf = H5.structure.ssf._v_children[args.flavour or 'AA']
                q = H5.structure.ssf.wavenumber[0]
                S_q, S_q_err = load_ssf(H5ssf, args)

            elif 'trajectory' in H5._v_groups:
                # compute SSF from trajectory data
                if args.flavour:
                    H5trj = H5.trajectory._v_children[args.flavour]
                else:
                    H5trj = H5.trajectory

                q, S_q = ssf_from_trajectory(H5trj, param, args)
            else:
                raise SystemExit('Input file provides neither SSF data nor a trajectory')

            # before closing the file, store attributes for later use
            attrs = mdplot.label.attributes(param)

        except IndexError:
            raise SystemExit('invalid phase space sample offset')
        except tables.exceptions.NoSuchNodeError as what:
            raise SystemExit(str(what) + '\nmissing simulation data in file: %s' % fn)
        finally:
            f.close()

        if args.label:
            label = args.label[i % len(args.label)] % attrs

        elif args.legend or not args.small:
            basename = os.path.splitext(os.path.basename(fn))[0]
            label = r'%s' % basename.replace('_', r'\_')

        if args.title:
            title = args.title % attrs

        c = args.colors[i % len(args.colors)]
        ax.plot(q, S_q, '-', color=c, label=label)
        if 'S_q_err' in locals():
            ax.errorbar(q, S_q, S_q_err, fmt='o', color=c, markerfacecolor=c, markeredgecolor=c, markersize=2, linewidth=.5)
        else:
            ax.plot(q, S_q, 'o', markerfacecolor=c, markeredgecolor=c, markersize=2)

        # optionally fit Ornstein-Zernike form
        if args.fit_ornstein_zernike:
            density = attrs['density']
            temperature = attrs['temperature']
            idx, = where(q <= args.fit_limit)
            kappa = mean(S_q[idx]) / density / temperature  # initial guess
            # result is a tuple (param, param_err, covariance_matrix)
            param, param_err = odr.odr(
                ornstein_zernike_log                    # fit model
              , (kappa, 1)                              # initial parameter values (kappa, xi)
              , S_q[idx], log(q[idx])                   # data (y, x)
              , extra_args=(density, temperature,), full_output=0
            )[:2]
            kappa, xi = abs(param)
            kappa_err, xi_err = param_err
            if args.verbose:
                print 'Density: {0:g}'.format(density)
                print 'Temperature: {0:g}'.format(temperature)
                print 'Compressibility: {0:g} ± {1:g}'.format(kappa, kappa_err)
                print 'Correlation length: {0:g} ± {1:g}'.format(xi, xi_err)

            if args.axes == 'loglog' or args.axes == 'xlog':
                x = logspace(log10(args.xlim[0] or .01), log10(3 * args.fit_limit), num=20)
            else:
                x = linspace(0, 3 * args.fit_limit, num=20)
            y = ornstein_zernike((kappa, xi), x, density, temperature)
            ax.plot(x, y, ':', color=c, linewidth=.8)

        # write plot data to file
        if args.dump:
            f = open(args.dump, 'a')
            print >>f, '# %s, sample %s' % (label.replace(r'\_', '_'), args.sample)
            if 'S_q_err' in locals():
                print >>f, '# q   S_q   S_q_err'
                savetxt(f, array((q, S_q, S_q_err)).T)
            else:
                print >>f, '# q   S_q'
                savetxt(f, array((q, S_q)).T)
            print >>f, '\n'
            f.close()

    # optionally plot power laws
    if args.power_law:
        p = reshape(args.power_law, (-1, 4))
        for (pow_exp, pow_coeff, pow_xmin, pow_xmax) in p:
            px = logspace(log10(pow_xmin), log10(pow_xmax), num=100)
            py = pow_coeff * pow(px, pow_exp)
            ax.plot(px, py, 'k--')

    # adjust axis ranges
    ax.axis('tight')
    if args.xlim:
        plt.setp(ax, xlim=args.xlim)
    if args.ylim:
        plt.setp(ax, ylim=args.ylim)
    else:
        plt.setp(ax, ylim=(0, plt.ylim()[1]))

    # optionally plot with logarithmic scale(s)
    if args.axes == 'xlog':
        ax.set_xscale('log')
    if args.axes == 'ylog':
        ax.set_yscale('log')
    if args.axes == 'loglog':
        ax.set_xscale('log')
        ax.set_yscale('log')

    if args.legend or not args.small:
        l = ax.legend(loc=args.legend)
        l.legendPatch.set_alpha(0.7)

    plt.xlabel(args.xlabel or r'$\lvert\textbf{q}\rvert\sigma$')
    plt.ylabel(args.ylabel or r'$S(\lvert\textbf{q}\rvert)$')

    if args.output is None:
        plt.show()
    else:
        plt.savefig(args.output, dpi=args.dpi)
Beispiel #5
0
def fit_line(points):
    if len(points) < 2:
        return False
    elif len(points) == 2:
        return Line(points[0], points[1])
    else:
        x = [p[0] for p in points]
        y = [p[1] for p in points]

        switched = False
        if abs(x[0] - x[-1]) < abs(y[0] - y[-1]):
            switched = True
            x_temp = list(x)
            x = list(y)
            y = list(x_temp)
            # print('Switched axes')

        odr_result = odr(linear, [0, 0], y, x, full_output=1)
        m, b = odr_result[0]
        m = round(m, 6)
        b = round(b, 6)
        f = np.poly1d((m, b))

        # if switched:
        #     print('ODR: x = {}y + {}'.format(m, b))
        # else:
        #     print('ODR: y = {}x + {}'.format(m, b))
        #
        # stop_cond = odr_result[3]['info']
        # if stop_cond < 1 or stop_cond > 3:
        #     print('Warning: ODR did not converge to a solution (stop condition {})'.format(stop_cond))
        #
        # ols_result = linregress(x, y)
        # m, b = ols_result[0:2]
        # m = round(m, 6)
        # b = round(b, 6)
        # f_ols = np.poly1d((m, b))
        #
        # if switched:
        #     print('OLS: x = {}y + {}'.format(m, b))
        # else:
        #     print('OLS: y = {}x + {}'.format(m, b))

        x1 = x[0]
        x2 = x[-1]

        if switched:
            p1 = round(f(x1)), x1
            p2 = round(f(x2)), x2
            line = Line(p1, p2)
            # pixels = line.pixels()
            # x_temp = list(x)
            # x = list(y)
            # y = list(x_temp)
        else:
            p1 = x1, round(f(x1))
            p2 = x2, round(f(x2))
            line = Line(p1, p2)
            # pixels = line.pixels()

        # x_l = [p[0] for p in pixels]
        # y_l = [p[1] for p in pixels]
        #
        # t_x = (min(x) - 1, max(x) + 1)
        # t_y = (min(y) - 1, max(y) + 1)
        # t = range(t_x[0], t_x[1] + 1, 1)
        #
        # plt.figure()
        # ax = plt.gca()
        # ax.plot(x, y, 'g', linewidth=3)
        # ax.plot(x_l, y_l, 'b', linewidth=3)
        # ax.plot(t, f(t), 'c--', linewidth=3)
        # ax.plot(t, f_ols(t), 'r--', linewidth=3)
        # ax.set_xlim(t_x)
        # ax.set_ylim(t_y)
        # plt.show()

        return line