示例#1
0
def get_response_content(fs):
    f_info = ctmcmi.get_mutual_info_known_distn
    # define the R table headers
    headers = ['log.probability.ratio', 'mutual.information']
    # make the array
    arr = []
    for x in np.linspace(fs.x_min, fs.x_max, 101):
        row = [x]
        proc = evozoo.AlternatingHypercube_d_1(3)
        X = np.array([x])
        distn = proc.get_distn(X)
        Q = proc.get_rate_matrix(X)
        info = f_info(Q, distn, fs.t)
        row.append(info)
        arr.append(row)
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#2
0
def get_response_content(fs):
    # validate and store user input
    if fs.x_max <= fs.x_min:
        raise ValueError('check the min and max logs')
    f_info = divtime.get_fisher_info_known_distn_fast
    # define the R table headers
    headers = ['log.probability.ratio', 'fisher.information']
    # make the array
    arr = []
    for x in np.linspace(fs.x_min, fs.x_max, 101):
        row = [x]
        proc = evozoo.DistinguishedCornerPairHypercube_d_1(3)
        X = np.array([x])
        distn = proc.get_distn(X)
        Q = proc.get_rate_matrix(X)
        info = f_info(Q, distn, fs.t)
        row.append(info)
        arr.append(row)
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#3
0
def main(args):
    # get the end positions,
    # forcing the first end position to be 5
    # and the last end position to be 898.
    incr = (g_nchar - 5) / float(args.nlengths - 1)
    stop_positions = [5 + int(i * incr) for i in range(args.nlengths)]
    stop_positions[-1] = g_nchar
    # run BEAST and create the R stuff
    table_string, scripts = get_table_string_and_scripts(
        stop_positions, args.nsamples)
    # create the comboscript
    out = StringIO()
    print >> out, 'library(ggplot2)'
    print >> out, 'par(mfrow=c(3,1))'
    for script in scripts:
        print >> out, script
    comboscript = out.getvalue()
    # create the R output image
    device_name = Form.g_imageformat_to_r_function['pdf']
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, comboscript, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    # write the image data
    with open(args.outfile, 'wb') as fout:
        fout.write(image_data)
示例#4
0
def get_response_content(fs):
    M, R = get_input_matrices(fs)
    # create the R table string and scripts
    headers = [
        't', 'mi.true.mut', 'mi.true.mutsel', 'mi.analog.mut',
        'mi.analog.mutsel'
    ]
    npoints = 100
    t_low = 0.0
    t_high = 5.0
    t_incr = (t_high - t_low) / (npoints - 1)
    t_values = [t_low + t_incr * i for i in range(npoints)]
    # get the data for the R table
    arr = []
    for t in t_values:
        mi_mut = ctmcmi.get_mutual_information(M, t)
        mi_mutsel = ctmcmi.get_mutual_information(R, t)
        mi_analog_mut = ctmcmi.get_ll_ratio_wrong(M, t)
        mi_analog_mutsel = ctmcmi.get_ll_ratio_wrong(R, t)
        row = [t, mi_mut, mi_mutsel, mi_analog_mut, mi_analog_mutsel]
        arr.append(row)
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#5
0
def get_response_content(fs):
    # precompute some transition matrices
    P_drift_selection = pgmsinglesite.create_drift_selection_transition_matrix(
        fs.npop, fs.selection_ratio)
    MatrixUtil.assert_transition_matrix(P_drift_selection)
    P_mutation = pgmsinglesite.create_mutation_transition_matrix(
        fs.npop, fs.mutation_ab, fs.mutation_ba)
    MatrixUtil.assert_transition_matrix(P_mutation)
    # define the R table headers
    headers = ['generation', 'number.of.mutants']
    # compute the path samples
    P = np.dot(P_drift_selection, P_mutation)
    mypath = PathSampler.sample_endpoint_conditioned_path(
        fs.nmutants_initial, fs.nmutants_final, fs.ngenerations, P)
    arr = [[i, nmutants] for i, nmutants in enumerate(mypath)]
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#6
0
def get_latex_documentbody(fs):
    """
    This is obsolete because I am now using pure R output.
    The latex documentbody should have a bunch of tikz pieces in it.
    Each tikz piece should have been generated from R.
    """
    Q_mut, Q_sels = get_qmut_qsels(fs)
    # compute the statistics
    ER_ratios, NSR_ratios, ER_NSR_ratios = get_statistic_ratios(Q_mut, Q_sels)
    M = zip(*(ER_ratios, NSR_ratios, ER_NSR_ratios))
    column_headers = ('ER.ratio', 'NSR.ratio', 'ER.times.NSR.ratio')
    table_string = RUtil.get_table_string(M, column_headers)
    nsels = len(Q_sels)
    # define the R scripts
    scripts = []
    for name in column_headers:
        scripts.append(get_r_tikz_script(nsels, name))
    # get the tikz codes from R, for each histogram
    retcode, r_out, r_err, tikz_code_list = RUtil.run_plotter_multiple_scripts(
        table_string, scripts, 'tikz', width=3, height=2)
    if retcode:
        raise RUtil.RError(r_err)
    #
    # show some timings
    print 'R did not fail, but here is its stderr:'
    print r_err
    #
    # write the latex code
    out = StringIO()
    #print >> out, '\\pagestyle{empty}'
    for tikz_code in tikz_code_list:
        print >> out, tikz_code
    # return the latex code, consisting mainly of a bunch of tikz plots
    return out.getvalue()
示例#7
0
def main(args):
    # set up the logger
    f = logging.getLogger('toplevel.logger')
    h = logging.StreamHandler()
    h.setFormatter(logging.Formatter('%(message)s %(asctime)s'))
    f.addHandler(h)
    if args.verbose:
        f.setLevel(logging.DEBUG)
    else:
        f.setLevel(logging.WARNING)
    f.info('(local) permute columns of the alignment')
    header_seq_pairs = beasttut.get_456_col_permuted_header_seq_pairs()
    f.info('(local) run BEAST serially locally and build the R stuff')
    table_string, scripts = get_table_string_and_scripts(
            g_start_stop_pairs, args.nsamples, header_seq_pairs)
    f.info('(local) create the composite R script')
    out = StringIO()
    print >> out, 'library(ggplot2)'
    print >> out, 'par(mfrow=c(3,1))'
    for script in scripts:
        print >> out, script
    comboscript = out.getvalue()
    f.info('(local) run R to create the pdf')
    device_name = Form.g_imageformat_to_r_function['pdf']
    retcode, r_out, r_err, image_data = RUtil.run_plotter( 
        table_string, comboscript, device_name, keep_intermediate=True) 
    if retcode: 
        raise RUtil.RError(r_err) 
    f.info('(local) write the .pdf file')
    with open(args.outfile, 'wb') as fout:
        fout.write(image_data)
    f.info('(local) return from toplevel')
示例#8
0
def get_r_tikz_stub():
    user_script = RUtil.g_stub
    device_name = 'tikz'
    retcode, r_out, r_err, tikz_code = RUtil.run_plotter_no_table(
            user_script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return tikz_code
示例#9
0
def get_response_content(fs):
    f_info = divtime.get_fisher_info_known_distn_fast
    requested_triples = []
    for triple in g_process_triples:
        name, desc, zoo_obj = triple
        if getattr(fs, name):
            requested_triples.append(triple)
    if not requested_triples:
        raise ValueError('nothing to plot')
    # define the R table headers
    r_names = [a.replace('_', '.') for a, b, c in requested_triples]
    headers = ['t'] + r_names
    # Spend a lot of time doing the optimizations
    # to construct the points for the R table.
    arr = []
    for t in cbreaker.throttled(progrid.gen_binary(fs.start_time,
                                                   fs.stop_time),
                                nseconds=5,
                                ncount=200):
        row = [t]
        for python_name, desc, zoo_class in requested_triples:
            zoo_obj = zoo_class(fs.d)
            df = zoo_obj.get_df()
            opt_dep = OptDep(zoo_obj, t, f_info)
            if df:
                X0 = np.random.randn(df)
                xopt = scipy.optimize.fmin(opt_dep,
                                           X0,
                                           maxiter=10000,
                                           maxfun=10000)
                # I would like to use scipy.optimize.minimize
                # except that this requires a newer version of
                # scipy than is packaged for ubuntu right now.
                # fmin_bfgs seems to have problems sometimes
                # either hanging or maxiter=10K is too big.
                """
                xopt = scipy.optimize.fmin_bfgs(opt_dep, X0,
                        gtol=1e-8, maxiter=10000)
                """
            else:
                xopt = np.array([])
            info_value = -opt_dep(xopt)
            row.append(info_value)
        arr.append(row)
    arr.sort()
    npoints = len(arr)
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#10
0
def get_response_content(fs):
    # legend labels
    label_a = 'N=%d mu=%f' % (fs.nstates_a, fs.mu_a)
    label_b = 'N=%d mu=%f' % (fs.nstates_b, fs.mu_b)
    arr, headers = make_table(fs)
    # compute the max value
    ymax = math.log(max(fs.nstates_a, fs.nstates_b))
    nfifths = int(math.floor(ymax * 5.0)) + 1
    ylim = RUtil.mk_call_str('c', 0, 0.2 * nfifths)
    # write the R script body
    out = StringIO()
    print >> out, RUtil.mk_call_str(
        'plot',
        'my.table$t',
        'my.table$alpha',
        type='"n"',
        ylim=ylim,
        xlab='"time"',
        ylab='"information"',
        main='"comparison of an information criterion for two processes"',
    )
    # draw some horizontal lines
    for i in range(nfifths + 1):
        print >> out, RUtil.mk_call_str('abline',
                                        h=0.2 * i,
                                        col='"lightgray"',
                                        lty='"dotted"')
    colors = ('darkblue', 'darkred')
    for c, header in zip(colors, headers[1:]):
        print >> out, RUtil.mk_call_str(
            'lines',
            'my.table$t',
            'my.table$%s' % header,
            col='"%s"' % c,
        )
    legend_names = (label_a, label_b)
    legend_name_str = 'c(' + ', '.join('"%s"' % s for s in legend_names) + ')'
    legend_col_str = 'c(' + ', '.join('"%s"' % s for s in colors) + ')'
    legend_lty_str = 'c(' + ', '.join('1' for s in colors) + ')'
    print >> out, RUtil.mk_call_str(
        'legend',
        '"%s"' % fs.legend_placement,
        legend_name_str,
        col=legend_col_str,
        lty=legend_lty_str,
    )
    script_body = out.getvalue()
    # create the R plot image
    table_string = RUtil.get_table_string(arr, headers)
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script_body, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#11
0
def get_response_content(fs):
    distn_modes = [x for x in g_ordered_modes if x in fs.distribution]
    if not distn_modes:
        raise ValueError('no distribution mode was specified')
    colors = [g_mode_to_color[m] for m in distn_modes]
    arr, headers = make_table(fs, distn_modes)
    distn_headers = headers[1:]
    # Get the largest value in the array,
    # skipping the first column.
    arrmax = np.max(arr[:, 1:])
    # write the R script body
    out = StringIO()
    ylim = RUtil.mk_call_str('c', 0, arrmax + 0.1)
    sel_str = {
        BALANCED: 'balanced',
        HALPERN_BRUNO: 'Halpern-Bruno',
    }[fs.selection]
    print >> out, RUtil.mk_call_str(
        'plot',
        'my.table$t',
        'my.table$%s' % distn_headers[0],
        type='"n"',
        ylim=ylim,
        xlab='""',
        ylab='"relaxation time"',
        main='"Effect of selection (%s) on relaxation time for %d states"' %
        (sel_str, fs.nstates),
    )
    for c, header in zip(colors, distn_headers):
        print >> out, RUtil.mk_call_str(
            'lines',
            'my.table$t',
            'my.table$%s' % header,
            col='"%s"' % c,
        )
    mode_names = [s.replace('_', ' ') for s in distn_modes]
    legend_name_str = 'c(' + ', '.join('"%s"' % s for s in mode_names) + ')'
    legend_col_str = 'c(' + ', '.join('"%s"' % s for s in colors) + ')'
    legend_lty_str = 'c(' + ', '.join(['1'] * len(distn_modes)) + ')'
    print >> out, RUtil.mk_call_str(
        'legend',
        '"%s"' % fs.legend_placement,
        legend_name_str,
        col=legend_col_str,
        lty=legend_lty_str,
    )
    script_body = out.getvalue()
    # create the R plot image
    table_string = RUtil.get_table_string(arr, headers)
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script_body, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#12
0
def get_response_content(fs):
    # define some fixed values
    N_diploid = 10
    N_hap = 2 * N_diploid
    #Nr = fs.Nr
    plot_density = 2
    # define some mutation rates
    theta_values = [0.001, 0.01, 0.1, 1.0]
    # define some selection coefficients to plot
    Ns_low = 0.0
    Ns_high = 3.0
    Ns_values = np.linspace(Ns_low, Ns_high, 3 * plot_density + 1)
    # get the values for each h
    Nr_values = (0, 5)
    arr_0 = get_plot_array(N_diploid, Nr_values[0], theta_values, Ns_values)
    arr_1 = get_plot_array(N_diploid, Nr_values[1], theta_values, Ns_values)
    if fs.scale_to_2N_200:
        arr_0 = (200 / float(N_hap)) * np.array(arr_0)
        arr_1 = (200 / float(N_hap)) * np.array(arr_1)
        ylab = '"generations * theta * (200 / 2N)"'
    else:
        ylab = '"generations * theta"'
    # define x and y plot limits
    xlim = (Ns_low, Ns_high)
    ylim = (np.min((arr_0, arr_1)), np.max((arr_0, arr_1)))
    if fs.ylogscale:
        ylogstr = '"y"'
    else:
        ylogstr = '""'
    # http://sphaerula.com/legacy/R/multiplePlotFigure.html
    out = StringIO()
    print >> out, mk_call_str(
        'par',
        mfrow='c(1,2)',
        oma='c(0,0,2,0)',
    )
    print >> out, get_plot('left', Nr_values[0], arr_0, theta_values,
                           Ns_values, xlim, ylim, ylogstr, ylab)
    print >> out, get_plot('right', Nr_values[1], arr_1, theta_values,
                           Ns_values, xlim, ylim, ylogstr, '""')
    print >> out, mk_call_str(
        'title',
        '"mean hitting time, 2N=%s"' % N_hap,
        outer='TRUE',
    )
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#13
0
def main(args):
    # check args
    if gmpy.popcount(args.ntiles) != 1:
        raise ValueError('the number of tiles should be a power of two')
    # set up the logger
    f = logging.getLogger('toplevel.logger')
    h = logging.StreamHandler()
    h.setFormatter(logging.Formatter('%(message)s %(asctime)s'))
    f.addHandler(h)
    if args.verbose:
        f.setLevel(logging.DEBUG)
    else:
        f.setLevel(logging.WARNING)
    f.info('(local) read the xml contents')
    if args.infile is None:
        xmldata = sys.stdin.read()
    else:
        with open(args.infile) as fin:
            xmldata = fin.read()
    f.info('(local) modify the log filename and chain length xml contents')
    xmldata = beast.set_nsamples(xmldata, args.mcmc_id, args.nsamples)
    xmldata = beast.set_log_filename(xmldata, args.log_id, args.log_filename)
    xmldata = beast.set_log_logevery(xmldata, args.log_id, args.log_logevery)
    f.info('(local) define the hierarchically nested intervals')
    start_stop_pairs = tuple(
        (a + 1, b) for a, b in beasttiling.gen_hierarchical_slices(
            args.tile_width, args.offset, args.tile_width * args.ntiles))
    f.info('(local) run BEAST serially locally and build the R stuff')
    table_string, full_table_string, scripts = get_table_strings_and_scripts(
        xmldata, args.alignment_id, start_stop_pairs, args.nsamples)
    if args.full_table_out:
        f.info('(local) create the verbose R table')
        with open(args.full_table_out, 'w') as fout:
            fout.write(full_table_string)
    f.info('(local) create the composite R script')
    out = StringIO()
    print >> out, 'library(ggplot2)'
    print >> out, 'par(mfrow=c(3,1))'
    for script in scripts:
        print >> out, script
    comboscript = out.getvalue()
    f.info('(local) run R to create the pdf')
    device_name = Form.g_imageformat_to_r_function['pdf']
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, comboscript, device_name, keep_intermediate=True)
    if retcode:
        raise RUtil.RError(r_err)
    f.info('(local) write the .pdf file')
    with open(args.outfile, 'wb') as fout:
        fout.write(image_data)
    f.info('(local) return from toplevel')
示例#14
0
def get_latex_documentbody(fs):
    """
    This is obsolete.
    """
    out = StringIO()
    table_string, scripts = get_table_string_and_scripts(fs)
    for script in scripts:
        retcode, r_out, r_err, tikz_code = RUtil.run_plotter(
                table_string, script, 'tikz',
                width=5, height=5)
        if retcode:
            raise RUtil.RError(r_err)
        print >> out, tikz_code
    return out.getvalue()
示例#15
0
def get_response_content(fs):
    # get the table string and scripts
    table_string, scripts = get_table_string_and_scripts(fs)
    # create a comboscript
    out = StringIO()
    print >> out, 'par(mfrow=c(3,1))'
    for script in scripts:
        print >> out, script
    comboscript = out.getvalue()
    # create the R plot image 
    device_name = Form.g_imageformat_to_r_function[fs.imageformat] 
    retcode, r_out, r_err, image_data = RUtil.run_plotter( 
        table_string, comboscript, device_name) 
    if retcode: 
        raise RUtil.RError(r_err) 
    return image_data 
示例#16
0
def get_response_content(fs):
    Q_mut, Q_sels = get_qmut_qsels(fs)
    # compute the statistics
    ER_ratios, NSR_ratios, ER_NSR_ratios = get_statistic_ratios(Q_mut, Q_sels)
    M = zip(*(ER_ratios, NSR_ratios, ER_NSR_ratios))
    column_headers = ('ER.ratio', 'NSR.ratio', 'ER.times.NSR.ratio')
    table_string = RUtil.get_table_string(M, column_headers)
    nsels = len(Q_sels)
    # get the R script
    comboscript = get_r_comboscript(nsels, column_headers)
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, comboscript, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#17
0
def get_response_content(fs):
    f_info = ctmcmi.get_mutual_info_known_distn
    requested_triples = []
    for triple in g_process_triples:
        name, desc, zoo_obj = triple
        if getattr(fs, name):
            requested_triples.append(triple)
    if not requested_triples:
        raise ValueError('nothing to plot')
    # define the R table headers
    headers = ['t']
    if fs.log4:
        headers.append('log.4')
    if fs.log3:
        headers.append('log.3')
    r_names = [a.replace('_', '.') for a, b, c in requested_triples]
    headers.extend(r_names)
    # Spend a lot of time doing the optimizations
    # to construct the points for the R table.
    times = np.linspace(fs.start_time, fs.stop_time, 101)
    arr = []
    for t in times:
        row = [t]
        if fs.log4:
            row.append(math.log(4))
        if fs.log3:
            row.append(math.log(3))
        for python_name, desc, zoo_obj in requested_triples:
            X = np.array([])
            info_value = f_info(zoo_obj.get_rate_matrix(X),
                                zoo_obj.get_distn(X), t)
            row.append(info_value)
        arr.append(row)
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#18
0
def main(args):
    # set up the logger
    f = logging.getLogger('toplevel.logger')
    h = logging.StreamHandler()
    h.setFormatter(logging.Formatter('%(message)s %(asctime)s'))
    f.addHandler(h)
    if args.verbose:
        f.setLevel(logging.DEBUG)
    else:
        f.setLevel(logging.WARNING)
    if args.run == 'hpc':
        r = RemoteBeast(g_start_stop_pairs, args.nsamples)
        f.info('run BEAST remotely')
        r.run(verbose=args.verbose)
        f.info('(local) build the R table string and scripts')
        table_string, scripts = beasttut.get_table_string_and_scripts_from_logs(
            g_start_stop_pairs, r.local_log_paths, args.nsamples)

    elif args.run == 'serial':
        f.info('(local) run BEAST serially locally and build the R stuff')
        table_string, scripts = beasttut.get_table_string_and_scripts(
            g_start_stop_pairs, args.nsamples)
    elif args.run == 'parallel':
        f.info('(local) run BEAST locally in parallel and build the R stuff')
        table_string, scripts = beasttut.get_table_string_and_scripts_par(
            g_start_stop_pairs, args.nsamples)
    else:
        raise ValueError('invalid execution model')
    f.info('(local) create the composite R script')
    out = StringIO()
    print >> out, 'library(ggplot2)'
    print >> out, 'par(mfrow=c(3,1))'
    for script in scripts:
        print >> out, script
    comboscript = out.getvalue()
    f.info('(local) run R to create the pdf')
    device_name = Form.g_imageformat_to_r_function['pdf']
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, comboscript, device_name, keep_intermediate=True)
    if retcode:
        raise RUtil.RError(r_err)
    f.info('(local) write the .pdf file')
    with open(args.outfile, 'wb') as fout:
        fout.write(image_data)
    f.info('(local) return from toplevel')
示例#19
0
def get_response_content(fs):
    # define the initial frequency
    p = 0.8
    # define some selection coefficients to plot
    low = -5
    high = 5
    s_values = np.linspace(low, high, (high - low) * 20 + 1)
    # define some dominance coefficients
    h_values = [2, 3, 5, 7]
    # get the values for each h
    arr = []
    for h in h_values:
        v = [kimura.get_fixation_probability_chen(p, s, h) for s in s_values]
        arr.append(v)
    #
    # define the r script
    out = StringIO()
    print >> out, 'title.string <- "my title"'
    print >> out, 's.values <- c', str(tuple(s_values))
    print >> out, 'ha <- c', str(tuple(arr[0]))
    print >> out, 'hb <- c', str(tuple(arr[1]))
    print >> out, 'hc <- c', str(tuple(arr[2]))
    print >> out, 'hd <- c', str(tuple(arr[3]))
    print >> out, mk_call_str(
        'plot',
        's.values',
        'ha',
        type='"l"',
        xlab='"selection coefficient (s)"',
        ylab='"probability of eventual fixation"',
        main='"fixation probabilities for various h ; p0 = 0.8"',
        ylim='c(0.5,1)',
    )
    print >> out, mk_call_str('lines', 's.values', 'hb', col='"red"')
    print >> out, mk_call_str('lines', 's.values', 'hc', col='"green"')
    print >> out, mk_call_str('lines', 's.values', 'hd', col='"blue"')
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#20
0
def get_response_content(fs):
    # create the R table string and scripts
    headers = ['entropy', 'analog']
    distributions = []
    nstates = 4
    npoints = 5000
    arr = []
    best_pair = None
    for i in range(npoints):
        weights = [random.expovariate(1) for j in range(nstates)]
        total = sum(weights)
        distn = [x / total for x in weights]
        entropy = -sum(p * math.log(p) for p in distn)
        sum_squares = sum(p * p for p in distn)
        sum_cubes = sum(p * p * p for p in distn)
        analog = math.log(sum_squares / sum_cubes)
        row = [entropy, analog]
        arr.append(row)
        dist = (entropy - 1.0)**2 + (analog - 0.4)**2
        if (best_pair is None) or (dist < best_pair[0]):
            best_pair = (dist, distn)
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    out = StringIO()
    title = ', '.join(str(x) for x in best_pair[1])
    print >> out, RUtil.mk_call_str('plot',
                                    'my.table$entropy',
                                    'my.table$analog',
                                    pch='20',
                                    main='"%s"' % title)
    script = out.getvalue()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#21
0
def get_response_content(fs):
    # create the R table string and scripts
    headers = [
        'z',
        'c.neg2.0',
        'c.neg0.5',
        'c.0.5',
        'c.2.0',
        #'c.a',
        #'c.b',
        #'c.c',
        #'c.d',
    ]
    #C = numpy.array([-0.5, -0.2, 0.2, 0.5], dtype=float)
    #C = numpy.array([-1.0, -0.4, 0.4, 1.0], dtype=float)
    C = numpy.array([-2.0, -0.5, 0.5, 2.0], dtype=float)
    Z = numpy.linspace(-5, 5, 101)
    # get the data for the R table
    arr = []
    for z in Z:
        row = [z]
        for c in C:
            rate = 1.0 / kimrecessive.denom_piecewise(c, z * numpy.sign(c))
            row.append(rate)
        arr.append(row)
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#22
0
def get_response_content(fs):
    #
    N_diploid = 10
    N_haploid = 2 * N_diploid
    t1_20_exact = get_t1_exact(N_diploid)
    t1_20_approx = get_t1_approx(N_diploid)
    proportions_20 = np.linspace(0.0, 1.0, 2 * N_diploid + 1)[1:]
    #
    N_diploid = 5
    N_haploid = 2 * N_diploid
    t1_10_exact = get_t1_exact(N_diploid)
    t1_10_approx = get_t1_approx(N_diploid)
    proportions_10 = np.linspace(0.0, 1.0, 2 * N_diploid + 1)[1:]
    #
    # define the r script
    out = StringIO()
    print >> out, 'title.string <- "my title"'
    print >> out, 't1.20.approx <- c', str(tuple(t1_20_approx))
    print >> out, 't1.20.exact <- c', str(tuple(t1_20_exact))
    print >> out, 'p.20 <- c', str(tuple(proportions_20.tolist()))
    print >> out, mk_call_str('plot',
                              'p.20',
                              't1.20.approx',
                              col='"red"',
                              type='"l"',
                              ylim='c(0,45)',
                              xaxp='c(0,1,10)')
    print >> out, mk_call_str('points', 'p.20', 't1.20.exact', col='"blue"')
    #
    print >> out, 't1.10.approx <- c', str(tuple(t1_10_approx))
    print >> out, 't1.10.exact <- c', str(tuple(t1_10_exact))
    print >> out, 'p.10 <- c', str(tuple(proportions_10.tolist()))
    print >> out, mk_call_str('lines', 'p.10', 't1.10.approx', col='"red"')
    print >> out, mk_call_str('points', 'p.10', 't1.10.exact', col='"blue"')
    #
    """
            'barplot',
            'mdat',
            'legend.text=' + mk_call_str(
                'c',
                '"exact discrete distribution"',
                '"continuous approximation"',
                #'"two-allele large N limit"',
                #'"two-allele"',
                #'"four-allele without mutational bias"',
                #'"four-allele with mutational bias (kappa_{1,2}=2)"',
                #'"four-allele with mutational bias, large N limit"',
                ),
            'args.legend = list(x="topright", bty="n")',
            'names.arg = 1:%s' % (N-1),
            main='title.string',
            xlab='"frequency of allele 1"',
            ylab='"frequency"',
            col=mk_call_str(
                'c',
                #'"red"',
                #'"white"',
                '"black"',
                #'"gray"',
                '"red"',
                ),
            beside='TRUE',
            border='NA',
            )
    #print >> out, 'box()'
    """
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#23
0
def get_response_content(fs):
    # transform the arguments according to the diffusion approximation
    mutation_ab = (fs.pop * fs.mutation_ab) / fs.pop_gran
    mutation_ba = (fs.pop * fs.mutation_ba) / fs.pop_gran
    if mutation_ab > 1 or mutation_ba > 1:
        raise Exception('the mutation probability is not small enough '
                        'for the diffusion approximation to be meaningful')
    selection_ratio = 1 + (fs.pop * fs.additive_selection) / fs.pop_gran
    npop = fs.pop_gran
    ngenerations = fs.ngenerations
    nmutants_initial = int(fs.initial_freq * fs.pop_gran)
    nmutants_final = int(fs.final_freq * fs.pop_gran)
    # precompute some transition matrices
    P_drift_selection = pgmsinglesite.create_drift_selection_transition_matrix(
        npop, selection_ratio)
    MatrixUtil.assert_transition_matrix(P_drift_selection)
    P_mutation = pgmsinglesite.create_mutation_transition_matrix(
        npop, mutation_ab, mutation_ba)
    MatrixUtil.assert_transition_matrix(P_mutation)
    # define the R table headers
    headers = [
        'generation',
        'allele.frequency',
        'probability',
        'log.density',
    ]
    # compute the transition matrix
    P = np.dot(P_drift_selection, P_mutation)
    # Compute the endpoint conditional probabilities for various states
    # along the unobserved path.
    nstates = npop + 1
    M = np.zeros((nstates, ngenerations))
    M[nmutants_initial, 0] = 1.0
    M[nmutants_final, ngenerations - 1] = 1.0
    for i in range(ngenerations - 2):
        A_exponent = i + 1
        B_exponent = ngenerations - 1 - A_exponent
        A = np.linalg.matrix_power(P, A_exponent)
        B = np.linalg.matrix_power(P, B_exponent)
        weights = np.zeros(nstates)
        for k in range(nstates):
            weights[k] = A[nmutants_initial, k] * B[k, nmutants_final]
        weights /= np.sum(weights)
        for k, p in enumerate(weights):
            M[k, i + 1] = p
    arr = []
    for g in range(ngenerations):
        for k in range(nstates):
            p = M[k, g]
            allele_frequency = k / float(npop)
            # Finer gridding needs larger scaling for the density
            # because each interval has a smaller support.
            density = p * nstates
            if density:
                log_density = math.log(density)
            else:
                log_density = float('-inf')
            row = [g, allele_frequency, p, log_density]
            arr.append(row)
    # create the R table string and scripts
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot(nstates)
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#24
0
def get_response_content(fs):
    M = get_input_matrix(fs)
    nstates = len(M)
    nsites = fs.nsites
    if nstates**nsites > 16:
        raise ValueError('the site dependent rate matrix is too big')
    # precompute some stuff
    M_site_indep = get_site_independent_process(M, nsites)
    v = mrate.R_to_distn(M)
    v_site_indep = get_site_independent_distn(v, nsites)
    if fs.info_fis:
        f_info = divtime.get_fisher_info_known_distn_fast
    elif fs.info_mut:
        f_info = ctmcmi.get_mutual_info_known_distn
    else:
        raise ValueError('no info type specified')
    f_selection = mrate.to_gtr_hb_known_energies
    # Spend a lot of time doing the optimizations
    # to construct the points for the R table.
    arr = []
    for t in cbreaker.throttled(progrid.gen_binary(fs.start_time,
                                                   fs.stop_time),
                                nseconds=4,
                                ncount=100):
        row = [t]
        # get the site-dependent mutation selection balance information
        if fs.dep_balance:
            dep_balance = OptDep(M_site_indep, v_site_indep, t, f_info,
                                 f_selection)
            X0 = np.random.randn(nstates**nsites - 1)
            xopt = scipy.optimize.fmin(dep_balance, X0)
            max_dep_balance_info = -dep_balance(xopt)
            row.append(max_dep_balance_info)
            # for debug
            Q_bal, v_bal = dep_balance.get_process(xopt)
            print 'dependent balance:'
            print max_dep_balance_info
            print v_bal
            print Q_bal
            print
        # get the site-independent mutation selection balance information
        if fs.indep_balance:
            indep_balance = OptIndep(M, v, nsites, t, f_info, f_selection)
            X0 = np.random.randn(nstates - 1)
            xopt = scipy.optimize.fmin(indep_balance, X0)
            max_indep_balance_info = -indep_balance(xopt)
            row.append(max_indep_balance_info)
            # for debug
            Q_bal, v_bal = indep_balance.get_process(xopt)
            print 'independent balance:'
            print max_indep_balance_info
            print v_bal
            print Q_bal
            print
        # get the site-independent mutation process information
        if fs.indep_mutation:
            indep_mut_info = f_info(M_site_indep, v_site_indep, t)
            row.append(indep_mut_info)
        # add the data row to the table
        arr.append(row)
    arr.sort()
    npoints = len(arr)
    # create the R table string and scripts
    headers = ['t']
    if fs.dep_balance:
        headers.append('max.site.dep.balance')
    if fs.indep_balance:
        headers.append('max.site.indep.balance')
    if fs.indep_mutation:
        headers.append('site.indep.mutation')
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
        table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#25
0
def get_response_content(fs):
    M = get_input_matrix(fs)
    # create the R table string and scripts
    headers = ['t']
    if fs.show_entropy:
        headers.append('ub.entropy')
    headers.extend([
            'ub.jc.spectral',
            'ub.f81.spectral',
            'mutual.information',
            'lb.2.state.spectral',
            'lb.2.state',
            'lb.f81',
            ])
    npoints = 100
    t_low = fs.start_time
    t_high = fs.stop_time
    t_incr = (t_high - t_low) / (npoints - 1)
    t_values = [t_low + t_incr*i for i in range(npoints)]
    # define some extra stuff
    v = mrate.R_to_distn(M)
    entropy = -np.dot(v, np.log(v))
    n = len(M)
    gap = sorted(abs(x) for x in np.linalg.eigvals(M))[1]
    print 'stationary distn:', v
    print 'entropy:', entropy
    print 'spectral gap:', gap
    M_slow_jc = gap * (1.0 / n) * (np.ones((n,n)) - n*np.eye(n))
    M_slow_f81 = gap * np.outer(np.ones(n), v)
    M_slow_f81 -= np.diag(np.sum(M_slow_f81, axis=1))
    M_f81 = msimpl.get_fast_f81(M)
    M_2state = msimpl.get_fast_two_state_autobarrier(M)
    M_2state_spectral = -gap * M_2state / np.trace(M_2state)
    # get the data for the R table
    arr = []
    for u in t_values:
        # experiment with log time
        #t = math.exp(u)
        t = u
        mi_slow_jc = ctmcmi.get_mutual_information(M_slow_jc, t)
        mi_slow_f81 = ctmcmi.get_mutual_information(M_slow_f81, t)
        mi_mut = ctmcmi.get_mutual_information(M, t)
        mi_2state_spectral = ctmcmi.get_mutual_information(M_2state_spectral, t)
        mi_f81 = ctmcmi.get_mutual_information(M_f81, t)
        mi_2state = ctmcmi.get_mutual_information(M_2state, t)
        row = [u]
        if fs.show_entropy:
            row.append(entropy)
        row.extend([mi_slow_jc, mi_slow_f81,
                mi_mut, mi_2state_spectral, mi_2state, mi_f81])
        arr.append(row)
    # get the R table
    table_string = RUtil.get_table_string(arr, headers)
    # get the R script
    script = get_ggplot()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter(
            table_string, script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#26
0
def get_response_content(fs):
    # define the initial frequency
    p = 0.1
    # define some selection coefficients to plot
    h_low = 0.2
    h_high = 0.8
    h_values = np.linspace(h_low, h_high, 6 * 10 + 1)
    # define some dominance coefficients
    hs_values = [-0.2, -0.05, 0, 0.05, 0.2]
    colors = ['blue', 'green', 'black', 'orange', 'red']
    # get the values for each h
    arr = []
    for hs in hs_values:
        v = [
            kimura.get_fixation_probability_chen(p, hs / h, h)
            for h in h_values
        ]
        arr.append(v)
    #
    # define the r script
    out = StringIO()
    print >> out, 'h.values <- c', str(tuple(h_values))
    print >> out, 'ha <- c', str(tuple(arr[0]))
    print >> out, 'hb <- c', str(tuple(arr[1]))
    print >> out, 'hc <- c', str(tuple(arr[2]))
    print >> out, 'hd <- c', str(tuple(arr[3]))
    print >> out, 'he <- c', str(tuple(arr[4]))
    print >> out, mk_call_str(
        'plot',
        'h.values',
        'ha',
        type='"l"',
        xlab='"h"',
        ylab='"probability of eventual fixation"',
        main=('"fixation probabilities for various h*s ; '
              's = 2*N*sigma ; p0 = %s"' % p),
        ylim='c(0, 0.2)',
        col='"%s"' % colors[0],
    )
    print >> out, mk_call_str('lines',
                              'h.values',
                              'hb',
                              col='"%s"' % colors[1])
    print >> out, mk_call_str('lines',
                              'h.values',
                              'hc',
                              col='"%s"' % colors[2])
    print >> out, mk_call_str('lines',
                              'h.values',
                              'hd',
                              col='"%s"' % colors[3])
    print >> out, mk_call_str('lines',
                              'h.values',
                              'he',
                              col='"%s"' % colors[4])
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#27
0
def get_response_content(fs):
    N_diploid = fs.N_diploid
    N = N_diploid * 2
    k = 2
    gamma = fs.gamma
    # define the fitnesses and the selection value
    f0 = 1.0
    f1 = 1.0 - gamma / N
    s = 1 - f1 / f0
    if f1 <= 0:
        raise ValueError('the extreme selection caused a non-positive fitness')
    # get a wright fisher transition matrix
    P = np.exp(wfengine.create_genic_diallelic(N_diploid, s))
    """
    # condition on no fixation
    for i in range(N):
        P[i] /= 1 - P[i, N]
    # remove the fixed state from the transition matrix
    P = P[:N, :N]
    """
    # add mutations
    P[0, 0] = 0
    P[0, 1] = 1
    P[N, N] = 0
    P[N, 1] = 1
    # compute the stationary distribution
    v = MatrixUtil.get_stationary_distribution(P)
    # get the distribution over dimorphic states
    h = v[1:-1]
    h /= np.sum(h)
    # look at continuous approximations
    w = np.zeros(N + 1)
    for i in range(1, N):
        x = i / float(N)
        #x0 = i / float(N)
        #x1 = (i + 1) / float(N)
        #value = sojourn_definite(x0, x1, gamma)
        value = sojourn_kernel(x, gamma)
        w[i] = value
    w = w[1:-1]
    w /= np.sum(w)
    # get the array for the R plot
    arr = [h.tolist(), w.tolist()]
    # define the r script
    out = StringIO()
    print >> out, 'title.string <- "allele 1 vs allele 2"'
    print >> out, 'mdat <-', RUtil.matrix_to_R_string(arr)
    print >> out, mk_call_str(
        'barplot',
        'mdat',
        'legend.text=' + mk_call_str(
            'c',
            '"exact discrete distribution"',
            '"continuous approximation"',
            #'"two-allele large N limit"',
            #'"two-allele"',
            #'"four-allele without mutational bias"',
            #'"four-allele with mutational bias (kappa_{1,2}=2)"',
            #'"four-allele with mutational bias, large N limit"',
        ),
        'args.legend = list(x="topright", bty="n")',
        'names.arg = 1:%s' % (N - 1),
        main='title.string',
        xlab='"frequency of allele 1"',
        ylab='"frequency"',
        col=mk_call_str(
            'c',
            #'"red"',
            #'"white"',
            '"black"',
            #'"gray"',
            '"red"',
        ),
        beside='TRUE',
        border='NA',
    )
    #print >> out, 'box()'
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#28
0
def get_response_content(fs):
    N_small = 10
    N_big_diploid = fs.N_big_diploid
    N_big_haploid = N_big_diploid * 2
    if N_big_haploid < N_small:
        raise ValueError('use a larger diploid population size')
    if fs.with_replacement:
        f_subsample = StatsUtil.subsample_pmf_with_replacement
    elif fs.without_replacement:
        f_subsample = StatsUtil.subsample_pmf_without_replacement
    else:
        raise ValueError('subsampling option error')
    k = 4
    gamma = fs.gamma_1
    params_list = [(0.008, 1, 1, fs.gamma_0, fs.gamma_1, fs.gamma_2),
                   (0.008, 2, 1, fs.gamma_0, fs.gamma_1, fs.gamma_2)]
    allele_histograms = np.zeros((2, N_big_haploid + 1))
    for i, params in enumerate(params_list):
        mutation, selection = kaizeng.params_to_mutation_fitness(
            N_big_haploid, params)
        P = kaizeng.get_transition_matrix(N_big_diploid, k, mutation,
                                          selection)
        v = MatrixUtil.get_stationary_distribution(P)
        for state_index, counts in enumerate(
                kaizeng.gen_states(N_big_haploid, k)):
            if counts[0] and counts[1]:
                allele_histograms[i, counts[0]] += v[state_index]
    # Define the r table.
    # There are nine columns each corresponding to an allele frequency.
    # There are three rows each corresponding to a configuration.
    arr = []
    # Use the two allele approximation
    # from mcvean and charlesworth 1999 referred to by zeng 2011.
    # I'm not sure if I am using the right equation.
    g0 = fs.gamma_0
    g1 = fs.gamma_1
    """
    s_0 = -gamma_0 / float(N_big)
    s_1 = -gamma_1 / float(N_big)
    hist = np.zeros(N_small+1)
    for i in range(1, N_small):
        x = i / float(N_small)
        hist[i] = math.exp(1*N_big*(s_0 - s_1)*x) / (x*(1-x))
    h = hist[1:-1]
    h /= np.sum(h)
    arr.append(h.tolist())
    """
    arr.append(diallelic_approximation(N_small, g0, g1).tolist())
    # Use the exact two allele distribution.
    # Well, it is exact if I understand the right scaling
    # of the population size and fitnesses.
    f0 = 1.0
    f1 = 1.0 - gamma / N_big_haploid
    #f0 = 1.0 + gamma / N
    #f1 = 1.0
    #f0 = 1.0 + 1.5 / (4*N)
    #f1 = 1.0 - 1.5 / (4*N)
    h = get_two_allele_distribution(N_big_haploid, N_small, f0, f1,
                                    f_subsample)
    arr.append(h.tolist())
    # Get frequencies for the other two configurations
    for hist in allele_histograms:
        # Get probabilities conditional on dimorphism.
        hist[0] = 0
        hist[-1] = 0
        hist /= np.sum(hist)
        # Get the subsampled pmf.
        distn = f_subsample(hist, N_small)
        MatrixUtil.assert_distribution(distn)
        # Get probabiities conditional on dimorphism of the sample.
        distn[0] = 0
        distn[-1] = 0
        distn /= np.sum(distn)
        # Add to the table of densities.
        arr.append(distn[1:-1].tolist())
    # Get a large population approximation
    # when there is mutational bias.
    params = (0.008, 2, 1, fs.gamma_0, fs.gamma_1, fs.gamma_2)
    mutation, fitness = kaizeng.params_to_mutation_fitness(
        N_big_haploid, params)
    gammas = np.array([fs.gamma_0, fs.gamma_1, fs.gamma_2, 0])
    h = kaizeng.get_large_population_approximation(N_small, k, gammas,
                                                   mutation)
    arr.append(h.tolist())
    # define the r script
    out = StringIO()
    print >> out, 'title.string <- "allele 1 vs allele 2"'
    print >> out, 'mdat <-', RUtil.matrix_to_R_string(arr)
    print >> out, mk_call_str(
        'barplot',
        'mdat',
        'legend.text=' + mk_call_str(
            'c',
            '"two-allele large N limit"',
            '"two-allele"',
            '"four-allele without mutational bias"',
            '"four-allele with mutational bias (kappa_{1,2}=2)"',
            '"four-allele with mutational bias, large N limit"',
        ),
        'args.legend = list(x="topleft", bty="n")',
        'names.arg = c(1,2,3,4,5,6,7,8,9)',
        main='title.string',
        xlab='"frequency of allele 1"',
        ylab='"frequency"',
        col=mk_call_str(
            'c',
            '"red"',
            '"white"',
            '"black"',
            '"gray"',
            '"blue"',
        ),
        beside='TRUE',
    )
    #print >> out, 'box()'
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#29
0
def get_response_content(fs):
    # define the initial frequency
    p = 0.01
    density = 2
    # dominance
    if fs.h_dense:
        h_low = 0.2
        h_high = 0.8
        h_values = np.linspace(h_low, h_high, 6 * density + 1)
    elif fs.h_sparse:
        h_low = 0
        h_high = 1
        h_values = np.linspace(h_low, h_high, 2 + 1)
    # selection
    s_low = -1.0
    s_high = 1.0
    s_values = fs.s_scale * np.linspace(s_low, s_high, 20 * density + 1)
    # hs product
    hs_values = np.outer(h_values, s_values)
    # compute all values in the grid
    f_values = np.zeros((len(h_values), len(s_values)))
    for i, h in enumerate(h_values):
        for j, s in enumerate(s_values):
            f_values[i, j] = kimura.get_fixation_probability_chen(p, s, h)
    if fs.x_is_log_pfix:
        f_values = np.log(f_values / p)
    # define the r script
    out = StringIO()
    if fs.infer_s:
        ylab_string = '"selection coefficient (s)"'
        ylim_low = np.min(s_values)
        ylim_high = np.max(s_values)
    elif fs.infer_hs:
        ylab_string = '"product of dominance and selection (hs)"'
        ylim_low = np.min(hs_values)
        ylim_high = np.max(hs_values)
    if fs.x_is_pfix:
        xlab_string = '"probability of eventual fixation"'
    elif fs.x_is_log_pfix:
        xlab_string = '"log of ratios of probability of eventual fixation"'
    xlim_low = np.min(f_values)
    xlim_high = np.max(f_values)
    colors = ['orange', 'green', 'blue']
    if fs.h_dense:
        main_string = ('"s = 2*N*sigma ; '
                       '%s < h < %s ; '
                       'p0 = %s"' % (h_low, h_high, p))
    elif fs.h_sparse:
        main_string = ('"s = 2*N*sigma ; ' 'p0 = %s"' % p)
    print >> out, mk_call_str(
        'plot',
        'c(0,0)',
        'c(0,0)',
        type='"n"',
        xlab=xlab_string,
        ylab=ylab_string,
        main=main_string,
        xlim='c(%s, %s)' % (xlim_low, xlim_high),
        ylim='c(%s, %s)' % (ylim_low, ylim_high),
    )
    if fs.h_dense:
        for h, s_row in zip(h_values, f_values):
            if fs.infer_s:
                y_vect = s_values
            elif fs.infer_hs:
                y_vect = h * s_values
            print >> out, mk_call_str(
                'lines',
                'c' + str(tuple(s_row)),
                'c' + str(tuple(y_vect)),
            )
        for s, h_col in zip(s_values, f_values.T):
            if fs.infer_s:
                y_vect = s * np.ones_like(h_col)
            elif fs.infer_hs:
                y_vect = s * h_values
            print >> out, mk_call_str(
                'lines',
                'c' + str(tuple(h_col)),
                'c' + str(tuple(y_vect)),
            )
    elif fs.h_sparse:
        for i, (h, s_row) in enumerate(zip(h_values, f_values)):
            if fs.infer_s:
                y_vect = s_values
            elif fs.infer_hs:
                y_vect = h * s_values
            print >> out, mk_call_str(
                'lines',
                'c' + str(tuple(s_row)),
                'c' + str(tuple(y_vect)),
                col='"%s"' % colors[i],
            )
    if fs.h_sparse:
        print >> out, mk_call_str(
            'legend',
            '"topleft"',
            'c' + str(tuple('h = %s' % x for x in h_values)),
            lty='c' + str(tuple([1] * len(h_values))),
            lwd='c' + str(tuple([2.5] * len(h_values))),
            col='c' + str(tuple(colors)),
        )
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
        script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data
示例#30
0
def get_response_content(fs):
    # define the initial frequency
    p = 0.1
    # define some selection coefficients to plot
    h_low = 0.2
    h_high = 0.8
    h_values = np.linspace(h_low, h_high, 6*10 + 1)
    # define some dominance coefficients
    hs_values = [-0.2, -0.1, -0.04, 0, 0.04, 0.1, 0.2]
    #colors = ['blue', 'green', 'black', 'orange', 'red']
    colors = ['darkviolet', 'blue', 'green', 'black', 'yellow', 'orange', 'red']
    # get the values for each h
    arr = []
    xaxis = []
    for hs in hs_values:
        s_values = hs / h_values
        v = [kimura.get_fixation_probability_chen(p, hs/h, h) for h in h_values]
        xaxis.append(s_values)
        arr.append(v)
    #
    # define the r script
    out = StringIO()
    print >> out, 'h.values <- c', str(tuple(h_values))
    print >> out, 'ha <- c', str(tuple(arr[0]))
    print >> out, 'hb <- c', str(tuple(arr[1]))
    print >> out, 'hc <- c', str(tuple(arr[2]))
    print >> out, 'hd <- c', str(tuple(arr[3]))
    print >> out, 'he <- c', str(tuple(arr[4]))
    print >> out, 'hf <- c', str(tuple(arr[5]))
    print >> out, 'hg <- c', str(tuple(arr[6]))
    print >> out, 'ha.x <- c', str(tuple(xaxis[0]))
    print >> out, 'hb.x <- c', str(tuple(xaxis[1]))
    print >> out, 'hc.x <- c', str(tuple(xaxis[2]))
    print >> out, 'hd.x <- c', str(tuple(xaxis[3]))
    print >> out, 'he.x <- c', str(tuple(xaxis[4]))
    print >> out, 'hf.x <- c', str(tuple(xaxis[5]))
    print >> out, 'hg.x <- c', str(tuple(xaxis[6]))
    print >> out, mk_call_str('plot', 'ha.x', 'ha',
            type='"l"',
            xlab='"selection coefficient (s)"',
            ylab='"probability of eventual fixation"',
            main=(
                '"fixation probabilities for various h*s ; '
                's = 2*N*sigma ; p0 = %s"' % p),
            xlim='c(-1, 1)',
            ylim='c(0.05, 0.15)',
            col='"%s"' % colors[0],
            )
    print >> out, mk_call_str('lines', 'hb.x', 'hb', col='"%s"' % colors[1])
    print >> out, mk_call_str('lines', 'hc.x', 'hc', col='"%s"' % colors[2])
    print >> out, mk_call_str('lines', 'hd.x', 'hd', col='"%s"' % colors[3])
    print >> out, mk_call_str('lines', 'he.x', 'he', col='"%s"' % colors[4])
    print >> out, mk_call_str('lines', 'hf.x', 'hf', col='"%s"' % colors[5])
    print >> out, mk_call_str('lines', 'hg.x', 'hg', col='"%s"' % colors[6])
    print >> out, mk_call_str(
            'legend',
            '"topleft"',
            'c' + str(rev('hs = %s' % x for x in hs_values)),
            lty='c' + str(rev([1]*7)),
            lwd='c' + str(rev([2.5]*7)),
            col='c' + str(rev(colors)),
            )
    script = out.getvalue().rstrip()
    # create the R plot image
    device_name = Form.g_imageformat_to_r_function[fs.imageformat]
    retcode, r_out, r_err, image_data = RUtil.run_plotter_no_table(
            script, device_name)
    if retcode:
        raise RUtil.RError(r_err)
    return image_data