Ejemplo n.º 1
0
    def best_param(self, pm_temp):
        rec, _ = split_dict(pm_temp, self.__rec_cols)

        calidates = self.__params[self.__cond(rec)].iloc[:, self.__score_idx]
        if calidates.empty:
            return None, None
        best = dict(self.__params.iloc[calidates.idxmax()].items())

        meta, result, _ = split_dict(best, self.__meta_cols,
                                     self.__result_cols)

        #logging.info('best: %s, %s' % (meta, result))
        return meta, result
Ejemplo n.º 2
0
def render_plot(ts, xs, *args, **kwargs):
    '''
    Renders a plot to the screen or to a file.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(
        ('xlabel', 'ylabel', 'mod2pi', 'title', 'file_prefix'), kwargs)
    title = opts.get('title', '$x(t)$')
    file_prefix = opts.get('file_prefix')
    modulo = opts.get('mod2pi', False)

    axes.plot(ts, xs, *args, **plot_args)
    axes.set_xlabel(opts.get('xlabel', 't'))
    axes.set_ylabel(opts.get('ylabel', 'x'))
    axes.set_title(title)

    if modulo:
        axes.set_xbound(0, 2 * numpy.pi)
        axes.set_xticks(
            (0, numpy.pi / 2, numpy.pi, 3 * numpy.pi / 2, 2 * numpy.pi))
        axes.set_xticklabels(('0', r'$\frac{\pi}{2}$', r'$\pi$',
                              r'$\frac{3\pi}{2}$', r'$2\pi$'))

    if file_prefix is None:
        figure.show()
    else:
        figure.savefig('{0}.png'.format(file_prefix), dpi=220)
Ejemplo n.º 3
0
def make_phase_portrait(pfunc, *args, **kwargs):
    '''
    Constructs a phase portrait of the system.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'file_prefix'), kwargs)
    file_prefix = opts.get('file_prefix')
    title = opts.get('title')

    for (theta, omega) in PHASE_POINTS:
        _, xs = rungekutta.rk4(
            pfunc, 0.0, numpy.array([theta, omega], dtype=numpy.float64),
            0.005, 2000)
        axes.plot(xs[0, :], xs[1, :], *args, **plot_args)

    axes.set_xlabel(r'$\theta$')
    axes.set_ylabel(r'$\omega$')
    axes.set_xbound(-3 * numpy.pi / 2, 3 * numpy.pi / 2)
    axes.set_xticks((-3 * numpy.pi / 2, -numpy.pi, -numpy.pi / 2, 0,
                     numpy.pi / 2, numpy.pi, 3 * numpy.pi / 2))
    axes.set_xticklabels(
        (r'$-\frac{3\pi}{2}$', r'$-\pi$', r'$-\frac{\pi}{2}$', '0',
         r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$'))
    axes.set_title('Phase Portrait' if title is None else title)

    if file_prefix is None:
        figure.show()
    else:
        figure.savefig('{0}.png'.format(file_prefix), dpi=220)
Ejemplo n.º 4
0
    def _fit(self, X, y, task_name):

        # add cv info
        pm_temp = {
            'task_name': task_name,
            'data_size': len(X),
            'cv_fold': self.__cv_options['cv'],
            'cv_scoring': self.__cv_options['scoring']
        }
        pm_temp.update(self.__cv_options['param_grid'])

        params = self.__hyparams.gen_params(pm_temp)

        if params:
            cv_options = {
                'verbose': 1,
                'n_jobs': -1,
                'return_train_score': True
            }
            cv_options.update(self.__cv_options)
            cv_options['param_grid'] = params

            cv = GridSearchCV(**cv_options)
            cv.fit(X, y)

            #save hyperparameters
            res = cv.cv_results_
            for pm, score, std in zip(res['params'], res['mean_test_score'],
                                      res['std_test_score']):
                pm = {**pm_temp, **pm}
                pm['score'] = score
                pm['std'] = std
                self.__hyparams.add(pm)
            self.__hyparams.save()

            # trained model
            cv_model = cv.best_estimator_
        else:
            cv_model = None
            logging.debug('All possbiles hyperparameters are trained: \n%s' %
                          pformat(pm_temp))

        # get best params from @pm_temp
        best_pm, result = self.__hyparams.best_param(pm_temp)
        logging.info('[MemoCV] CV(%s,%d), result: %s, Best parameter: \n%s' %
                     (self.__cv_options['scoring'], self.__cv_options['cv'],
                      result, pformat(best_pm)))

        # return the model from best params
        if cv_model is not None and split_dict(
                cv_model.get_params(),
                best_pm.keys())[0] == best_pm:  # optimize for the lucky case
            return cv_model
        else:
            logging.info('[MemoCV] Instaniate model from the best param')
            model = clone(self.__cv_options['estimator'])
            model.set_params(**best_pm)
            model.fit(X, y)
            return model
Ejemplo n.º 5
0
def skewed(x_start=1.0, y_start=0.5, size=1.0, iterations=13, **kwargs):
    '''
    Draws a fractal tree with tuneable parameters.

    '''
    opts, plot_args = split_dict((
                                'title', 
                                'filename', 
                                'llength', 
                                'rlength', 
                                'ltheta', 
                                'rtheta'
                            ), kwargs)
    llength = opts.get('llength', 0.6)
    rlength = opts.get('rlength', 0.6)
    render_color = opts.get('color', 'k')
    ltheta = -numpy.deg2rad(opts.get('ltheta', 90.0))
    rtheta = numpy.deg2rad(opts.get('rtheta', 90.0))

    def _iterate(axes, p0, p1, iterations):
        '''
        Iterates a fancy fractal tree over the axes.

        '''
        if iterations == 0:
            return

        x0, y0 = p0
        x1, y1 = p1
        dv = numpy.array([x1 - x0, y1 - y0], numpy.float64)

        lvec = llength * rotate(dv, ltheta)
        rvec = rlength * rotate(dv, rtheta)

        axes.plot((x1, x1+lvec[0]), (y1, y1+lvec[1]), color=render_color, 
                    **plot_args)
        _iterate(axes, p1, (x1+lvec[0], y1+lvec[1]), iterations-1)
        axes.plot((x1, x1+rvec[0]), (y1, y1+rvec[1]), color=render_color, 
                    **plot_args)
        _iterate(axes, p1, (x1+rvec[0], y1+rvec[1]), iterations-1)

    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    axes.plot(
            (x_start, x_start), 
            (y_start - (size/2), y_start + (size/2)), 
            color=render_color, 
            **plot_args
        )
    _iterate(axes, (x_start, y_start-(size/2)), (x_start, y_start+(size/2)), 
                iterations)

    axes.set_title(opts.get('title', 'Rotated Fractal Tree'))
    if opts.get('filename') is not None:
        figure.savefig(opts['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 6
0
def plot_time(ts, xs, **kwargs):
    '''
    Generates a 3D plot of the Henon map over time.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.add_subplot(111, projection='3d')
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    axes.plot(ts, xs[:,0], xs[:,1], '-', **plot_args)
    figure.show()
Ejemplo n.º 7
0
def plot_time(ts, xs, **kwargs):
    '''
    Generates a 3D plot of the Henon map over time.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.add_subplot(111, projection='3d')
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    axes.plot(ts, xs[:, 0], xs[:, 1], '-', **plot_args)
    figure.show()
Ejemplo n.º 8
0
def skewed(x_start=1.0, y_start=0.5, size=1.0, iterations=13, **kwargs):
    '''
    Draws a fractal tree with tuneable parameters.

    '''
    opts, plot_args = split_dict(
        ('title', 'filename', 'llength', 'rlength', 'ltheta', 'rtheta'),
        kwargs)
    llength = opts.get('llength', 0.6)
    rlength = opts.get('rlength', 0.6)
    render_color = opts.get('color', 'k')
    ltheta = -numpy.deg2rad(opts.get('ltheta', 90.0))
    rtheta = numpy.deg2rad(opts.get('rtheta', 90.0))

    def _iterate(axes, p0, p1, iterations):
        '''
        Iterates a fancy fractal tree over the axes.

        '''
        if iterations == 0:
            return

        x0, y0 = p0
        x1, y1 = p1
        dv = numpy.array([x1 - x0, y1 - y0], numpy.float64)

        lvec = llength * rotate(dv, ltheta)
        rvec = rlength * rotate(dv, rtheta)

        axes.plot((x1, x1 + lvec[0]), (y1, y1 + lvec[1]),
                  color=render_color,
                  **plot_args)
        _iterate(axes, p1, (x1 + lvec[0], y1 + lvec[1]), iterations - 1)
        axes.plot((x1, x1 + rvec[0]), (y1, y1 + rvec[1]),
                  color=render_color,
                  **plot_args)
        _iterate(axes, p1, (x1 + rvec[0], y1 + rvec[1]), iterations - 1)

    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    axes.plot((x_start, x_start), (y_start - (size / 2), y_start + (size / 2)),
              color=render_color,
              **plot_args)
    _iterate(axes, (x_start, y_start - (size / 2)),
             (x_start, y_start + (size / 2)), iterations)

    axes.set_title(opts.get('title', 'Rotated Fractal Tree'))
    if opts.get('filename') is not None:
        figure.savefig(opts['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 9
0
def make_phase_portrait(pfunc, *args, **kwargs):
    '''
    Constructs a phase portrait of the system.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'file_prefix'), kwargs)
    file_prefix = opts.get('file_prefix')
    title = opts.get('title')

    for (theta, omega) in PHASE_POINTS:
        _, xs = rungekutta.rk4(
                                pfunc, 
                                0.0, 
                                numpy.array([theta, omega], dtype=numpy.float64),
                                0.005,
                                2000
                            )
        axes.plot(xs[0,:], xs[1,:], *args, **plot_args)

    axes.set_xlabel(r'$\theta$')
    axes.set_ylabel(r'$\omega$')
    axes.set_xbound(-3*numpy.pi/2, 3*numpy.pi/2)
    axes.set_xticks((
                -3*numpy.pi/2, 
                -numpy.pi, 
                -numpy.pi/2, 
                0, 
                numpy.pi/2,
                numpy.pi,
                3*numpy.pi/2
            ))
    axes.set_xticklabels((
                r'$-\frac{3\pi}{2}$',
                r'$-\pi$',
                r'$-\frac{\pi}{2}$',
                '0',
                r'$\frac{\pi}{2}$',
                r'$\pi$',
                r'$\frac{3\pi}{2}$'
            ))
    axes.set_title('Phase Portrait' if title is None else title)

    if file_prefix is None:
        figure.show()
    else:
        figure.savefig('{0}.png'.format(file_prefix), dpi=220)
Ejemplo n.º 10
0
def render(x_start=1.0, y_start=0.5, size=1.0, iterations=13, **kwargs):
    '''
    Draws a neat fractal tree. 

    '''
    opts, plot_args = split_dict(('title', 'filename', 'ratio'), kwargs)
    render_color = opts.get('color', 'k')
    ratio = opts.get('ratio', 0.6)
    figure = matplotlib.pyplot.figure()

    def _iterate(axes, x_center, y_center, horizontal, size, iterations):
        '''
        Iterates the fractal tree over the axes.

        '''
        if iterations == 0:
            return

        halfsize = size / 2
        if horizontal:
            (x1, x2) = (x_center - halfsize, x_center + halfsize)
            (y1, y2) = (y_center, y_center)
        else:
            # Vertical
            (x1, x2) = (x_center, x_center)
            (y1, y2) = (y_center - halfsize, y_center + halfsize)

        axes.plot((x1,x2), (y1,y2), color=render_color, **plot_args)
        _iterate(axes, x1, y1, not horizontal, ratio*size, iterations-1)
        _iterate(axes, x2, y2, not horizontal, ratio*size, iterations-1)

    axes = figure.gca()
    axes.plot(
            (x_start, x_start), 
            (y_start - (size/2), y_start + (size/2)), 
            color=render_color, 
            **plot_args
        )
    _iterate(axes, x_start, y_start + (size/2), True, 0.6*size, iterations)
    axes.set_xbound((0.4, 1.6))
    axes.set_ybound((0.0, 1.4))
    axes.set_title(opts.get('title', 'Self-similar Fractal Tree'))

    if opts.get('filename') is not None:
        figure.savefig(opts['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 11
0
    def gen_params(self, pm_temp, by='nodup'):

        # extract meta parameter from template
        meta, rec, _ = split_dict(pm_temp, self.__meta_cols, self.__rec_cols)

        def listify(pm):
            for p in meta:
                v = pm[p]
                pm[p] = [v]
            return pm

        metas = []
        for m in self.__gen(list(meta.items()), 0):
            if not self.is_dup({**m, **rec}):
                metas.append(listify(m))

        return metas
        '''
Ejemplo n.º 12
0
def plot_pfunc(pfunc, *args, **kwargs):
    '''
    Convenience function for experimenting with pendulum functions.

    '''
    opts, plot_args = split_dict(('tstep', 'theta0', 'omega0', 'nsteps'),
                                 kwargs)
    theta0 = opts.get('theta0', 3.0)
    omega0 = opts.get('omega0', 0.1)
    tstep = opts.get('tstep', 0.005)
    nsteps = opts.get('nsteps', 2000)
    _, xs = rungekutta.rk4(pfunc, 0.0,
                           numpy.array([theta0, omega0], dtype=numpy.float64),
                           tstep, nsteps)
    fix_domain = lambda x: mod2pi(x) if kwargs.get('mod2pi', False) else x
    xs[0, :] = numpy.array([fix_domain(theta) for theta in xs[0, :]],
                           dtype=numpy.float64)
    render_plot(xs[0, :], xs[1, :], *args, **plot_args)
Ejemplo n.º 13
0
def plot_time(ts, xs, **kwargs):
    '''
    Plots the specified vector in the time domain.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(ts, xs, '.', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_aspect(ts[-1] - ts[0])
    axes.set_xlabel('n')
    axes.set_ylabel(r'$x_n$')
    axes.set_title(opts.get('title', r'$x_n$'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 14
0
def plot_bifdiag(ass, xs, **kwargs):
    '''
    Plots a bifurcation diagram of the Henon map.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    plot_args.update(markersize=0.2)
    axes.plot(ass, xs, 'k.', **plot_args)
    axes.set_xlabel('a')
    axes.set_ylabel('$x_n$')
    axes.set_title(opts.get('title', 'Bifurcation Diagram for the Henon Map'))

    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 15
0
def plot_time(ts, xs, **kwargs):
    '''
    Plots the specified vector in the time domain.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(ts, xs, '.', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_aspect(ts[-1] - ts[0])
    axes.set_xlabel('n')
    axes.set_ylabel(r'$x_n$')
    axes.set_title(opts.get('title', r'$x_n$'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 16
0
def plot_bifdiag(ass, xs, **kwargs):
    '''
    Plots a bifurcation diagram of the Henon map.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    plot_args.update(markersize=0.2)
    axes.plot(ass, xs, 'k.', **plot_args)
    axes.set_xlabel('a')
    axes.set_ylabel('$x_n$')
    axes.set_title(opts.get('title', 'Bifurcation Diagram for the Henon Map'))

    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 17
0
def render(x_start=1.0, y_start=0.5, size=1.0, iterations=13, **kwargs):
    '''
    Draws a neat fractal tree. 

    '''
    opts, plot_args = split_dict(('title', 'filename', 'ratio'), kwargs)
    render_color = opts.get('color', 'k')
    ratio = opts.get('ratio', 0.6)
    figure = matplotlib.pyplot.figure()

    def _iterate(axes, x_center, y_center, horizontal, size, iterations):
        '''
        Iterates the fractal tree over the axes.

        '''
        if iterations == 0:
            return

        halfsize = size / 2
        if horizontal:
            (x1, x2) = (x_center - halfsize, x_center + halfsize)
            (y1, y2) = (y_center, y_center)
        else:
            # Vertical
            (x1, x2) = (x_center, x_center)
            (y1, y2) = (y_center - halfsize, y_center + halfsize)

        axes.plot((x1, x2), (y1, y2), color=render_color, **plot_args)
        _iterate(axes, x1, y1, not horizontal, ratio * size, iterations - 1)
        _iterate(axes, x2, y2, not horizontal, ratio * size, iterations - 1)

    axes = figure.gca()
    axes.plot((x_start, x_start), (y_start - (size / 2), y_start + (size / 2)),
              color=render_color,
              **plot_args)
    _iterate(axes, x_start, y_start + (size / 2), True, 0.6 * size, iterations)
    axes.set_xbound((0.4, 1.6))
    axes.set_ybound((0.0, 1.4))
    axes.set_title(opts.get('title', 'Self-similar Fractal Tree'))

    if opts.get('filename') is not None:
        figure.savefig(opts['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 18
0
def plot_ret1(xs, **kwargs):
    '''
    Plots the Henon map in the first return map space.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    plot_args.update(markersize=0.2)

    axes.plot(xs[:,0], xs[:,1], '.', **plot_args)
    axes.set_xlabel('$x_n$')
    axes.set_ylabel('$y_n$')
    axes.set_title(opts.get('title', 'Henon Map'))

    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 19
0
def plot_time2(ts, xs1, xs2, **kwargs):
    '''
    Plots 2 vectors in the time domain.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(ts, xs1, 'b-o', **plot_args)
    axes.plot(ts, xs2, 'r-o', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_xlabel('n')
    axes.set_ylabel(r'$x_n$')
    axes.legend(('$x_0 = {0}$'.format(xs1[0]), '$x_0 = {0}$'.format(xs2[0])))
    axes.set_title(opts.get('title', r'$x_n$'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 20
0
def plot_time2(ts, xs1, xs2, **kwargs):
    '''
    Plots 2 vectors in the time domain.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(ts, xs1, 'b-o', **plot_args)
    axes.plot(ts, xs2, 'r-o', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_xlabel('n')
    axes.set_ylabel(r'$x_n$')
    axes.legend(('$x_0 = {0}$'.format(xs1[0]), '$x_0 = {0}$'.format(xs2[0])))
    axes.set_title(opts.get('title', r'$x_n$'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 21
0
def plot_ret1(xs, **kwargs):
    '''
    Plots the specified vector in the first return map space.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(xs[:-1], xs[1:], '.', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_xlim((0.0, 1.0))
    axes.set_aspect(1.0)
    axes.set_xlabel(r'$x_n$')
    axes.set_ylabel(r'$x_{n+1}$')
    axes.set_title(opts.get('title', 'First Return Map Space'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 22
0
def plot_ret1(xs, **kwargs):
    '''
    Plots the specified vector in the first return map space.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(['title', 'filename'], kwargs)
    axes.plot(xs[:-1], xs[1:], '.', **plot_args)
    axes.set_ylim((0.0, 1.0))
    axes.set_xlim((0.0, 1.0))
    axes.set_aspect(1.0)
    axes.set_xlabel(r'$x_n$')
    axes.set_ylabel(r'$x_{n+1}$')
    axes.set_title(opts.get('title', 'First Return Map Space'))
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 23
0
def plot_ret1(xs, **kwargs):
    '''
    Plots the Henon map in the first return map space.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    plot_args.update(markersize=0.2)

    axes.plot(xs[:, 0], xs[:, 1], '.', **plot_args)
    axes.set_xlabel('$x_n$')
    axes.set_ylabel('$y_n$')
    axes.set_title(opts.get('title', 'Henon Map'))

    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 24
0
def plot_bifdiag(rs, xs, **kwargs):
    '''
    Plots a bifurcation diagram given a data set of rs, xs.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict(('title', 'filename'), kwargs)
    plot_args.update(markersize=0.2)
    axes.plot(rs, xs, 'k.', **plot_args)
    axes.set_xlabel('R')
    axes.set_ylabel('$x_n$')
    axes.set_title(opts.get('title', 'Bifurcation Diagram for the Logistic Map'))

    # Check opts.get('filename') is not None instead of 'filename' in opts.
    # Expect callers to pass filename=None and show the plot to the screen.
    if opts.get('filename') is not None:
        figure.savefig(kwargs['filename'], dpi=220)
    else:
        figure.show()
Ejemplo n.º 25
0
def render_plot(ts, xs, *args, **kwargs):
    '''
    Renders a plot to the screen or to a file.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opts, plot_args = split_dict((
                            'xlabel', 'ylabel', 'mod2pi', 'title', 'file_prefix'
                        ), kwargs)
    title = opts.get('title', '$x(t)$')
    file_prefix = opts.get('file_prefix')
    modulo = opts.get('mod2pi', False)

    axes.plot(ts, xs, *args, **plot_args)
    axes.set_xlabel(opts.get('xlabel', 't'))
    axes.set_ylabel(opts.get('ylabel', 'x'))
    axes.set_title(title)

    if modulo:
        axes.set_xbound(0, 2*numpy.pi)
        axes.set_xticks((
                    0, 
                    numpy.pi/2,
                    numpy.pi,
                    3*numpy.pi/2,
                    2*numpy.pi
                ))
        axes.set_xticklabels((
                    '0',
                    r'$\frac{\pi}{2}$',
                    r'$\pi$',
                    r'$\frac{3\pi}{2}$',
                    r'$2\pi$'
                ))

    if file_prefix is None:
        figure.show()
    else:
        figure.savefig('{0}.png'.format(file_prefix), dpi=220)
Ejemplo n.º 26
0
def plot_pfunc(pfunc, *args, **kwargs):
    '''
    Convenience function for experimenting with pendulum functions.

    '''
    opts, plot_args = split_dict(('tstep', 'theta0', 'omega0', 'nsteps'), kwargs)
    theta0 = opts.get('theta0', 3.0)
    omega0 = opts.get('omega0', 0.1)
    tstep = opts.get('tstep', 0.005)
    nsteps = opts.get('nsteps', 2000)
    _, xs = rungekutta.rk4(
                        pfunc, 
                        0.0, 
                        numpy.array([theta0, omega0], dtype=numpy.float64),
                        tstep, 
                        nsteps
                    )
    fix_domain = lambda x: mod2pi(x) if kwargs.get('mod2pi', False) else x
    xs[0,:] = numpy.array([
                        fix_domain(theta) for theta in xs[0,:]
                    ], dtype=numpy.float64)
    render_plot(xs[0,:], xs[1,:], *args, **plot_args)
Ejemplo n.º 27
0
def plot3d(*args, **kwargs):
    '''
    Renders a 3D plot.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.add_subplot(111, projection='3d')
    opt_actions = (
        ('title', axes.set_title),
        ('xlabel', axes.set_xlabel),
        ('ylabel', axes.set_ylabel),
        ('zlabel', axes.set_zlabel),
        ('xticks', axes.set_xticks),
        ('yticks', axes.set_yticks),
        ('zticks', axes.set_zticks),
        ('xticklabels', axes.set_xticklabels),
        ('yticklabels', axes.set_yticklabels),
        ('zticklabels', axes.set_zticklabels),
        ('aspect', axes.set_aspect),
        ('xbound', lambda (x1, x2): axes.set_xbound(x1, x2)),
        ('ybound', lambda (y1, y2): axes.set_ybound(y1, y2)),
        ('zbound', lambda (z1, z2): axes.set_zbound(z1, z2)),
        ('file_prefix', _noop),
        ('ax_callback', _noop),
    )
    opts, plot_args = utils.split_dict([name for (name, _) in opt_actions],
                                       kwargs)

    if 'ax_callback' in opts:
        opts['ax_callback'](axes)
    else:
        axes.plot(*args, **plot_args)

    for (name, action) in opt_actions:
        if name in opts:
            action(opts[name])

    _render_to_output(figure, opts.get('file_prefix'))
Ejemplo n.º 28
0
def plot(*args, **kwargs):
    '''
    Renders a 2D plot.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opt_actions = (
        ('title', axes.set_title),
        ('xlabel', axes.set_xlabel),
        ('ylabel', axes.set_ylabel),
        ('xticks', axes.set_xticks),
        ('yticks', axes.set_yticks),
        ('xticklabels', axes.set_xticklabels),
        ('yticklabels', axes.set_yticklabels),
        ('aspect', axes.set_aspect),
        ('xbound', lambda (x1, x2): axes.set_xbound(x1, x2)),
        ('ybound', lambda (y1, y2): axes.set_ybound(y1, y2)),
        ('legend', axes.legend),
        ('file_prefix', _noop),
        ('ax_callback', _noop),
    )
    opts, plot_args = utils.split_dict([name for (name, _) in opt_actions],
                                       kwargs)

    if 'ax_callback' in opts:
        opts['ax_callback'](axes)
    else:
        axes.plot(*args, **plot_args)

    # Use tuples instead of a dict because order matters. Want to set xticks
    # before xlabels, etc.
    for (name, action) in opt_actions:
        if name in opts:
            action(opts[name])

    _render_to_output(figure, opts.get('file_prefix'))
Ejemplo n.º 29
0
def plot3d(*args, **kwargs):
    '''
    Renders a 3D plot.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.add_subplot(111, projection='3d')
    opt_actions = (
        ('title', axes.set_title),
        ('xlabel', axes.set_xlabel),
        ('ylabel', axes.set_ylabel),
        ('zlabel', axes.set_zlabel),
        ('xticks', axes.set_xticks),
        ('yticks', axes.set_yticks),
        ('zticks', axes.set_zticks),
        ('xticklabels', axes.set_xticklabels),
        ('yticklabels', axes.set_yticklabels),
        ('zticklabels', axes.set_zticklabels),
        ('aspect', axes.set_aspect),
        ('xbound', lambda (x1, x2): axes.set_xbound(x1, x2)),
        ('ybound', lambda (y1, y2): axes.set_ybound(y1, y2)),
        ('zbound', lambda (z1, z2): axes.set_zbound(z1, z2)),
        ('file_prefix', _noop),
        ('ax_callback', _noop),
    )
    opts, plot_args = utils.split_dict([name for (name, _) in opt_actions], kwargs)

    if 'ax_callback' in opts:
        opts['ax_callback'](axes)
    else:
        axes.plot(*args, **plot_args)

    for (name, action) in opt_actions:
        if name in opts:
            action(opts[name])

    _render_to_output(figure, opts.get('file_prefix'))
Ejemplo n.º 30
0
def plot(*args, **kwargs):
    '''
    Renders a 2D plot.

    '''
    figure = matplotlib.pyplot.figure()
    axes = figure.gca()
    opt_actions = (
        ('title', axes.set_title),
        ('xlabel', axes.set_xlabel),
        ('ylabel', axes.set_ylabel),
        ('xticks', axes.set_xticks),
        ('yticks', axes.set_yticks),
        ('xticklabels', axes.set_xticklabels),
        ('yticklabels', axes.set_yticklabels),
        ('aspect', axes.set_aspect),
        ('xbound', lambda (x1, x2): axes.set_xbound(x1, x2)),
        ('ybound', lambda (y1, y2): axes.set_ybound(y1, y2)),
        ('legend', axes.legend),
        ('file_prefix', _noop),
        ('ax_callback', _noop),
    )
    opts, plot_args = utils.split_dict([name for (name, _) in opt_actions], kwargs)

    if 'ax_callback' in opts:
        opts['ax_callback'](axes) 
    else:
        axes.plot(*args, **plot_args)

    # Use tuples instead of a dict because order matters. Want to set xticks
    # before xlabels, etc.
    for (name, action) in opt_actions:
        if name in opts:
            action(opts[name])

    _render_to_output(figure, opts.get('file_prefix'))