Beispiel #1
0
def rows(session, row_data, sample_id=None, group_id=None):
    """Handle rows of sambamba output.

    N.B. only handles single sample annotations.

    Args:
        session (Session): database session object
        row_data (List[dict]): parsed sambamba output rows
        sample_id (Optional[str]): id to reference sample
        group_id (Optional[str]): id to group samples together

    Yields:
        ExonStatistic: stats model linked to exon and sample
    """
    if sample_id is None:
        # use first row to get information on sample
        first_row = next(iter(row_data))
        sample_id = first_row['sampleName']
        # place the first row back in the stream
        all_data = cons(first_row, row_data)
    else:
        all_data = row_data

    exons = {exon.exon_id: exon.id for exon in session.query(Exon)}
    sample_obj = Sample(sample_id=sample_id, group_id=group_id)
    nested_stats = (row(session, data, sample_obj, exons) for data in all_data)
    # flatten 2D nested list
    return (stat for stats in nested_stats for stat in stats)
Beispiel #2
0
def rows(session, row_data, sample_id=None, group_id=None):
    """Handle rows of sambamba output.

    N.B. only handles single sample annotations.

    Args:
        session (Session): database session object
        row_data (dict): parsed sambamba output rows
        sample_id (Optional[str]): id to reference sample
        group_id (Optional[str]): id to group samples together

    Yields:
        ExonStatistic: stats model linked to exon and sample
    """
    if sample_id is None:
        # use first row to get information on sample
        first_row = next(iter(row_data))
        sample_id = first_row['sampleName']
        # place the first row back in the stream
        all_data = cons(first_row, row_data)
    else:
        all_data = row_data

    sample_obj = Sample(sample_id=sample_id, group_id=group_id)
    nested_stats = (row(session, data, sample_obj) for data in all_data)
    # flatten 2D nested list
    return (stat for stats in nested_stats for stat in stats)
Beispiel #3
0
def move(n: int, target_stack_index: int, context: Context,
         logs: List[str]) -> Tuple[Context, List[str]]:
    current_stack_index = where(n, context)
    current_stack = nth(current_stack_index, context)
    target_stack = nth(target_stack_index, context)
    untouched_stack_index = nth(
        0,
        set(range(3)) - {target_stack_index, current_stack_index})
    untouched_stack = nth(untouched_stack_index, context)

    if n == min(current_stack):
        if len(target_stack) == 0 or n < min(target_stack):
            _, *new_current_stack = current_stack
            new_target_stack = list(cons(n, target_stack))

            new_context = tuple(
                map(
                    lambda tup: nth(1, tup),
                    sorted(((target_stack_index, new_target_stack),
                            (current_stack_index, new_current_stack),
                            (untouched_stack_index, untouched_stack)))))

            log = (f"{index_to_name[current_stack_index]}" +
                   f" to {index_to_name[target_stack_index]}")
            new_logs = logs + [log]

            return new_context, new_logs
        else:
            new_context, new_logs = move(min(target_stack),
                                         untouched_stack_index, context, logs)
            return move(n, target_stack_index, new_context, new_logs)
    else:
        new_context, new_logs = move(min(current_stack), untouched_stack_index,
                                     context, logs)
        return move(n, target_stack_index, new_context, new_logs)
Beispiel #4
0
def render_tabular(api, options=None):
    """Entry point for the tabular reporter interface."""
    # determine separator
    separator = options.get('report.separator', '\t')
    human = options.get('report.human')
    panel = options.get('report.panel')
    samples = options.get('report.samples')
    group = options.get('report.group')

    # read gene panel file if it has been set
    if panel:
        superblock_ids = [line.rstrip() for line in panel]
    else:
        superblock_ids = None

    # get sample ID, group and cutoff from metadata
    sample_query = limit_query(api.samples(), group=group, samples=samples)
    metadata = ((sample.id, sample.group_id, sample.cutoff)
                for sample in sample_query)

    # get the data
    base_query = limit_query(
        api.average_metrics(superblock_ids=superblock_ids),
        group=group,
        samples=samples)

    queries = [
        metadata, base_query,
        api.diagnostic_yield(superblock_ids=superblock_ids,
                             group_id=group,
                             sample_ids=samples),
        api.sex_checker(group_id=group, sample_ids=samples)
    ]

    # group multiple queries by sample ID (first column)
    key_metrics = groupby(get(0), concat(queries))

    # get the column names dynamically from the query
    headers = concatv(['sample_id', 'group_id', 'cutoff'],
                      (column['name']
                       for column in base_query.column_descriptions),
                      ['diagnostic yield', 'gender'])

    unique_headers = unique(headers)

    # iterate over all values, concat different query results, and keep
    # only the unique values (excluding second sample_id)
    data = (unique(concat(values)) for values in itervalues(key_metrics))

    if human:
        # export key_metrics in a more human friendly format
        return tabulate(data, unique_headers)

    # yield headers
    return '\n'.join(
        cons('#' + separator.join(unique_headers),
             stringify_list(data, separator=separator)))
Beispiel #5
0
def run_features(args):
    """Run image feature computation.

    Parameters
    ----------
    args : argparse.Namespace
        The arguments parsed by the argparse library.
    """
    if args.global_threshold:
        images = map(io.imread, args.images)
        thresholds = pre.global_threshold(images, args.random_seed)
    else:
        thresholds = None
    images = map(io.imread, args.images)
    screen_info = screens.d[args.screen]
    index_function, fmap = screen_info['index'], screen_info['fmap']
    fmap = tz.partial(fmap,
                      threshold=thresholds,
                      sample_size=args.sample_size,
                      random_seed=args.random_seed)
    indices = list(map(index_function, args.images))
    f0, feature_names = fmap(next(images))
    feature_vectors = tz.cons(f0, (fmap(im)[0] for im in images))
    online_scaler = StandardScaler()
    online_pca = cluster.OnlineIncrementalPCA(n_components=args.n_components,
                                              batch_size=args.pca_batch_size)
    nimages, nfeatures = len(args.images), len(f0)
    emit = io.emitter_function(args.emitter)
    with temporary_hdf5_dataset((nimages, nfeatures), 'float') as dset:
        # First pass: compute the features, compute the mean and SD,
        # compute the PCA
        for i, (idx, v) in enumerate(zip(indices, feature_vectors)):
            emit({'_id': idx, 'feature_vector': list(v)})
            dset[i] = v
            online_scaler.partial_fit(v.reshape(1, -1))
            online_pca.add_sample(v)
        # Second pass: standardise the feature vectors, compute PCA-transform
        for i, (idx, v) in enumerate(zip(indices, dset)):
            v_std = online_scaler.transform(v)
            v_pca = online_pca.transform(v)
            dset[i] = v_std
            emit({
                '_id': idx,
                'feature_vector_std': list(v_std),
                'pca_vector': list(v_pca)
            })
            online_pca.transform(v)
        # Third pass: Compute the nearest neighbors graph.
        # THIS ANNOYINGLY INSTANTIATES FULL ARRAY -- no out-of-core
        # solution that I'm aware of...
        ng = neighbors.kneighbors_graph(dset,
                                        args.num_neighbours,
                                        include_self=False,
                                        mode='distance')
        for idx, row in zip(indices, ng):
            emit({'_id': idx, 'neighbours': [indices[i] for i in row.indices]})
Beispiel #6
0
def render_tabular(api, options=None):
  """Entry point for the tabular reporter interface."""
  # determine separator
  separator = options.get('report.separator', '\t')
  human = options.get('report.human')
  panel = options.get('report.panel')
  samples = options.get('report.samples')
  group = options.get('report.group')

  # read gene panel file if it has been set
  if panel:
    superblock_ids = [line.rstrip() for line in panel]
  else:
    superblock_ids = None

  # get sample ID, group and cutoff from metadata
  sample_query = limit_query(api.samples(), group=group, samples=samples)
  metadata = ((sample.id, sample.group_id, sample.cutoff)
              for sample in sample_query)

  # get the data
  base_query = limit_query(api.average_metrics(superblock_ids=superblock_ids),
                           group=group,
                           samples=samples)

  queries = [metadata,
             base_query,
             api.diagnostic_yield(superblock_ids=superblock_ids,
                                  group_id=group, sample_ids=samples),
             api.sex_checker(group_id=group, sample_ids=samples)]

  # group multiple queries by sample ID (first column)
  key_metrics = groupby(get(0), concat(queries))

  # get the column names dynamically from the query
  headers = concatv(['sample_id', 'group_id', 'cutoff'],
                    (column['name'] for column
                     in base_query.column_descriptions),
                    ['diagnostic yield', 'gender'])

  unique_headers = unique(headers)

  # iterate over all values, concat different query results, and keep
  # only the unique values (excluding second sample_id)
  data = (unique(concat(values)) for values in itervalues(key_metrics))

  if human:
    # export key_metrics in a more human friendly format
    return tabulate(data, unique_headers)

  # yield headers
  return '\n'.join(cons('#' + separator.join(unique_headers),
                        stringify_list(data, separator=separator)))
Beispiel #7
0
def test_actions_call_done_with_state_and_values():
    def f(a, b):
        return '%s%d' % (a, b)

    fl = lift(f)
    instructions = [fl(i) for i in range(randint(1, 1000))]

    run = actions(instructions, result)
    r = run('seed')

    expect = ''.join(cons('seed', [str(i) for i in range(len(instructions))]))

    assert r == expect
Beispiel #8
0
def run_features(args):
    """Run image feature computation.

    Parameters
    ----------
    args : argparse.Namespace
        The arguments parsed by the argparse library.
    """
    if args.global_threshold:
        images = map(io.imread, args.images)
        thresholds = pre.global_threshold(images, args.random_seed)
    else:
        thresholds = None
    images = map(io.imread, args.images)
    screen_info = screens.d[args.screen]
    index_function, fmap = screen_info['index'], screen_info['fmap']
    fmap = tz.partial(fmap, threshold=thresholds,
                            sample_size=args.sample_size,
                            random_seed=args.random_seed)
    indices = list(map(index_function, args.images))
    f0, feature_names = fmap(next(images))
    feature_vectors = tz.cons(f0, (fmap(im)[0] for im in images))
    online_scaler = StandardScaler()
    online_pca = cluster.OnlineIncrementalPCA(n_components=args.n_components,
                                              batch_size=args.pca_batch_size)
    nimages, nfeatures = len(args.images), len(f0)
    emit = io.emitter_function(args.emitter)
    with temporary_hdf5_dataset((nimages, nfeatures), 'float') as dset:
        # First pass: compute the features, compute the mean and SD,
        # compute the PCA
        for i, (idx, v) in enumerate(zip(indices, feature_vectors)):
            emit({'_id': idx, 'feature_vector': list(v)})
            dset[i] = v
            online_scaler.partial_fit(v.reshape(1, -1))
            online_pca.add_sample(v)
        # Second pass: standardise the feature vectors, compute PCA-transform
        for i, (idx, v) in enumerate(zip(indices, dset)):
            v_std = online_scaler.transform(v.reshape(1, -1))[0]
            v_pca = online_pca.transform(v)
            dset[i] = v_std
            emit({'_id': idx, 'feature_vector_std': list(v_std),
                              'pca_vector': list(v_pca)})
            online_pca.transform(v)
        # Third pass: Compute the nearest neighbors graph.
        # THIS ANNOYINGLY INSTANTIATES FULL ARRAY -- no out-of-core
        # solution that I'm aware of...
        ng = neighbors.kneighbors_graph(dset, args.num_neighbours,
                                        include_self=False, mode='distance')
        for idx, row in zip(indices, ng):
            emit({'_id': idx, 'neighbours': [indices[i] for i in row.indices]})
Beispiel #9
0
def compress(sexp):
  if sexp is None: return None
  if not isinstance(sexp, list): return sexp
  if all(not isinstance(x, list) for x in sexp): return sexp

  # if both heads are the same then gut the children.
  children = list(map(compress, sexp[1:]))
  heads = set(extract_op(x) for x in t.pluck(0, filter(lambda x: isinstance(x,list),children)))
  heads.add(extract_op(sexp[0]))
  # number heads are fine, we just want to make sure that the
  # string type heads are all the same
  if len(heads) <= 1:
    return list(t.cons(sexp[0], t.concat(x[1:] if isinstance(x,list) else [x]
                                         for x in children)))

  return [sexp[0]]+children
Beispiel #10
0
def clean_data(file, df, column_list, sample_size=None):
    """ Reformat dates and fix null values """

    df = make_sample(df, sample_size)

    # Add event time and adjust day format
    # TODO: Move to concat script
    df['day'] = df['day'].astype(str).map(fix_day)
    df['event_time'] = df['day'].map(lambda dy: arrow.get(dy).timestamp * 1000)
    df = df[list(cons('event_time', column_list))]

    # TOOD: Handle infinity values
    df = df.mask(df.isin([np.inf, -np.inf]))
    # df.replace([np.inf, -np.inf], np.nan)

    # TODO: Handle null values.  Setting to 0 until get way of handling nulls from Omar
    clean_columns = ['ads_per_video_cnt_avg', 'ad_vs_video_time_avg']
    df[clean_columns] = df[clean_columns].fillna(0.)
    return file, df
Beispiel #11
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()
Beispiel #12
0
        def _run(state):
            ans = fn(*cons(state, args), **kwargs)
            s = state_fn(state) if state_fn is not None else ans

            return {'answer': ans, 'state': s}
Beispiel #13
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()
Beispiel #14
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()
Beispiel #15
0
        def _run(state):
            ans = fn(*cons(state, args), **kwargs)
            s = state_fn(state) if state_fn is not None else ans

            return {'answer': ans, 'state': s}
Beispiel #16
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()
Beispiel #17
0
 def port(x):
     p = x[2].split(',')
     p1 = ['/'.join((x[1], y)) for y in p]
     return list(cons(x[0], p1))
Beispiel #18
0
def sieve(numbers):
    p = next(numbers)
    yield from cons(p, sieve(n for n in numbers if n % p > 0))
Beispiel #19
0
 def port(x):
     p = x[2].split(',')
     p1 = ['/'.join((x[1], y)) for y in p]
     return list(cons(x[0], p1))