Ejemplo n.º 1
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
Ejemplo n.º 2
0
def simulate_branch_path(tree, node):
    """
    Simulate the nucleotide history on the path between a node and its parent.
    This simulated path is conditional on known values at each node.
    Purines are red; pyrimidines are blue.
    A and T are brighter; G and C are darker.
    @param tree: a SpatialTree with simulated nucleotides at each node
    @param node: the node that defines the branch on which to simulate a history
    """
    nucleotide_to_color = {
        'A': 'FF4444',
        'G': 'FF8888',
        'T': '4444FF',
        'C': '8888FF'
    }
    node.branch_color = nucleotide_to_color[node.state]
    rate_matrix = RateMatrix.get_jukes_cantor_rate_matrix()
    initial_state = node.parent.state
    terminal_state = node.state
    states = 'ACGT'
    events = None
    while events is None:
        events = PathSampler.get_nielsen_sample(initial_state, terminal_state,
                                                states, node.blen, rate_matrix)
    parent = node.parent
    last_t = 0
    for t, state in events:
        new = SpatialTree.SpatialTreeNode()
        new.name = node.name
        new.state = state
        new.branch_color = nucleotide_to_color[parent.state]
        tree.insert_node(new, parent, node, (t - last_t) / float(node.blen))
        last_t = t
        parent = new
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def simulate_branch_path(tree, node):
    """
    Simulate the nucleotide history on the path between a node and its parent.
    This simulated path is conditional on known values at each node.
    Purines are red; pyrimidines are blue.
    A and T are brighter; G and C are darker.
    @param tree: a SpatialTree with simulated nucleotides at each node
    @param node: the node that defines the branch on which to simulate a history
    """
    nucleotide_to_color = {
            'A':'FF4444', 'G':'FF8888', 'T':'4444FF', 'C':'8888FF'}
    node.branch_color = nucleotide_to_color[node.state]
    rate_matrix = RateMatrix.get_jukes_cantor_rate_matrix()
    initial_state = node.parent.state
    terminal_state = node.state
    states = 'ACGT'
    events = None
    while events is None:
        events = PathSampler.get_nielsen_sample(
                initial_state, terminal_state, states, node.blen, rate_matrix)
    parent = node.parent
    last_t = 0
    for t, state in events:
        new = SpatialTree.SpatialTreeNode()
        new.name = node.name
        new.state = state
        new.branch_color = nucleotide_to_color[parent.state]
        tree.insert_node(new, parent, node, (t - last_t) / float(node.blen))
        last_t = t
        parent = new
Ejemplo n.º 5
0
def simulate_branch_path(tree, node, rate_matrix_object):
    # purines are red; pyrimidines are blue
    # A and T are brighter, G and C are darker
    nt_to_color = {'A':'ff4444', 'G':'ffaaaa', 'T':'4444ff', 'C':'aaaaff'}
    node.branch_color = nt_to_color[node.state]
    rate_matrix = rate_matrix_object.dictionary_rate_matrix
    initial_state = node.parent.state
    terminal_state = node.state
    states = 'ACGT'
    events = None
    while events is None:
        events = PathSampler.get_nielsen_sample(
                initial_state, terminal_state, states, node.blen, rate_matrix)
    parent = node.parent
    last_t = 0
    for t, state in events:
        new = SpatialTree.SpatialTreeNode()
        new.name = node.name
        new.state = state
        new.branch_color = nt_to_color[parent.state]
        tree.insert_node(new, parent, node, (t - last_t) / float(node.blen))
        last_t = t
        parent = new
Ejemplo n.º 6
0
def get_response_content(fs):
    # define the states using the default transition matrix
    default_transition_matrix = EnglishModel.get_transition_matrix()
    states = list(sorted(set(a for a, b in default_transition_matrix)))
    # read the constraints from the form data
    if fs.first not in states:
        raise HandlingError("invalid first letter")
    if fs.last not in states:
        raise HandlingError("invalid last letter")
    if fs.count == 1 and fs.first != fs.last:
        msg_a = "if a single letter is to be simulated "
        msg_b = "then the first letter must be the same as the last letter."
        raise HandlingError(msg_a + msg_b)
    # read the transition matrix from the form data
    T = fs.matrix
    if T.shape[0] != len(states):
        msg = "expected the transition matrix to have %d lines" % len(states)
        raise HandlingError(msg)
    matrix = MatrixUtil.row_major_to_dict(T.tolist(), states, states)
    # simulate the path
    path = PathSampler.get_discrete_path_sample(fs.first, fs.last, states, fs.count, matrix)
    # show the simulated path in convenient text form
    return "".join(path) + "\n"
Ejemplo n.º 7
0
def get_response_content(fs):
    # define the states using the default transition matrix
    default_transition_matrix = EnglishModel.get_transition_matrix()
    states = list(sorted(set(a for a, b in default_transition_matrix)))
    # read the constraints from the form data
    if fs.first not in states:
        raise HandlingError('invalid first letter')
    if fs.last not in states:
        raise HandlingError('invalid last letter')
    if fs.count == 1 and fs.first != fs.last:
        msg_a = 'if a single letter is to be simulated '
        msg_b = 'then the first letter must be the same as the last letter.'
        raise HandlingError(msg_a + msg_b)
    # read the transition matrix from the form data
    T = fs.matrix
    if T.shape[0] != len(states):
        msg = 'expected the transition matrix to have %d lines' % len(states)
        raise HandlingError(msg)
    matrix = MatrixUtil.row_major_to_dict(T.tolist(), states, states)
    # simulate the path
    path = PathSampler.get_discrete_path_sample(fs.first, fs.last, states,
                                                fs.count, matrix)
    # show the simulated path in convenient text form
    return ''.join(path) + '\n'
Ejemplo n.º 8
0
def get_response_content(fs):
    initial_state = multiline_state_to_ndarray(fs.initial_state)
    final_state = multiline_state_to_ndarray(fs.final_state)
    if initial_state.shape != final_state.shape:
        raise ValueError(
            'initial and final states do not have the same dimensions')
    nchromosomes, npositions = initial_state.shape
    ndimcap = 12
    if nchromosomes * npositions > ndimcap:
        raise ValueError('at most 2^%d states are allowed per generation' %
                         ndimcap)
    #
    mutation = 0.5 * fs.mutation_param
    recombination = 0.5 * fs.recombination_param
    selection = fs.selection_param
    #
    out = StringIO()
    print >> out, 'number of chromosomes:'
    print >> out, nchromosomes
    print >> out
    print >> out, 'number of positions per chromosome:'
    print >> out, npositions
    print >> out
    # define the transition matrix
    results = pgmfancy.get_state_space_info(nchromosomes, npositions)
    ci_to_short, short_to_count, sorted_chrom_lists = results
    initial_ci = pgmfancy.chroms_to_index(
        sorted(popgenmarkov.bin_to_int(row) for row in initial_state),
        npositions)
    initial_short = ci_to_short[initial_ci]
    final_ci = pgmfancy.chroms_to_index(
        sorted(popgenmarkov.bin_to_int(row) for row in final_state),
        npositions)
    final_short = ci_to_short[final_ci]
    P_sr_s = pgmfancy.get_selection_recombination_transition_matrix_s(
        ci_to_short, short_to_count, sorted_chrom_lists, selection,
        recombination, nchromosomes, npositions)
    P_m_s = pgmfancy.get_mutation_transition_matrix_s(ci_to_short,
                                                      short_to_count,
                                                      sorted_chrom_lists,
                                                      mutation, nchromosomes,
                                                      npositions)
    P = np.dot(P_sr_s, P_m_s)
    # sample the endpoint conditioned path
    path = PathSampler.sample_endpoint_conditioned_path(
        initial_short, final_short, fs.ngenerations, P)
    print >> out, 'sampled endpoint conditioned path, including endpoints:'
    print >> out
    # print the initial state without shuffling of individuals
    print >> out, ndarray_to_multiline_state(initial_state)
    print >> out
    # print the intermediate states with randomly permuted individuals
    for short_index in path[1:-1]:
        chroms = sorted_chrom_lists[short_index]
        random.shuffle(chroms)
        K = np.array([popgenmarkov.int_to_bin(x, npositions) for x in chroms])
        print >> out, ndarray_to_multiline_state(K)
        print >> out
    # print the final state without shuffling of individuals
    print >> out, ndarray_to_multiline_state(final_state)
    print >> out
    return out.getvalue()
Ejemplo n.º 9
0
def get_response_content(fs):
    initial_state = multiline_state_to_ndarray(fs.initial_state)
    final_state = multiline_state_to_ndarray(fs.final_state)
    if initial_state.shape != final_state.shape:
        raise ValueError(
                'initial and final states do not have the same dimensions')
    nchromosomes, npositions = initial_state.shape
    ndimcap = 12
    if nchromosomes * npositions > ndimcap:
        raise ValueError(
                'at most 2^%d states are allowed per generation' % ndimcap)
    #
    mutation = 0.5 * fs.mutation_param
    recombination = 0.5 * fs.recombination_param
    selection = fs.selection_param
    #
    out = StringIO()
    print >> out, 'number of chromosomes:'
    print >> out, nchromosomes
    print >> out
    print >> out, 'number of positions per chromosome:'
    print >> out, npositions
    print >> out
    # define the transition matrix
    results = pgmfancy.get_state_space_info(nchromosomes, npositions)
    ci_to_short, short_to_count, sorted_chrom_lists = results
    initial_ci = pgmfancy.chroms_to_index(
            sorted(popgenmarkov.bin_to_int(row) for row in initial_state),
            npositions)
    initial_short = ci_to_short[initial_ci]
    final_ci = pgmfancy.chroms_to_index(
            sorted(popgenmarkov.bin_to_int(row) for row in final_state),
            npositions)
    final_short = ci_to_short[final_ci]
    P_sr_s = pgmfancy.get_selection_recombination_transition_matrix_s(
            ci_to_short, short_to_count, sorted_chrom_lists,
            selection, recombination, nchromosomes, npositions)
    P_m_s = pgmfancy.get_mutation_transition_matrix_s(
            ci_to_short, short_to_count, sorted_chrom_lists,
            mutation, nchromosomes, npositions)
    P = np.dot(P_sr_s, P_m_s)
    # sample the endpoint conditioned path
    path = PathSampler.sample_endpoint_conditioned_path(
            initial_short, final_short,
            fs.ngenerations, P)
    print >> out, 'sampled endpoint conditioned path, including endpoints:'
    print >> out
    # print the initial state without shuffling of individuals
    print >> out, ndarray_to_multiline_state(initial_state)
    print >> out
    # print the intermediate states with randomly permuted individuals
    for short_index in path[1:-1]:
        chroms = sorted_chrom_lists[short_index]
        random.shuffle(chroms)
        K = np.array([popgenmarkov.int_to_bin(x, npositions) for x in chroms])
        print >> out, ndarray_to_multiline_state(K)
        print >> out
    # print the final state without shuffling of individuals
    print >> out, ndarray_to_multiline_state(final_state)
    print >> out
    return out.getvalue()