Example #1
0
def main():
    """Entry point of application."""
    program_description = 'Harmonic oscillator'
    parser = argparse.ArgumentParser(program_description)
    parser.add_argument('--plot', help='plot best results', action='store_true')

    app, args = application.default_console_app(Individual, AssessmentRunner, parser=parser)
    app.run()

    logger = logging.getLogger(__name__)
    logger.info('\n')
    logger.info('Hall of Fame:')
    for individual in app.gp_runner.halloffame[:4]:
        logger.info('{}  {} = {}'.format(individual.fitness.values, repr(individual), str(individual)))

    if not args.plot:
        return
    # Plot n best results.
    import matplotlib.pyplot as plt
    import seaborn
    n = 4
    seaborn.set_palette('husl', n + 2)
    alpha = 0.75
    label_size = 16
    title_size = 20
    assessment_runner = AssessmentRunner()
    params, yinit = assessment_runner.params, assessment_runner.yinit
    x, target = assessment_runner.x, assessment_runner.target
    title = program_description + '\nparams={}, yinit={}'.format(params, yinit, fontsize=title_size)
    ax0 = plt.subplot2grid((2, 2), (0, 0))
    ax1 = plt.subplot2grid((2, 2), (1, 0))
    ax2 = plt.subplot2grid((2, 2), (1, 1))
    lines, labels = [], []
    l, = ax0.plot(x, target, alpha=alpha)
    labels.append('target')
    lines.append(l)
    for ind in reversed(app.gp_runner.halloffame[:n]):
        label = 'with $a(y_0, y_1) = {}$'.format(str(ind))
        label = label.replace('**', '^').replace('*', '\cdot ')
        y = assessment_runner.trajectory(ind)
        l, = ax0.plot(x, y[0, :], alpha=alpha)
        ax1.plot(x, y[1, :], alpha=alpha, color=l.get_color())
        ax2.plot(y[0, :], y[1, :], alpha=alpha, color=l.get_color())
        labels.append(label)
        lines.append(l)
    ax0.set_ylabel('$y_0$', fontsize=label_size)
    ax0.set_xlabel('time', fontsize=label_size)
    ax1.set_ylabel('$y_1$', fontsize=label_size)
    ax1.set_xlabel('time', fontsize=label_size)
    ax2.set_xlabel('$y_0$', fontsize=label_size)
    ax2.set_ylabel('$y_1$', fontsize=label_size)
    ax2.set_title('Phase Portrait', fontsize=label_size)
    plt.figlegend(lines, labels, loc='upper right', bbox_to_anchor=(0.9, 0.9), fontsize=label_size)
    plt.suptitle(title, fontsize=title_size)
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
    plt.show()
Example #2
0
def main():
    """Entry point of application."""
    program_description = 'Lorenz system'
    parser = argparse.ArgumentParser(program_description)
    parser.add_argument(
        '--params',
        type=utils.argparse.ntuple(3, float),
        default=(10, 28, 8 / 3),
        help='parameters σ,r,b for the lorenz system (default: 10,28,8/3)')
    parser.add_argument('--plot',
                        help='plot best results',
                        action='store_true')

    app, args = application.default_console_app(Individual, AssessmentRunner,
                                                parser)
    app.assessment_runner.params['s'] = args.params[0]
    app.assessment_runner.params['r'] = args.params[1]
    app.assessment_runner.params['b'] = args.params[2]
    app.run()

    logger = logging.getLogger(__name__)
    logger.info('\n')
    logger.info('Hall of Fame:')
    for individual in app.gp_runner.halloffame:
        logger.info('{}  {}'.format(individual.fitness.values,
                                    str(individual)))

    if not args.plot:
        return
    # Plot n best results.
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import seaborn
    n = 2
    seaborn.set_palette('husl', n + 2)
    alpha = 0.7
    label_size = 16
    title_size = 20
    params, yinit = app.assessment_runner.params, app.assessment_runner.yinit
    x, target = app.assessment_runner.x, app.assessment_runner.target
    title = program_description + '\nparams={}, yinit={}'.format(params, yinit)
    ax0 = plt.subplot2grid((3, 2), (0, 0))
    ax1 = plt.subplot2grid((3, 2), (1, 0))
    ax2 = plt.subplot2grid((3, 2), (2, 0))
    ax3 = plt.subplot2grid((3, 2), (1, 1), projection='3d', rowspan=2)
    lines, labels = [], []
    l, = ax0.plot(x, target, linestyle='dotted')
    ax1.plot(x, target, linestyle='dotted')
    ax2.plot(x, target, linestyle='dotted')
    labels.append('target')
    lines.append(l)
    uncontrolled = Individual.from_string('Add(y_0, Neg(y_0))')
    for ind in cons(uncontrolled, app.gp_runner.halloffame[:n]):
        popt = getattr(ind, 'popt', np.zeros(len(ind.pset.constants)))
        label = 'with $a({}) = {}$, $c={}$'.format(','.join(ind.pset.args),
                                                   str(ind), popt)
        label = label.replace('**', '^').replace('*', '\cdot ')
        y = app.assessment_runner.trajectory(ind, *popt)
        l, = ax0.plot(x, y[0, :], alpha=alpha)
        ax1.plot(x, y[1, :], alpha=alpha, color=l.get_color())
        ax2.plot(x, y[2, :], alpha=alpha, color=l.get_color())
        ax3.plot(y[0, :], y[1, :], y[2, :], alpha=alpha, color=l.get_color())
        labels.append(label)
        lines.append(l)
    ax0.set_ylabel('$y_0$', fontsize=label_size)
    ax0.set_xlabel('time', fontsize=label_size)
    ax1.set_ylabel('$y_1$', fontsize=label_size)
    ax1.set_xlabel('time', fontsize=label_size)
    ax2.set_ylabel('$y_2$', fontsize=label_size)
    ax2.set_xlabel('time', fontsize=label_size)
    ax3.set_xlabel('$y_0$', fontsize=label_size)
    ax3.set_ylabel('$y_1$', fontsize=label_size)
    ax3.set_title('Phase Portrait', fontsize=label_size)
    plt.figlegend(lines,
                  labels,
                  loc='upper right',
                  bbox_to_anchor=(0.9, 0.9),
                  fontsize=label_size)
    plt.suptitle(title, fontsize=title_size)
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
    plt.show()
Example #3
0
def main():
    """Entry point of application."""
    program_description = "Damped oscillator d²y/dt² = -k*y - c*dy/dt"
    parser = argparse.ArgumentParser(description=program_description)
    parser.add_argument(
        "--params",
        type=utils.argparse.ntuple(2, float),
        default=(3.0 / 8.0, 1.0),
        help="parameters c,k for the damped oscillator (default: 3/8,1)",
    )
    parser.add_argument("--plot",
                        help="plot best results",
                        action="store_true")

    app, args = application.default_console_app(Individual,
                                                AssessmentRunner,
                                                parser=parser)
    app.assessment_runner.params["c"] = app.args.params[0]
    app.assessment_runner.params["k"] = app.args.params[1]
    app.run()

    logger = logging.getLogger(__name__)
    logger.info("\n")
    logger.info("Hall of Fame:")
    for individual in app.gp_runner.pareto_front:
        popt = getattr(individual, "popt", ())
        logger.info("{}  {}, {} = {}".format(
            individual.fitness.values,
            str(individual),
            individual.pset.constants,
            popt,
        ))

    if not args.plot:
        return
    # Plot n best results.
    import matplotlib.pyplot as plt
    import seaborn

    n = 2
    seaborn.set_palette("husl", n + 2)
    alpha = 0.75
    label_size = 16
    title_size = 20
    assessment_runner = AssessmentRunner()
    params, yinit = assessment_runner.params, assessment_runner.yinit
    x, ampl, omega = (
        assessment_runner.x,
        assessment_runner.ampl,
        assessment_runner.omega,
    )
    title = program_description + "\nparams={}, yinit={}".format(
        params, yinit, fontsize=title_size)
    ax0 = plt.subplot2grid((2, 2), (0, 0))
    ax1 = plt.subplot2grid((2, 2), (1, 0))
    ax2 = plt.subplot2grid((2, 2), (1, 1))
    lines, labels = [], []
    target = (ampl * np.sin(omega * x), ampl * omega * np.cos(omega * x))
    (l, ) = ax2.plot(target[0], target[1], linestyle="dotted", alpha=alpha)
    ax0.plot(x,
             target[0],
             linestyle="dotted",
             alpha=alpha,
             color=l.get_color())
    ax1.plot(x,
             target[1],
             linestyle="dotted",
             alpha=alpha,
             color=l.get_color())
    labels.append("target")
    lines.append(l)
    uncontrolled = Individual.from_string("Add(y_0, Neg(y_0))")
    for ind in cons(uncontrolled, reversed(app.gp_runner.pareto_front[:n])):
        popt = getattr(ind, "popt", np.zeros(len(ind.pset.constants)))
        label = "with $a(y_0, y_1) = {}$, $c={}$".format(str(ind), popt)
        label = label.replace("**", "^").replace("*", "\cdot ")
        y = assessment_runner.trajectory(ind, *popt)
        (l, ) = ax0.plot(x, y[0, :], alpha=alpha)
        ax1.plot(x, y[1, :], alpha=alpha, color=l.get_color())
        ax2.plot(y[0, :], y[1, :], alpha=alpha, color=l.get_color())
        labels.append(label)
        lines.append(l)
    ax0.set_ylabel("$y_0$", fontsize=label_size)
    ax0.set_xlabel("time", fontsize=label_size)
    ax1.set_ylabel("$y_1$", fontsize=label_size)
    ax1.set_xlabel("time", fontsize=label_size)
    ax2.set_xlabel("$y_0$", fontsize=label_size)
    ax2.set_ylabel("$y_1$", fontsize=label_size)
    ax2.set_title("Phase Portrait", fontsize=label_size)
    plt.figlegend(lines,
                  labels,
                  loc="upper right",
                  bbox_to_anchor=(0.9, 0.9),
                  fontsize=label_size)
    plt.suptitle(title, fontsize=title_size)
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
    plt.show()
Example #4
0
def main():
    """Entry point of application."""
    program_description = 'Damped oscillator d²y/dt² = -k*y - c*dy/dt'
    parser = argparse.ArgumentParser(description=program_description)
    parser.add_argument(
        '--params',
        type=utils.argparse.ntuple(2, float),
        default=(3.0 / 8.0, 1.0),
        help='parameters c,k for the damped oscillator (default: 3/8,1)')
    parser.add_argument('--plot',
                        help='plot best results',
                        action='store_true')

    app, args = application.default_console_app(Individual,
                                                AssessmentRunner,
                                                parser=parser)
    app.assessment_runner.params['c'] = app.args.params[0]
    app.assessment_runner.params['k'] = app.args.params[1]
    app.run()

    logger = logging.getLogger(__name__)
    logger.info('\n')
    logger.info('Hall of Fame:')
    for individual in app.gp_runner.halloffame:
        popt = getattr(individual, 'popt', ())
        logger.info('{}  {}, {} = {}'.format(individual.fitness.values,
                                             str(individual),
                                             individual.pset.constants, popt))

    if not args.plot:
        return
    # Plot n best results.
    import matplotlib.pyplot as plt
    import seaborn
    n = 2
    seaborn.set_palette('husl', n + 2)
    alpha = 0.75
    label_size = 16
    title_size = 20
    assessment_runner = AssessmentRunner()
    params, yinit = assessment_runner.params, assessment_runner.yinit
    x, ampl, omega = assessment_runner.x, assessment_runner.ampl, assessment_runner.omega
    title = program_description + '\nparams={}, yinit={}'.format(
        params, yinit, fontsize=title_size)
    ax0 = plt.subplot2grid((2, 2), (0, 0))
    ax1 = plt.subplot2grid((2, 2), (1, 0))
    ax2 = plt.subplot2grid((2, 2), (1, 1))
    lines, labels = [], []
    target = (ampl * np.sin(omega * x), ampl * omega * np.cos(omega * x))
    l, = ax2.plot(target[0], target[1], linestyle='dotted', alpha=alpha)
    ax0.plot(x,
             target[0],
             linestyle='dotted',
             alpha=alpha,
             color=l.get_color())
    ax1.plot(x,
             target[1],
             linestyle='dotted',
             alpha=alpha,
             color=l.get_color())
    labels.append('target')
    lines.append(l)
    uncontrolled = Individual.from_string('Add(y_0, Neg(y_0))')
    for ind in cons(uncontrolled, reversed(app.gp_runner.halloffame[:n])):
        popt = getattr(ind, 'popt', np.zeros(len(ind.pset.constants)))
        label = 'with $a(y_0, y_1) = {}$, $c={}$'.format(str(ind), popt)
        label = label.replace('**', '^').replace('*', '\cdot ')
        y = assessment_runner.trajectory(ind, *popt)
        l, = ax0.plot(x, y[0, :], alpha=alpha)
        ax1.plot(x, y[1, :], alpha=alpha, color=l.get_color())
        ax2.plot(y[0, :], y[1, :], alpha=alpha, color=l.get_color())
        labels.append(label)
        lines.append(l)
    ax0.set_ylabel('$y_0$', fontsize=label_size)
    ax0.set_xlabel('time', fontsize=label_size)
    ax1.set_ylabel('$y_1$', fontsize=label_size)
    ax1.set_xlabel('time', fontsize=label_size)
    ax2.set_xlabel('$y_0$', fontsize=label_size)
    ax2.set_ylabel('$y_1$', fontsize=label_size)
    ax2.set_title('Phase Portrait', fontsize=label_size)
    plt.figlegend(lines,
                  labels,
                  loc='upper right',
                  bbox_to_anchor=(0.9, 0.9),
                  fontsize=label_size)
    plt.suptitle(title, fontsize=title_size)
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
    plt.show()
Example #5
0
def main():
    """Entry point of application."""
    program_description = "Lorenz system"
    parser = argparse.ArgumentParser(program_description)
    parser.add_argument(
        "--params",
        type=utils.argparse.ntuple(3, float),
        default=(10, 28, 8 / 3),
        help="parameters σ,r,b for the lorenz system (default: 10,28,8/3)",
    )
    parser.add_argument("--plot",
                        help="plot best results",
                        action="store_true")

    app, args = application.default_console_app(Individual, AssessmentRunner,
                                                parser)
    app.assessment_runner.params["s"] = args.params[0]
    app.assessment_runner.params["r"] = args.params[1]
    app.assessment_runner.params["b"] = args.params[2]
    app.run()

    logger = logging.getLogger(__name__)
    logger.info("\n")
    logger.info("Hall of Fame:")
    for individual in app.gp_runner.pareto_front:
        logger.info("{}  {}".format(individual.fitness.values,
                                    str(individual)))

    if not args.plot:
        return
    # Plot n best results.
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import seaborn

    n = 2
    seaborn.set_palette("husl", n + 2)
    alpha = 0.7
    label_size = 16
    title_size = 20
    params, yinit = app.assessment_runner.params, app.assessment_runner.yinit
    x, target = app.assessment_runner.x, app.assessment_runner.target
    title = program_description + "\nparams={}, yinit={}".format(params, yinit)
    ax0 = plt.subplot2grid((3, 2), (0, 0))
    ax1 = plt.subplot2grid((3, 2), (1, 0))
    ax2 = plt.subplot2grid((3, 2), (2, 0))
    ax3 = plt.subplot2grid((3, 2), (1, 1), projection="3d", rowspan=2)
    lines, labels = [], []
    (l, ) = ax0.plot(x, target, linestyle="dotted")
    ax1.plot(x, target, linestyle="dotted")
    ax2.plot(x, target, linestyle="dotted")
    labels.append("target")
    lines.append(l)
    uncontrolled = Individual.from_string("Add(y_0, Neg(y_0))")
    for ind in cons(uncontrolled, app.gp_runner.pareto_front[:n]):
        popt = getattr(ind, "popt", np.zeros(len(ind.pset.constants)))
        label = "with $a({}) = {}$, $c={}$".format(",".join(ind.pset.args),
                                                   str(ind), popt)
        label = label.replace("**", "^").replace("*", "\cdot ")
        y = app.assessment_runner.trajectory(ind, *popt)
        (l, ) = ax0.plot(x, y[0, :], alpha=alpha)
        ax1.plot(x, y[1, :], alpha=alpha, color=l.get_color())
        ax2.plot(x, y[2, :], alpha=alpha, color=l.get_color())
        ax3.plot(y[0, :], y[1, :], y[2, :], alpha=alpha, color=l.get_color())
        labels.append(label)
        lines.append(l)
    ax0.set_ylabel("$y_0$", fontsize=label_size)
    ax0.set_xlabel("time", fontsize=label_size)
    ax1.set_ylabel("$y_1$", fontsize=label_size)
    ax1.set_xlabel("time", fontsize=label_size)
    ax2.set_ylabel("$y_2$", fontsize=label_size)
    ax2.set_xlabel("time", fontsize=label_size)
    ax3.set_xlabel("$y_0$", fontsize=label_size)
    ax3.set_ylabel("$y_1$", fontsize=label_size)
    ax3.set_title("Phase Portrait", fontsize=label_size)
    plt.figlegend(lines,
                  labels,
                  loc="upper right",
                  bbox_to_anchor=(0.9, 0.9),
                  fontsize=label_size)
    plt.suptitle(title, fontsize=title_size)
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
    plt.show()