Esempio n. 1
0
    def parseAndGenerateImage(self, script_string):
        input = InputStream(script_string)
        lexer = PigeonLexer(input)
        stream = CommonTokenStream(lexer)
        parser = PigeonParser(stream)
        tree = parser.script()

        htmlPigeon = HtmlPigeonListener()
        walker = ParseTreeWalker()
        walker.walk(htmlPigeon, tree)

        dr = dpl.DNARenderer()
        part_renderers = dr.SBOL_part_renderers()

        design = HtmlPigeonListener.getDesignList(htmlPigeon)
        arcs = HtmlPigeonListener.getArcList(htmlPigeon)

        fig = plt.figure(figsize=(design.__len__() / 3, 2))
        gs = gridspec.GridSpec(1, 1)
        axis = plt.subplot(gs[0])

        print("Deisgn Length: " + str(design.__len__()))
        print("Arcs Length: " + str(arcs.__len__()))

        start, end = dr.renderDNA(axis,
                                  design,
                                  part_renderers,
                                  regs=arcs,
                                  reg_renderers=dr.std_reg_renderers())
        axis.set_xlim([start, end])
        axis.set_ylim([-(30 + design.__len__()), (30 + design.__len__())])
        axis.set_aspect('equal')
        axis.axis('off')
        self.fig = fig
        pass
Esempio n. 2
0
def plot_operon_structure(design, fig_width, directory_name=""):
    # Redender the DNA
    fig = plt.figure(figsize=(fig_width / 85, 0.5))
    gs = gridspec.GridSpec(1, 1)
    ax_dna = plt.subplot(gs[0])

    dr = dpl.DNARenderer()
    part_renderers = dr.SBOL_part_renderers()
    start, end = dr.renderDNA(ax_dna, design, part_renderers)

    # Set bounds and display options for the DNA axis
    dna_len = end - start

    ax_dna.set_xlim([start - 20, end + 20])
    ax_dna.set_ylim([-15, 20])
    ax_dna.plot([start - 20, end + 20], [0, 0],
                color=(0, 0, 0),
                linewidth=1.0,
                zorder=1)
    ax_dna.axis('off')
    plt.subplots_adjust(hspace=.08, left=.01, right=.99, top=0.99, bottom=0.02)

    #create the directory if it doesn't exist
    if not path.exists(directory_name):
        os.makedirs(directory_name, exist_ok=True)  #remember to add mode later
    plt.savefig("{}sbol_plot".format(directory_name), dpi=300)
    plt.close('all')
Esempio n. 3
0
def plotDesign(design,renderer = None,part_renderers=None,\
                circular=False,title=None):
    """helper function for doing dnaplotlib plots. You need to set the size and min max of the
    plot, and that's what this function does"""
    if (PLOT_DNA):
        if (renderer is None):
            renderer = dpl.DNARenderer(scale=5, linewidth=3)
        if (part_renderers is None):
            part_renderers = renderer.SBOL_part_renderers()
        fig = plt.figure(figsize=(len(design) * .75, 1.1))
        ax = fig.add_axes([0, 0, 1, 1])
        try:
            start, end = renderer.renderDNA(ax,
                                            design,
                                            part_renderers,
                                            circular=circular)
        except TypeError:
            start, end = renderer.renderDNA(ax, design, part_renderers)
        ax.axis('off')
        if title is not None:
            ax.set_title(title)
        addedsize = 1
        ax.set_xlim([start - addedsize, end + addedsize])
        ax.set_ylim([-15, 15])
        plt.show()
    else:
        warn(
            "plotting DNA has been disabled because you don't have DNAplotlib")
Esempio n. 4
0
def Run_PlotCircuit(Input, Regulations=None):

    dr = dpl.DNARenderer()

    ## Parse the command line inputs
    #parser = argparse.ArgumentParser(description="one line quick plot")
    #parser.add_argument("-input",  dest="input",  required=True,  help="\"p.orange p.lightblue i.lightred r.green c.orange t.purple -t.black -c.yellow -p.yellow\"", metavar="string")
    #parser.add_argument("-output", dest="output", required=False, help="output pdf filename")
    #args = parser.parse_args()

    # Input = "p.black.pBAD r.black.rbsD c.red.RFP t.black -t.black.BBaB0015 -c.green.GFP -r.black.rbs34 -i.black -p.black.pTet o.black.CoIE1"

    #print('Hello: ', args.input)

    # Process the arguments
    design = PlotCircuitfunc(Input)

    reg_renderers = dr.std_reg_renderers()
    part_renderers = dr.SBOL_part_renderers()

    #Regulations = None
    # For adding regulation control (Activation, Repression, Connection)
    #    Regulations = [{'type': 'Repression', 'from_part': {'start': 40, 'end': 40},
    #             'to_part': {'start': 150,'end': 150, 'fwd': True},
    #             'opts': {'color': (0.12,0.47,0.71), 'linewidth': 1.5}}]

    # Generate the figure
    fig = plt.figure(figsize=(1.0, 1.0), dpi=100)
    ax = fig.add_subplot(1, 1, 1)

    # Plot the design
    dna_start, dna_end = dr.renderDNA(ax, design, part_renderers, Regulations,
                                      reg_renderers)
    max_dna_len = dna_end - dna_start

    print('Max Dna length: ', max_dna_len)

    # Format the axis
    ax.set_xticks([])
    ax.set_yticks([])

    # Set bounds
    ax.set_xlim([(-0.0 * max_dna_len), max_dna_len + (0.0 * max_dna_len)])
    ax.set_ylim([-25, 25])
    ax.set_aspect('equal')
    ax.set_axis_off()

    # Update the size of the figure to fit the constructs drawn
    fig_x_dim = max_dna_len / 30  #/60.0
    print('x_dim: ', fig_x_dim)
    if fig_x_dim < 1.0:
        fig_x_dim = 1.0
    fig_y_dim = 1.8  #fig_x_dim*0.4
    plt.gcf().set_size_inches(fig_x_dim, fig_y_dim, forward=True)

    # Save the figure
    plt.tight_layout()
    #fig.savefig(args.output, transparent=True)
    plt.show()
Esempio n. 5
0
def plot_nupop(design_nupop, full_sequence, directory_name=""):

    #wrap promoter with 420bp buffer sequence on each side
    pre = "aaaagactctaacaaaatagcaaatttcgtcaaaaatgctaagaaataggttattactgagtagtatttatttaagtattgtttgtgcacttgcctgcaagccttttgaaaagcaagcataaaagatctaaacataaaatctgtaaaataacaagatgtaaagataatgctaaatcatttggctttttgattgattgtacaggaaaatatacatcgcagggggttgacttttaccatttcaccgcaatggaatcaaacttgttgaagagaatgttcacaggcgcatacgctacaatgacccgattcttgctagccgaattccagtcaggctgctagcaccagagctacgtgaccgcaggactagctccagctgagcgacacgcgaacaggtgtagagtcagtcgtgctgcaaggtcgcac"
    post = "TTAAAGAGGAGAAAGGTACCATGAGTAAAGGAGAAGAACTTTTCACTGGAGTTGTCCCAATTCTTGTTGAATTAGATGGTGATGTTAATGGGCACAAATTTTCTGTCAGTGGAGAGGGTGAAGGTGATGCAACATACGGAAAACTTACCCTTAAATTTATTTGCACTACTGGAAAACTACCTGTTCCATGGCCAACACTTGTCACTACTTTCACTTATGGTGTTCAATGCTTTTCAAGATACCCAGATCATATGAAACGGCATGACTTTTTCAAGAGTGCCATGCCCGAAGGTTATGTACAGGAAAGAACTATATTTTTCAAAGATGACGGGAACTACAAGACACGTGCTGAAGTCAAGTTTGAAGGTGATACCCTTGTTAATAGAATCGAGTTAAAAGGTATTGATTTTAAAGAAGATG"
    buffered_sequence = pre + full_sequence + post

    #run NuPoP on R
    NuPoP_out = subprocess.check_output(
        ["Rscript", "NuPoP_Rscript.R", buffered_sequence])
    nuc_occu = NuPoP_out.decode("utf-8").split()

    nuc_occu = list(map(float, nuc_occu))

    operon_length = len(full_sequence)

    # Create the figure and all axes to draw to (width of figure should be size of operon divided by 200)
    fig = plt.figure(figsize=(operon_length / 400, 1.5))
    gs = gridspec.GridSpec(2, 1, height_ratios=[0.5, 0.3])
    ax_dna = plt.subplot(gs[0])

    # Render the DNA
    dr = dpl.DNARenderer(scale=1, linewidth=0.9)
    start, end = dr.renderDNA(ax_dna, design_nupop, dr.trace_part_renderers())
    # Set bounds and display options for the DNA axis
    ax_dna.set_xlim([0, operon_length])
    ax_dna.set_ylim([-8, 8])
    ax_dna.plot([0, operon_length], [0, 0],
                color=(0, 0, 0),
                linewidth=1.0,
                zorder=1)
    ax_dna.axis('off')

    #plot the NuPoP output
    nuc_coords = range(-420, operon_length + 420)
    ax_nupop = plt.subplot(gs[1])
    ax_nupop.plot(nuc_coords, nuc_occu, linewidth=1)
    ax_nupop.set_xlim([0, operon_length])
    ax_nupop.set_ylim([0, 1.1])
    ax_nupop.set_xlabel('Nucleotide Position', fontsize=8, labelpad=6)

    ax_nupop.spines["top"].set_visible(False)
    #ax.spines["bottom"].set_visible(False)
    ax_nupop.spines["right"].set_visible(False)
    #ax.spines["left"].set_visible(False)

    ax_nupop.tick_params(axis='y', which='major', pad=2, labelsize=8)
    ax_nupop.tick_params(axis='x', which='major', pad=2, labelsize=8)

    plt.setp(ax_nupop.spines.values(), linewidth=1)
    plt.fill_between(nuc_coords, nuc_occu, color=(0.38, 0.65, 0.87))
    plt.subplots_adjust(hspace=.08, left=.03, right=.99, top=0.99, bottom=0.30)

    #create the directory if it doesn't exist
    if not path.exists(directory_name):
        os.makedirs(directory_name, exist_ok=True)  #remember to add mode later
    plt.savefig("{}nupop_plot".format(directory_name), dpi=300)
Esempio n. 6
0
def main():
    # Parse the command line inputs
    parser = argparse.ArgumentParser(description="one line quick plot")
    parser.add_argument(
        "-input",
        dest="input",
        required=True,
        help=
        "\"p.gray p.lightblue i.lightred r.green c.orange t.purple -t.black -c.yellow -p.yellow\"",
        metavar="string")
    parser.add_argument("-output",
                        dest="output",
                        required=False,
                        help="output pdf filename")
    args = parser.parse_args()

    # Process the arguments
    design = process_arguments(args.input)

    # Create objects for plotting (dnaplotlib)
    dr = dpl.DNARenderer(linewidth=1.15,
                         backbone_pad_left=3,
                         backbone_pad_right=3)
    reg_renderers = dr.std_reg_renderers()
    part_renderers = dr.SBOL_part_renderers()
    regs = None

    # Generate the figure
    fig = plt.figure(figsize=(5.0, 5.0))
    ax = fig.add_subplot(1, 1, 1)

    # Plot the design
    dna_start, dna_end = dr.renderDNA(ax, design, part_renderers, regs,
                                      reg_renderers)
    max_dna_len = dna_end - dna_start

    # Format the axis
    ax.set_xticks([])
    ax.set_yticks([])

    # Set bounds
    ax.set_xlim([(-0.01 * max_dna_len), max_dna_len + (0.01 * max_dna_len)])
    ax.set_ylim([-35, 35])
    ax.set_aspect('equal')
    ax.set_axis_off()

    # Update the size of the figure to fit the constructs drawn
    fig_x_dim = max_dna_len / 60.0
    if fig_x_dim < 1.0:
        fig_x_dim = 1.0
    fig_y_dim = 1.2
    plt.gcf().set_size_inches((fig_x_dim, fig_y_dim))

    # Save the figure
    plt.tight_layout()
    fig.savefig(args.output, transparent=True, dpi=300)
Esempio n. 7
0
    def PlotCircuit(self, filename, Input, Regulation=None):
        """Plot the SBOL-compliant gene circuit figure.
        Parameters:
            filename: the filename for the generated figure
            Input, Regulation: Input design and Regulation strings from users
        Returns:
            Max DNA Design length and export the gene circuit figure
        """

        # matplotlib.use("Qt5Agg")
        matplotlib.use("Agg")

        dr = dpl.DNARenderer(linewidth=1.5)

        # Process the arguments
        design, Regulations = self.CircuitDesign(Input, Regulation)

        reg_renderers = dr.std_reg_renderers()
        part_renderers = dr.SBOL_part_renderers()

        # Generate the figure
        fig = plt.figure(figsize=(1.0, 1.0), dpi=100)
        ax = fig.add_subplot(1, 1, 1)

        # Plot the design
        dna_start, dna_end = dr.renderDNA(ax, design, part_renderers,
                                          Regulations, reg_renderers)
        max_dna_len = dna_end - dna_start

        # print("Max Dna length: ", max_dna_len)

        # Format the axis
        ax.set_xticks([])
        ax.set_yticks([])

        # Set bounds
        ax.set_xlim([(-0.0 * max_dna_len), max_dna_len + (0.0 * max_dna_len)])
        ax.set_ylim([-25, 25])
        ax.set_aspect("equal")
        ax.set_axis_off()

        # Update the size of the figure to fit the constructs drawn
        fig_x_dim = max_dna_len / 30
        # print("x_dim: ", fig_x_dim)
        if fig_x_dim < 1.0:
            fig_x_dim = 1.0
        fig_y_dim = 1.8
        plt.gcf().set_size_inches(fig_x_dim, fig_y_dim, forward=True)

        # Save the figure
        plt.tight_layout()
        fig.savefig(filename, transparent=True, dpi=300)
        # plt.show()

        return max_dna_len, fig
Esempio n. 8
0
def plot_trace_y_offset(designs, output_prefix):
    design_frame1 = designs[0]
    design_frame2 = designs[1]
    design_frame3 = designs[2]
    # Generate the offsets for each design
    frame2_offset = 9.0
    for part in design_frame2:
        if 'opts' in list(part.keys()):
            part['opts']['y_offset'] = frame2_offset
        else:
            part['opts'] = {'y_offset': frame2_offset}
    frame3_offset = 16.0
    for part in design_frame3:
        if 'opts' in list(part.keys()):
            part['opts']['y_offset'] = frame3_offset
        else:
            part['opts'] = {'y_offset': frame3_offset}
    # We can now combine all into a single design
    combined_designs = design_frame1 + design_frame2 + design_frame3

    # Create the figure and all axes to draw to
    fig = plt.figure(figsize=(3.2, 1.2))
    gs = gridspec.GridSpec(1, 1)
    ax_dna_all_frames = plt.subplot(gs[0])

    # Redender the DNA
    dr = dpl.DNARenderer(scale=5, linewidth=0.9)
    start1, end1 = dr.renderDNA(ax_dna_all_frames,
                                combined_designs,
                                dr.trace_part_renderers(),
                                plot_backbone=True)
    # We specify the length manually as we know the design constraints
    start1 = 0
    end1 = 2640
    dna_len = end1 - start1
    ax_dna_all_frames.set_xlim([start1 - 20, end1 + 20])
    ax_dna_all_frames.set_ylim([-5, 21])
    # We also plot a manual backbone beyond the extent of the design
    ax_dna_all_frames.plot([start1 - 20, end1 + 20], [0, 0],
                           color=(0, 0, 0),
                           linewidth=1.0,
                           zorder=1)
    ax_dna_all_frames.axis('off')

    plt.subplots_adjust(hspace=.001,
                        left=.01,
                        right=.99,
                        top=0.99,
                        bottom=0.01)
    # Save the figure
    fig.savefig(output_prefix + '.pdf', transparent=True)
    fig.savefig(output_prefix + '.png', dpi=300)
    # Clear the plotting cache
    plt.close('all')
Esempio n. 9
0
def main():
    parser = argparse.ArgumentParser(
        description="Plot RNAseq profile from predicted RPU."
    )
    parser.add_argument("--ucf", "-u",
                        required=True, help="UCF file.", metavar="FILE")
    parser.add_argument("--netlist", "-n",
                        required=True, help="Netlist.", metavar="FILE")
    parser.add_argument("--output", "-o",
                        required=False, help="Output file.", metavar="FILE")
    args = parser.parse_args()

    with open(args.ucf, 'r') as ucf_file:
        ucf = pycello2.ucf.UCF(json.load(ucf_file))
    with open(args.netlist, 'r') as netlist_file:
        netlist = pycello2.netlist.Netlist(json.load(netlist_file), ucf)

    designs = pycello2.dnaplotlib.get_designs(netlist)

    fig = plt.figure(figsize=(5, len(designs)*1))

    h_frac = 1./len(designs)
    w_pad = 0.05
    for i, design in enumerate(designs):
        width = (1. - w_pad*(len(design) - 1))
        left = 0.0
        seq_len = 0
        for group in design:
            seq_len += group[-1]['end']
        for j, group in enumerate(design):
            w_frac = group[-1]['end'] / seq_len * width
            # Set up the axes for the genetic constructs
            rect = [left, i*h_frac, w_frac, h_frac]
            left += w_frac + w_pad
            ax = fig.add_axes(rect)

            # Create the DNAplotlib renderer
            dr = dpl.DNARenderer()

            # Redender the DNA to axis
            start, end = dr.renderDNA(ax, group, dr.trace_part_renderers())
            ax.set_xlim([start, end])
            ax.set_ylim([-5, 10])
            ax.set_aspect('auto')
            ax.set_xticks([])
            ax.set_yticks([])
            ax.axis('off')

    if (args.output):
        out_file = args.output
    else:
        out_file = 'out'
        plt.savefig(out_file + '.png')
Esempio n. 10
0
def plot_trace_3_axes(designs, output_prefix):
    design_frame1 = designs[0]
    design_frame2 = designs[1]
    design_frame3 = designs[2]

    # Create the figure and all axes to draw to
    fig = plt.figure(figsize=(3.2, 1.2))
    gs = gridspec.GridSpec(3, 1, height_ratios=[0.5, 0.5, 0.75])
    ax_dna_frame1 = plt.subplot(gs[2])
    ax_dna_frame2 = plt.subplot(gs[1], sharex=ax_dna_frame1)
    ax_dna_frame3 = plt.subplot(gs[0], sharex=ax_dna_frame1)

    # Redender the DNA
    dr = dpl.DNARenderer(scale=5, linewidth=0.9)
    start1, end1 = dr.renderDNA(ax_dna_frame1,
                                design_frame1,
                                dr.trace_part_renderers(),
                                plot_backbone=True)
    dna_len = end1 - start1
    ax_dna_frame1.set_xlim([start1 - 20, end1 + 20])
    ax_dna_frame1.set_ylim([-3.5, 7])
    # We also plot a manual backbone beyond the extent of the design
    ax_dna_frame1.plot([start1 - 20, end1 + 20], [0, 0],
                       color=(0, 0, 0),
                       linewidth=1.0,
                       zorder=1)
    ax_dna_frame1.axis('off')

    start2, end2 = dr.renderDNA(ax_dna_frame2,
                                design_frame2,
                                dr.trace_part_renderers(),
                                plot_backbone=False)
    ax_dna_frame2.set_ylim([-3.5, 3.5])
    ax_dna_frame2.axis('off')

    start3, end3 = dr.renderDNA(ax_dna_frame3,
                                design_frame3,
                                dr.trace_part_renderers(),
                                plot_backbone=False)
    ax_dna_frame3.set_ylim([-3.5, 3.5])
    ax_dna_frame3.axis('off')

    plt.subplots_adjust(hspace=.001,
                        left=.01,
                        right=.99,
                        top=0.99,
                        bottom=0.01)
    # Save the figure
    fig.savefig(output_prefix + '.pdf', transparent=True)
    fig.savefig(output_prefix + '.png', dpi=300)
    # Clear the plotting cache
    plt.close('all')
Esempio n. 11
0
def plotConstruct(DNA_construct_obj,dna_renderer=None,\
                                    rna_renderer=None,\
                                    plot_rnas=False,debug=False,showlabels = None,plot_dna_test=True):
    """helper function for making dnaplotlib plots of a DNA_construct object. Plots the
    DNAs and the RNAs that come from that DNA, using DNA_construct.explore_txtl"""
    #TODO: make the label showing more general
    if (showlabels is None):
        showlabels = []
    if (PLOT_DNA and plot_dna_test):
        if (dna_renderer is None):
            dna_renderer = dpl.DNARenderer(scale=5, linewidth=3)
        if (rna_renderer is None):
            rna_renderer = dpl.DNARenderer(scale=5,
                                           linewidth=3,
                                           linecolor=(1, 0, 0))

    design = make_dpl_from_construct(DNA_construct_obj, showlabels=showlabels)
    circular = DNA_construct_obj.circular
    if (PLOT_DNA and plot_dna_test):
        plotDesign(design,
                   circular=circular,
                   title=DNA_construct_obj.get_species())
        if (plot_rnas):
            rnas, proteins = DNA_construct_obj.explore_txtl()
            for promoter in rnas:
                rnadesign = make_dpl_from_construct(rnas[promoter],
                                                    showlabels=showlabels)
                rnacolor = rna_renderer.linecolor
                for part in rnadesign:
                    if ("edgecolor" not in part['opts']):
                        part['opts'].update({'edgecolor': rnacolor})
                plotDesign(rnadesign,
                           renderer=rna_renderer,
                           title=rnas[promoter].get_species())
    else:
        print(DNA_construct_obj.show())
Esempio n. 12
0
for idx1 in range(len(seq)):
    for idx2 in range(len(seq)):
        if h_matrix_60[idx1, idx2] == 1:
            h_matrix[idx1, idx2] = 60
        elif h_matrix_30[idx1, idx2] == 1:
            h_matrix[idx1, idx2] = 25
        elif h_matrix_15[idx1, idx2] == 1:
            h_matrix[idx1, idx2] = 10

# Create the figure and all axes to draw to
fig = plt.figure(figsize=(3.2, 3.4))
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 9], height_ratios=[1.6, 9])
ax_dna_x = plt.subplot(gs[1])

# Redender the DNA
dr = dpl.DNARenderer(scale=1, linewidth=0.9)
start, end = dr.renderDNA(ax_dna_x,
                          design,
                          dr.trace_part_renderers(),
                          regs=regs,
                          reg_renderers=dr.std_reg_renderers())

# Set bounds and display options for the DNA axis
dna_len = end - start
ax_dna_x.set_xlim([start, end])
ax_dna_x.set_ylim([-6, 13])
ax_dna_x.plot([start - 20, end + 20], [0, 0],
              color=(0, 0, 0),
              linewidth=1.0,
              zorder=1)
ax_dna_x.axis('off')
Esempio n. 13
0
    def visualize(cls, circuit_library, feature_library, min_features):
        lw = 0.75

        dr = dpl.DNARenderer()

        part_renderers = dr.SBOL_part_renderers()

        reg_renderers = dr.std_reg_renderers()
        reg_renderers['CurvedRepression'] = curved_repression
        reg_renderers['CurvedActivation'] = curved_activation

        k = 0

        for circuit in circuit_library.circuits:
            if len(circuit.features) > min_features:
                print('Visualizing ' + circuit.identity)

                k = k + 1

                designs = []

                part_dict = {}

                for feature in circuit.features:
                    comp_definition = feature_library.get_definition(
                        feature.identity)

                    if comp_definition is not None and BIOPAX_DNA in comp_definition.types:
                        design = []

                        located = []

                        for seq_anno in comp_definition.sequenceAnnotations:
                            if seq_anno.component is not None and len(
                                    seq_anno.locations
                            ) == 1 and seq_anno.locations[0].getTypeURI(
                            ) == SBOL_RANGE:
                                sub_comp = comp_definition.components.get(
                                    seq_anno.component)

                                range_location = seq_anno.locations.getRange()

                                located.append(
                                    (range_location.start, range_location.end,
                                     range_location.orientation,
                                     sub_comp.definition, sub_comp.identity))

                        located.sort()

                        max_span = 1

                        for i in range(1, len(located)):
                            span = located[i][0] - located[i - 1][1]

                            if span > max_span:
                                max_span = span

                        for i in range(0, len(located)):
                            if i > 0:
                                span = located[i][0] - located[i - 1][1]

                                if span > 0:
                                    normal_span = int(span / max_span * 60)
                                else:
                                    normal_span = 0

                                if normal_span > 0:
                                    design.append({
                                        'type': 'EmptySpace',
                                        'fwd': True,
                                        'opts': {
                                            'x_extent': normal_span
                                        }
                                    })

                            feature_definition = feature_library.get_definition(
                                located[i][3])

                            part = {'opts': {}}

                            for role in feature_definition.roles:
                                if role in cls.SO_DICT:
                                    part['type'] = cls.SO_DICT[role]
                                elif 'type' not in part:
                                    part['type'] = 'UserDefined'

                            if part['type'] == 'CDS':
                                part['opts']['arrowhead_height'] = 0

                            part['name'] = located[i][4]

                            if part['type'] == 'CDS' or part[
                                    'type'] == 'promoter':
                                if feature_definition.name is None:
                                    part['opts'][
                                        'label'] = feature_definition.displayId
                                else:
                                    part['opts'][
                                        'label'] = feature_definition.name

                                part['opts']['label_y_offset'] = -30
                                part['opts']['label_size'] = 4
                                if part['type'] == 'CDS':
                                    part['opts']['label_style'] = 'italic'

                            part['fwd'] = (
                                located[i][2] == SBOL_ORIENTATION_INLINE)

                            if located[i][3] not in part_dict:
                                part_dict[located[i][3]] = []

                            part_dict[located[i][3]].append(part)

                            design.append(part)

                        designs.append(design)

                arcs = []

                for template in circuit.get_feature_identities():
                    for activated in circuit_library.get_activated_by_template(
                            template):
                        for source in part_dict[template]:
                            for sink in part_dict[activated]:
                                arcs.append({
                                    'type': 'CurvedActivation',
                                    'from_part': source,
                                    'to_part': sink,
                                    'opts': {
                                        'color': cls.COLOR['green'],
                                        'linewidth': lw,
                                        'arc_height_start': 15,
                                        'arc_height_end': 15,
                                        'rad': -0.4
                                    }
                                })

                    for repressed in circuit_library.get_repressed_by_template(
                            template):
                        for source in part_dict[template]:
                            for sink in part_dict[repressed]:
                                arcs.append({
                                    'type': 'CurvedRepression',
                                    'from_part': source,
                                    'to_part': sink,
                                    'opts': {
                                        'color': cls.COLOR['red'],
                                        'linewidth': lw,
                                        'arc_height_start': 15,
                                        'arc_height_end': 15,
                                        'rad': -0.4
                                    }
                                })

                fig = plt.figure(figsize=(2.2, 1.8))
                gs = gridspec.GridSpec(len(designs), 1)

                dna_axes = []

                for i in range(0, len(designs)):
                    dna_axes.append(plt.subplot(gs[i]))

                for i in range(0, len(designs)):
                    dna_axis = plt.subplot(gs[i])
                    start, end = dr.renderDNA(dna_axis,
                                              designs[i],
                                              part_renderers,
                                              regs=arcs,
                                              reg_renderers=reg_renderers)
                    # start, end = dr.renderDNA(ax_dna1, design1, part_renderers, regs=reg1, reg_renderers=reg_renderers)
                    dna_axis.set_xlim([start, end])
                    dna_axis.set_ylim([-25, 25])
                    dna_axis.set_aspect('equal')
                    dna_axis.set_xticks([])
                    dna_axis.set_yticks([])
                    dna_axis.axis('off')

                plt.subplots_adjust(hspace=0.01,
                                    left=0.05,
                                    right=0.95,
                                    top=0.92,
                                    bottom=0.01)

                fig.savefig('test_circuit' + str(k) + '.pdf', transparent=True)
                fig.savefig('test_circuit' + str(k) + '.png', dpi=300)

                plt.close('all')

                logging.info('Finished visualizing %s.\n', circuit.identity)
            else:
                logging.warning('Failed to visualize %s.\n', circuit.identity)
def plot_sequence(seq=None,
                  seq_name=None,
                  start_position=None,
                  end_position=None,
                  seq_label=None,
                  seq_label_pos='left',
                  glyph_labels={},
                  ignore_names=[],
                  cds_split_char='',
                  cds_colors={},
                  cds_label_colors={},
                  chromosomal_locus=None,
                  chromosomal_locus_pos='left',
                  ax=None,
                  ax_x_extent=250,
                  ax_x_alignment='center',
                  ax_ylim=(-15, 15),
                  savefig=None):
    """
    Plot a specified benchling sequence as SBOL visual

    Parameters
    ----------
    seq : benchlingclient.DNASequence
        Sequence to be plotted. Can be omitted if `seq_name` is provided.
    seq_name : str, optional
        Name of the sequence to load and plot. Ignored if `seq` is
        specified.
    start_position, end_position : int, optional
        Only annotations in the sequence completely contained by the range
        given by these two parameters will be plotted.
    seq_label : str, optional
        If specified, the text specified in `seq_label` will be added to either
        the left or right side of the sequence diagram, depending on the
        contents of `seq_label_pos`.
    seq_label_pos : {'left', 'right'}, optional
        Whether to add the label in `seq_label` to the left or right side of
        the sequence diagram.
    glyph_labels : dict, optional
        Dictionary with ``name: label`` pairs that specify a glyph's label,
        when the label is different than the name. If a part's name is not
        a key of `glyph_labels`, the name will be used as the glyph's label.
    ignore_names : list, optional
        Names of parts that should not be plotted.
    cds_split_char : str, optionsl
        If specified, a CDS whose name contains `cds_split_char` as a
        substring will be split along this substring and shown as a
        multipart CDS. A multipart CDS looks like a single CDS divided into
        many fragments, each with its own label and color that can be
        specified in `glyph_labels`, `cds_colors`, and `cds_label_colors`.
    cds_colors : dict, optional
        Dictionary with ``name: color`` pairs that specify a CDS' face
        color, when the color is different than the one specified by
        ``RENDER_OPT['CDS']``.
    cds_label_colors : dict, optional
        Dictionary with ``name: label_color`` pairs that specify a CDS'
        label color, when the color is different than the one specified by
        ``RENDER_OPT['CDS']``.
    chromosomal_locus : str, optional
        If specified, a pair of "ChromosomalLocus" glyphs will be added to
        both sides of the rendered design, and a label with the text given
        by `chromosomal_locus` on the glyph specified by
        `chromosomal_locus_pos`.
    chromosomal_locus_pos : {'left', 'right', 'both', 'none'}, optional
        Location of the chromosomal locus label.
    ax : matplotlib.axes, optional
        Axes to draw into.
    ax_x_extent : float, optinal
        Range covered by the x axis limits.
    ax_x_alignment : {'left', 'center', 'right'}
        Alignment of the rendered diagram in the x axis.
    ax_ylim : tuple-like, optional
        Y axis limits.
    savefig : str, optional
        If specified, save figure with a filename given by `savefig`.

    Raises
    ------
    ValueError
        If more than one sequence with the name given by `seq_name` was
        found.

    """
    # If seq is provided, the following is not executed.
    # If not, load from seq_name
    if seq is None:
        if seq_name is not None:
            # Load sequence from benchling
            seq_list = benchlingclient.DNASequence.list_all(name=seq_name)
            # Test that only one sequence has been found
            if len(seq_list) > 1:
                raise ValueError("more than one sequence found with name {}".\
                    format(seq_name))
            elif len(seq_list) < 1:
                raise ValueError("no sequence with name {} found".\
                    format(seq_name))
            seq = seq_list[0]
        else:
            # No sequence or sequence name provided, raise exception
            raise ValueError("seq or seq_name should be provided")

    # Get annotations
    annotations = seq.annotations.copy()

    # Remove annotations outside of range specified
    if start_position is None:
        start_position = 0
    if end_position is None:
        end_position = seq.length - 1
    annotations_filtered = []
    for annotation in annotations:
        if (annotation.start >= start_position) and \
                (annotation.end <= end_position):
            annotations_filtered.append(annotation)
    annotations = annotations_filtered

    # Sort by start position
    annotations = sorted(annotations, key=lambda x: x.start)

    # Initialize plot
    if ax is None:
        fig, ax = pyplot.subplots()
    # Set axis limits and aspect right away
    # This allows for a more precise estimation of label widths later on
    ax.set_xlim((0, ax_x_extent))
    ax.set_ylim(ax_ylim)
    ax.set_aspect('equal')

    # Iterate and extract parts to be plotted
    parts = []
    for annotation in annotations:
        # Iterate through mapping and select appropriate part type
        match = False
        for mapping in ANN_PARTS_MAPPING:
            if check_annotation_features(annotation, mapping['annotation']):
                match = True
                break
        # Only add part if matching part has been found
        if match:
            part_type = mapping['part']
            part_name = annotation.name
            # Part will be split if type is CDS and a cds_split_char has been
            # specified.
            # All resulting parts, but the last one, will be given the temporary
            # part type "CDSFragment". This is so arrowheads and padding are
            # modified later to make a continuous multipart CDS glyph.
            if cds_split_char and mapping['part'] == 'CDS':
                part_names = part_name.split(cds_split_char)
                # Remove parts flagged to be ignored
                part_names = [p for p in part_names if p not in ignore_names]
                if len(part_names) == 0:
                    continue
                # Reverse if orientation is reverse
                if annotation.strand == -1:
                    part_names = part_names[::-1]
                for part_index, part_name in enumerate(part_names):
                    # Define new part
                    part = {}
                    if annotation.strand == -1:
                        if part_index <= 0:
                            part['type'] = 'CDS'
                        else:
                            part['type'] = 'CDSFragment'
                    else:
                        if part_index < (len(part_names) - 1):
                            part['type'] = 'CDSFragment'
                        else:
                            part['type'] = 'CDS'
                    part['name'] = part_name
                    # Orientation ('fwd') will be False if the reverse strand is
                    # explicitly specified in the annotation, True if any other
                    # value, not specified if None.
                    if annotation.strand is not None:
                        part['fwd'] = not (annotation.strand == -1)
                    # Save part
                    parts.append(part)
            else:
                # Check if part name is flagged to be ignored
                if part_name in ignore_names:
                    continue
                # Define new part
                part = {}
                part['type'] = part_type
                part['name'] = part_name
                # Orientation ('fwd') will be False if the reverse strand is
                # explicitly specified in the annotation, True if any other
                # value, not specified if None.
                if annotation.strand is not None:
                    part['fwd'] = not (annotation.strand == -1)
                # Save part
                parts.append(part)

    # Construct plotting options for each part
    for part_index, part in enumerate(parts):
        # Initialize dictionary with rendering options
        opts = {}

        # GENERAL TYPE-DEPENDENT RENDERING OPTIONS
        # ========================================

        # Get opts from RENDER_OPT if available
        if part['type'] == 'CDSFragment':
            # CDSFragment combines options from 'CDS' and 'CDSFragment', with
            # the latter taking precedence.
            part_type_opts = RENDER_OPT.get('CDSFragment', {})
            part_type_opts_cds = RENDER_OPT.get('CDS', {})
            for k, v in part_type_opts_cds.items():
                if k not in part_type_opts:
                    part_type_opts[k] = v
        else:
            part_type_opts = RENDER_OPT.get(part['type'], {})

        # PART-SPECIFIC RENDERING OPTIONS
        # ===============================

        # The following deals with issues specific to the type "CDSFragment"
        # 'CDSFragment' does not have an arrowhead
        if part['type'] == 'CDSFragment':
            opts['arrowhead_length'] = 0
            opts['arrowhead_height'] = 0
        # Correction for label_x_offset
        # Removing padding will affect how the CDS looks but not the label,
        # therefore the label offset has to be corrected.
        label_x_offset_c = 0
        if ('fwd' in part) and (part['fwd'] == False):
            # Start padding is zero if there is a 'CDS' or CDSFragment' to the
            # left
            if part['type'] == 'CDSFragment':
                if (part_index > 0) and \
                        (parts[part_index-1]['type'] in ['CDS', 'CDSFragment']):
                    opts['end_pad'] = 0
                    label_x_offset_c += part_type_opts.get('end_pad', 0) / 2
            # End padding is zero if there is a 'CDSFragment' to the right
            if part['type'] in ['CDS', 'CDSFragment']:
                if (part_index < (len(parts)-1)) and \
                        (parts[part_index+1]['type']=='CDSFragment'):
                    opts['start_pad'] = 0
                    label_x_offset_c -= part_type_opts.get('start_pad', 0) / 2
        else:
            # Start padding is zero if there is a 'CDSFragment' to the left
            if part['type'] in ['CDS', 'CDSFragment']:
                if (part_index > 0) and \
                        (parts[part_index-1]['type']=='CDSFragment'):
                    opts['start_pad'] = 0
                    label_x_offset_c -= part_type_opts.get('start_pad', 0) / 2
            # End padding is zero if there is a 'CDS' or 'CDSFragment' to the
            # right
            if part['type'] == 'CDSFragment':
                if (part_index < (len(parts)-1)) and \
                        (parts[part_index+1]['type'] in ['CDS', 'CDSFragment']):
                    opts['end_pad'] = 0
                    label_x_offset_c += part_type_opts.get('end_pad', 0) / 2

        # Colors for CDS glyph and label
        if part['type'] in ['CDS', 'CDSFragment']:
            if part['name'] in cds_colors:
                opts['color'] = cds_colors[part['name']]
            if part['name'] in cds_label_colors:
                opts['label_color'] = cds_label_colors[part['name']]

        # Some elements in RENDER_OPT can be functions, in which case the
        # actual value is computed by calling that function with the label width
        # as an argument.
        # Label is taken from the glyph_labels dictionary, or from the name.
        label = glyph_labels.get(part['name'], part['name'])
        opts['label'] = label
        # Method to calculate label_width from "https://stackoverflow.com/\
        # questions/24581194/matplotlib-text-bounding-box-dimensions"
        t = ax.text(0,
                    0,
                    label,
                    fontsize=part_type_opts.get('label_size', 7),
                    fontstyle=part_type_opts.get('label_style', 'normal'))
        bb = t.get_window_extent(renderer=ax.figure.canvas.get_renderer())
        bb_datacoords = bb.transformed(ax.transData.inverted())
        label_width = bb_datacoords.width
        t.remove()

        # Iterate over options
        for k, v in part_type_opts.items():
            if k in opts:
                # Don't override specific options established above
                continue
            elif hasattr(v, '__call__'):
                # Evaluate option based on label width
                opts[k] = v(label_width)
            else:
                # Special case: label_y_offset is modified depending on the
                # orientation of the part
                if k == 'label_y_offset':
                    if ('fwd' in part) and (not part['fwd']):
                        opts[k] = -v
                    else:
                        opts[k] = v
                # Special case: label_x_offset is modified depending on the
                # orientation of the part and an offset correction
                elif k == 'label_x_offset':
                    if ('fwd' in part) and (not part['fwd']):
                        opts[k] = -(v + label_x_offset_c)
                    else:
                        opts[k] = v + label_x_offset_c
                else:
                    opts[k] = v

        # Add options
        part['opts'] = opts

    # 'CDSFragment' is not a real dnaplotlib part type. Change it to 'CDS'
    for part in parts:
        if part['type'] == 'CDSFragment':
            part['type'] = 'CDS'

    # Define renderer options
    sequence_opts = RENDER_OPT.get('Sequence', {})
    backbone_linewidth = sequence_opts.get('backbone_linewidth', 1)
    if chromosomal_locus is not None:
        backbone_pad_left = -2 * backbone_linewidth
        backbone_pad_right = -2 * backbone_linewidth
    else:
        backbone_pad_left = 0
        backbone_pad_right = 0

    # Add chromosomal locus parts if specified
    if chromosomal_locus is not None:
        # 5' glyph
        cl5 = {}
        cl5['type'] = '5ChromosomalLocus'
        cl5['name'] = 'cl5_{}'.format(chromosomal_locus)
        cl5['fwd'] = True
        opts = RENDER_OPT.get('5ChromosomalLocus', {}).copy()
        if chromosomal_locus_pos in ['left', 'both']:
            opts['label'] = chromosomal_locus
        opts['linewidth'] = backbone_linewidth
        cl5['opts'] = opts
        # 3' glyph
        cl3 = {}
        cl3['type'] = '3ChromosomalLocus'
        cl3['name'] = '3cl_{}'.format(chromosomal_locus)
        opts = RENDER_OPT.get('3ChromosomalLocus', {}).copy()
        if chromosomal_locus_pos in ['right', 'both']:
            opts['label'] = chromosomal_locus
        opts['linewidth'] = backbone_linewidth
        cl3['opts'] = opts
        # Save glyphs
        parts = [cl5] + parts + [cl3]

    # Create the DNAplotlib renderer
    dr = dnaplotlib.DNARenderer(
        linewidth=backbone_linewidth,
        backbone_pad_left=backbone_pad_left,
        backbone_pad_right=backbone_pad_right,
    )

    # Render the DNA to axis
    start, end = dr.renderDNA(ax, parts, dr.SBOL_part_renderers())

    # Add sequence label if specified
    if seq_label is not None:
        # Compute offsets
        seq_label_x_offset = sequence_opts.get('label_x_offset', 0)
        seq_label_y_offset = sequence_opts.get('label_y_offset', 0)
        # Compute horizontal position of label
        if seq_label_pos == 'left':
            x = start + seq_label_x_offset
        elif seq_label_pos == 'right':
            x = end + seq_label_x_offset
        # Create label
        t = ax.text(
            x,
            seq_label_y_offset,
            seq_label,
            fontsize=sequence_opts.get('label_size', 10),
            horizontalalignment=sequence_opts.get('label_x_alignment', 'left'),
            verticalalignment='center',
            zorder=50,
        )

        # Modify 'start' or 'end' depending on label
        bb = t.get_window_extent(renderer=ax.figure.canvas.get_renderer())
        bb_datacoords = bb.transformed(ax.transData.inverted())
        start = min(start, bb_datacoords.xmin)
        end = max(end, bb_datacoords.xmax)

    # Set x axis limits depending on alignment
    # Note that the extent is always ax_x_extent
    if ax_x_alignment == 'left':
        ax.set_xlim((start, start + ax_x_extent))
    if ax_x_alignment == 'right':
        ax.set_xlim((end - ax_x_extent, end))
    if ax_x_alignment == 'center':
        ax.set_xlim(
            ((start + end - ax_x_extent) / 2, (start + end + ax_x_extent) / 2))
    ax.set_xticks([])
    ax.set_yticks([])
    ax.axis('off')

    if savefig is not None:
        pyplot.savefig(savefig, bbox_inches='tight', dpi=300)
Esempio n. 15
0
def plot_genome(ax_dna, INI_file):
    """
    General Function that plots a genome from an INI file and puts it into a subplot
    """

    # path to the input files (remove the "params.ini" from the path)
    path = INI_file.rpartition("/")[0]
    if path == "":
        path = "."
    path += "/"
    # read the config file
    config = sim.read_config_file(INI_file)
    # get inputs infos from the config file
    GFF_file = path + config.get('INPUTS', 'GFF')
    TSS_file = path + config.get('INPUTS', 'TSS')
    TTS_file = path + config.get('INPUTS', 'TTS')
    Prot_file = path + config.get('INPUTS', 'BARR_FIX')

    SIGMA_0 = config.getfloat('SIMULATION', 'SIGMA_0')
    DELTA_X = config.getfloat('GLOBAL', 'DELTA_X')

    # load and get BARR_FIX positions
    prot = sim.load_tab_file(Prot_file)
    BARR_FIX = prot['prot_pos'].values.astype(int)

    # To draw the beautiful genes we need to read the GFF, TSS and TTS files to get some info ;)
    gff_df_raw = sim.load_gff(GFF_file)
    # to get the cov_bp (a verifier)
    genome_size = sim.get_genome_size(gff_df_raw)
    genome = math.ceil(genome_size / DELTA_X)
    cov_bp = np.arange(0, genome_size, DELTA_X)
    cov_bp = np.resize(cov_bp, genome)

    gff_df = sim.rename_gff_cols(gff_df_raw)

    tss = sim.load_tab_file(TSS_file)
    Kon = tss['TSS_strength'].values

    tts = sim.load_tab_file(TTS_file)
    Poff = tts['TTS_proba_off'].values

    strands = sim.str2num(gff_df['strand'].values)
    tssstrands = sim.str2num(tss["TUorient"].values)

    # Color maps for formatting
    col_map = {}
    col_map['red'] = (0.95, 0.30, 0.25)
    col_map['green'] = (0.38, 0.82, 0.32)
    col_map['blue'] = (0.38, 0.65, 0.87)
    col_map['orange'] = (1.00, 0.75, 0.17)
    col_map['purple'] = (0.55, 0.35, 0.64)
    col_map['yellow'] = (0.98, 0.97, 0.35)
    col_map['grey'] = (0.70, 0.70, 0.70)
    col_map['dark_grey'] = (0.60, 0.60, 0.60)
    col_map['light_grey'] = (0.9, 0.9, 0.9)

    # CDS formatting options
    opt_CDSs = []

    Ps = []
    CDSs = []
    Ts = []

    design = []

    for i in gff_df.index.values:
        opt_CDSs.append({  #'label': 'Gene%s \n%.03f' % (str(i + 1), Kon[i]),
            #'label_style': 'italic',
            #'label_y_offset': -5,
            #'label_size': 9,
            'color': col_map['orange']
        })
        # Design of the construct
        if strands[i] == 1:
            # Coding Sequence
            CDSs.append({
                'type': 'CDS',
                'name': 'CDS%s' % str(i + 1),
                'start': gff_df['start'][i],
                'end': gff_df['end'][i],
                'fwd': gff_df['strand'][i],
                'opts': opt_CDSs[i]
            })
        else:
            # Coding Sequence
            CDSs.append({
                'type': 'CDS',
                'name': 'CDS%s' % str(i + 1),
                'start': gff_df['end'][i],
                'end': gff_df['start'][i],
                'fwd': gff_df['strand'][i],
                'opts': opt_CDSs[i]
            })

        # A design is merely a list of parts and their properties
        if strands[i]:
            #design.append(Ps[i])
            design.append(CDSs[i])
            #design.append(Ts[i])
        else:
            #design.append(Ts[i])
            design.append(CDSs[i])
            #design.append(Ps[i])

    for i in tss.index.values:
        # Design of the construct
        if tssstrands[i] == 1:
            # Promoters
            Ps.append({
                'type': 'Promoter',
                'name': 'P%s' % str(i + 1),
                'start': tss['TSS_pos'][i],
                'end': tss['TSS_pos'][i] + 5,
                'fwd': tssstrands[i],
                'opts': {
                    'color': col_map['green']
                }
            })
        else:
            # Promoters
            Ps.append({
                'type': 'Promoter',
                'name': 'P%s' % str(i + 1),
                'start': tss['TSS_pos'][i],
                'end': tss['TSS_pos'][i] - 5,
                'fwd': tssstrands[i],
                'opts': {
                    'color': col_map['green']
                }
            })
            # A design is merely a list of parts and their properties
        design.append(Ps[i])

    for i in tts.index.values:
        print(i)
        # Terminators
        Ts.append({
            'type': 'Terminator',
            'name': 'T%s' % str(i + 1),
            'start': tts['TTS_pos'][i],
            'end': tts['TTS_pos'][i] + 5,
            'fwd': 1,
            'opts': {
                'color': col_map['red']
            }
        })
        design.append(Ts[i])

    # Redender the DNA
    dr = dpl.DNARenderer(scale=7, linewidth=1)
    start, end = dr.renderDNA(ax_dna, design, dr.trace_part_renderers())

    # Set bounds and display options for the DNA axis
    dna_len = end - start
    ax_dna.set_xlim([cov_bp[0], cov_bp[-1]])  # start-50
    ax_dna.set_ylim([-8, 8])
    # ax_dna.plot(5000, 'ro', markersize=15)
    for xc in BARR_FIX:
        ax_dna.axvline(x=xc, ymin=0.40, ymax=0.60, color='k', linewidth=5)

    ax_dna.plot([cov_bp[0], cov_bp[-1]], [0, 0],
                color=(0, 0, 0),
                linewidth=1.0,
                zorder=1)
    ax_dna.axis('off')
    return SIGMA_0, DELTA_X, BARR_FIX, cov_bp
Esempio n. 16
0
def main():
    parser = argparse.ArgumentParser(
        description="Plot RNAseq profile from predicted RPU.")
    parser.add_argument("--ucf",
                        "-u",
                        required=True,
                        help="UCF file.",
                        metavar="FILE")
    parser.add_argument("--activity-table",
                        "-a",
                        dest="activity",
                        required=True,
                        help="Activity table.",
                        metavar="FILE")
    parser.add_argument("--logic-table",
                        "-l",
                        dest="logic",
                        required=True,
                        help="Logic table.",
                        metavar="FILE")
    parser.add_argument("--netlist",
                        "-n",
                        required=True,
                        help="Netlist.",
                        metavar="FILE")
    parser.add_argument("--output",
                        "-o",
                        required=False,
                        help="Output file.",
                        metavar="FILE")
    parser.add_argument("--debug",
                        "-d",
                        required=False,
                        help="Debug.",
                        action='store_true')
    args = parser.parse_args()

    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(format='%(levelname)s:%(message)s', level=level)

    activity = []
    logic = []
    with open(args.ucf, 'r') as ucf_file:
        ucf = pycello2.ucf.UCF(json.load(ucf_file))
    with open(args.activity, 'r') as activity_file:
        activity_reader = csv.reader(activity_file)
        for row in activity_reader:
            activity.append(row)
    with open(args.logic, 'r') as logic_file:
        logic_reader = csv.reader(logic_file)
        for row in logic_reader:
            logic.append(row)
    with open(args.netlist, 'r') as netlist_file:
        netlist = pycello2.netlist.Netlist(json.load(netlist_file), ucf)

    # dnaplotlib specifications
    designs = pycello2.dnaplotlib.get_designs(netlist)

    placement = netlist.placements[0]

    num_plots = len(logic[0])

    widths = [len(group.sequence) for group in placement.groups]

    fig = plt.figure(figsize=(np.sum(widths) / 650, num_plots))
    gs = fig.add_gridspec(num_plots,
                          len(placement.groups),
                          width_ratios=widths)

    locator = FixedLocator((1e-5, 1e-3, 1e-1, 1e1, 1e3))

    axes = []

    for row in range(num_plots - 1):
        axes_row = []
        axes.append(axes_row)
        for col, group in enumerate(placement.groups):
            sharex = axes[row - 1][col] if row > 0 else None
            sharey = axes[0][0] if (row != 0 or col != 0) else None
            ax = fig.add_subplot(gs[row, col], sharex=sharex, sharey=sharey)
            axes_row.append(ax)

            profile = []
            temp = []
            for component in group.components:
                for part in component.parts:
                    temp.append(1.0)
                    profile.append(100.0)

            iteration = 0
            while (np.max(np.abs(np.array(profile) - np.array(temp))) >
                   TOLERANCE):
                format_str = "state: {:>4d}  group: {:>4d}  iteration: {:>4d}"
                logging.debug(format_str.format(row, col, iteration))
                temp = profile.copy()
                profile = []
                for i, component in enumerate(group.components):
                    for j, part_instance in enumerate(component.parts):
                        # offset to which we add the flux
                        # (readthrough, upstream promoter flux)
                        if j == 0 and i > 0:
                            offset = group.components[i - 1].parts[-1].flux
                        elif j > 0:
                            offset = component.parts[j - 1].flux
                        else:
                            offset = 0.0

                        if part_instance.part.type == 'promoter':
                            upstream_node = pycello2.utils.get_upstream_node(
                                part_instance.part, component.node, netlist)
                            if upstream_node.type == 'PRIMARY_INPUT':
                                delta_flux = float(
                                    get_node_activity(upstream_node,
                                                      activity)[row])
                            else:
                                upstream_components = pycello2.utils.get_components(
                                    upstream_node, placement)
                                input_flux = 0.0
                                for upstream_component in upstream_components:
                                    input_flux += upstream_component.parts[
                                        -2].flux
                                delta_flux = pycello2.utils.evaluate_equation(
                                    upstream_node.gate, {'x': input_flux})
                            part_instance.flux = pycello2.utils.get_ribozyme(
                                component).efficiency * delta_flux + offset
                        if part_instance.part.type == 'ribozyme':
                            part_instance.flux = offset / pycello2.utils.get_ribozyme(
                                component).efficiency
                        if part_instance.part.type in ('cds', 'rbs'):
                            part_instance.flux = offset
                        if part_instance.part.type == 'terminator':
                            part_instance.flux = offset / part_instance.part.strength

                        profile.append(part_instance.flux)

                iteration += 1

            ax.set_yscale('log')
            ax.xaxis.set_major_locator(NullLocator())
            ax.yaxis.set_major_locator(locator)
            if col > 0:
                plt.setp(ax.get_yticklabels(), visible=False)

            x = []
            y = []
            last_x = 0
            last_y = BASAL_TRANSCRIPTION

            for i, component in enumerate(group.components):
                x.append([])
                y.append([])

                for j, part_instance in enumerate(component.parts):
                    if j == 0:
                        initial_x = last_x
                        initial_y = last_y
                    else:
                        initial_x = x[-1][-1]
                        initial_y = y[-1][-1]

                    if part_instance.part.type == 'terminator':
                        x[-1].append(initial_x)
                        x[-1].append(initial_x +
                                     int(0.5 *
                                         len(part_instance.part.sequence)))
                        x[-1].append(initial_x +
                                     int(0.5 *
                                         len(part_instance.part.sequence)))
                        x[-1].append(initial_x +
                                     len(part_instance.part.sequence))
                        y[-1].append(initial_y)
                        y[-1].append(initial_y)
                        y[-1].append(part_instance.flux)
                        y[-1].append(part_instance.flux)
                    elif part_instance.part.type == 'promoter':
                        x[-1].append(initial_x)
                        x[-1].append(initial_x +
                                     len(part_instance.part.sequence))
                        x[-1].append(initial_x +
                                     len(part_instance.part.sequence))
                        y[-1].append(initial_y)
                        y[-1].append(initial_y)
                        y[-1].append(part_instance.flux)
                    elif part_instance.part.type == 'ribozyme':
                        x[-1].append(initial_x)
                        x[-1].append(initial_x + 7)
                        x[-1].append(initial_x + 7)
                        x[-1].append(initial_x +
                                     len(part_instance.part.sequence))
                        y[-1].append(initial_y)
                        y[-1].append(initial_y)
                        y[-1].append(part_instance.flux)
                        y[-1].append(part_instance.flux)
                    else:
                        x[-1].append(initial_x)
                        x[-1].append(initial_x +
                                     len(part_instance.part.sequence))
                        y[-1].append(part_instance.flux)
                        y[-1].append(part_instance.flux)

                if i == 0:
                    pre_x = []
                    pre_y = []
                else:
                    pre_x = [
                        last_x,
                    ]
                    pre_y = [
                        last_y,
                    ]

                x[-1] = pre_x + x[-1]
                y[-1] = pre_y + y[-1]

                last_x = x[-1][-1]
                last_y = y[-1][-1]

            for i, component in enumerate(group.components):
                this_x = np.array(x[i], dtype=np.float64)
                this_y = np.array(y[i], dtype=np.float64)
                ax.plot(this_x, this_y, '-', color='black', lw=1)
                ax.fill_between(this_x, this_y, 1e-10, fc='black', alpha=0.1)

            ax.set_xlim(x[0][0], x[-1][-1])
            ax.set_ylim(1e-4, 1e2)

    for i, group in enumerate(placement.groups):
        ax_dna = fig.add_subplot(gs[-1, i])
        design = designs[0][i]
        for part in design:
            if part['type'] == 'Promoter':
                part['opts']['x_extent'] = np.sum(widths) / 30
            if part['type'] == 'Terminator':
                part['opts']['x_extent'] = np.sum(widths) / 100
            if part['type'] == 'CDS':
                part['opts']['arrowhead_length'] = np.sum(widths) / 50
                part['opts']['y_extent'] = 1

        dr = dpl.DNARenderer()
        start, end = dr.renderDNA(ax_dna, design, dr.trace_part_renderers())
        ax_dna.set_xlim([start, end])
        ax_dna.set_ylim([-5, 10])
        ax_dna.set_aspect('auto')
        ax_dna.axis('off')

    label_x = 0.02
    label_y = (1.0 + (1.0 / num_plots)) / 2.0
    fig.text(label_x,
             label_y,
             "predicted transcription (RPU)",
             va='center',
             ha='center',
             rotation='vertical')

    if (args.output):
        out_file = args.output
    else:
        out_file = 'out'

    plt.tight_layout(rect=[0.025, 0., 1., 1.])
    plt.subplots_adjust(hspace=0.0, wspace=0.1)
    plt.savefig(out_file + '.png', bbox_to_inches='tight')
Esempio n. 17
0
    def plot(self, circuits, total_gates, total_time, option, num):
        # Colour map
        col_map = {}
        col_map[0] = '#e31414'  #red
        col_map[1] = '#34e681'  #green
        col_map[2] = '#34a4e6'  #blue
        col_map[3] = '#ff7b00'  #orange
        col_map[4] = '#44855a'  #dark green
        col_map[5] = '#1831c4'  #dark blue
        col_map[6] = '#9918c4'  #indigo
        col_map[7] = '#e6178f'  #violet
        col_map[8] = '#995f81'  #purple

        for i in range(len(circuits)):
            file_num = SortNum(i, option) + 1
            if Total_Gates(i) <= total_gates and Total_time(
                    i
            ) <= total_time and file_num <= num:  #If Total Delay and number of gates are less than the input
                fig = plt.figure()
                design = []  #A list to be gathered to draw
                reg = []  #To store the Repression Lines
                color = 0  #A number to assign colors in order to coordinate with Logical Representation
                use = []  #To temporarily store the second input of NOR Gate
                coding_seq = [
                ]  #A List to temporarily hold coding sequences from each gate
                seperate = []
                for j in range(len(circuits[i])):
                    if j == 0:
                        All_gates = circuits[i][0].split(' ----|')
                        FP = All_gates[-1].split('-> ')[
                            -1]  #YFP for our case right now
                        for k in range(len(All_gates)):
                            gate = All_gates[k].split('-> ')
                            if FP not in gate[-1]:
                                if len(gate) == 2:  #NOT Gate
                                    if k == 0:  #Append all the parts in a list
                                        promotor = {
                                            'type': 'Promoter',
                                            'name': gate[0],
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'label': gate[0],
                                                'label_x_offset': -5,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                        design.append(promotor)
                                        u = {
                                            'type': 'RBS',
                                            'name': 'u' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -6,
                                                'x_extent': 6
                                            }
                                        }
                                        design.append(u)
                                        cds = {
                                            'type': 'CDS',
                                            'name': gate[1],
                                            'opts': {
                                                'color': col_map[color],
                                                'edge_color': col_map[color],
                                                'x_extent': 24,
                                                'label': gate[1],
                                                'label_color': (1, 1, 1),
                                                'label_style': 'italic',
                                                'label_x_offset': -1,
                                                'label_size': 6
                                            }
                                        }
                                        design.append(cds)
                                        coding_seq.append(cds)
                                        terminator = {
                                            'type': 'Terminator',
                                            'name': 't' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -1
                                            }
                                        }
                                        design.append(terminator)

                                    else:  #If it's not the first gate than it will contain the repression interaction form the previous gate
                                        promotor = {
                                            'type': 'Promoter',
                                            'name': gate[0],
                                            'opts': {
                                                'color': col_map[color],
                                                'label': gate[0],
                                                'label_x_offset': -5,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                        rep = {
                                            'type': 'Repression',
                                            'from_part': coding_seq[0],
                                            'to_part': promotor,
                                            'opts': {
                                                'color': col_map[color],
                                                'arc_height': 20
                                            }
                                        }
                                        design.append(promotor)
                                        reg.append(rep)
                                        coding_seq.pop(0)
                                        color += 1  #Change color once the repression intercation is created
                                        u = {
                                            'type': 'RBS',
                                            'name': 'u' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -6,
                                                'x_extent': 6
                                            }
                                        }
                                        design.append(u)
                                        cds = {
                                            'type': 'CDS',
                                            'name': gate[1],
                                            'opts': {
                                                'color': col_map[color],
                                                'edge_color': col_map[color],
                                                'x_extent': 24,
                                                'label': gate[1],
                                                'label_color': (1, 1, 1),
                                                'label_style': 'italic',
                                                'label_x_offset': -1,
                                                'label_size': 6
                                            }
                                        }
                                        design.append(cds)
                                        coding_seq.append(cds)
                                        terminator = {
                                            'type': 'Terminator',
                                            'name': 't' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -1
                                            }
                                        }
                                        design.append(terminator)

                                elif len(gate) == 3:  #NOR Gate
                                    if k == 0:
                                        promotor1 = {
                                            'type': 'Promoter',
                                            'name': gate[0],
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'label': gate[0],
                                                'label_x_offset': -6,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                        design.append(promotor1)
                                        if gate[1] in baseList(
                                        ):  #If the input is one of PTet, PTac or PBad in our case, the color should be black
                                            promotor2 = {
                                                'type': 'Promoter',
                                                'name': gate[1],
                                                'opts': {
                                                    'color': (0, 0, 0),
                                                    'label': gate[1],
                                                    'label_x_offset': -1,
                                                    'label_y_offset': -4,
                                                    'label_size': 5
                                                }
                                            }
                                        else:  #Other wise tthe color is stored so it can be assigned to its repression
                                            promotor2 = {
                                                'type': 'Promoter',
                                                'name': gate[1],
                                                'opts': {
                                                    'color': col_map[color],
                                                    'label': gate[1],
                                                    'label_x_offset': -1,
                                                    'label_y_offset': -4,
                                                    'label_size': 5
                                                }
                                            }
                                            use.append((promotor2, color))
                                            color += 1
                                        design.append(promotor2)
                                        u = {
                                            'type': 'RBS',
                                            'name': 'u' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -6,
                                                'x_extent': 6
                                            }
                                        }
                                        design.append(u)
                                        cds = {
                                            'type': 'CDS',
                                            'name': gate[2],
                                            'opts': {
                                                'color': col_map[color],
                                                'edge_color': col_map[color],
                                                'x_extent': 24,
                                                'label': gate[2],
                                                'label_color': (1, 1, 1),
                                                'label_style': 'italic',
                                                'label_x_offset': -1,
                                                'label_size': 6
                                            }
                                        }
                                        design.append(cds)
                                        coding_seq.append(cds)
                                        terminator = {
                                            'type': 'Terminator',
                                            'name': 't' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -1
                                            }
                                        }
                                        design.append(terminator)

                                    else:
                                        promotor1 = {
                                            'type': 'Promoter',
                                            'name': gate[0],
                                            'opts': {
                                                'color': col_map[color],
                                                'label': gate[0],
                                                'label_x_offset': -6,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                        rep = {
                                            'type': 'Repression',
                                            'from_part': coding_seq[0],
                                            'to_part': promotor1,
                                            'opts': {
                                                'color': col_map[color],
                                                'arc_height': 20
                                            }
                                        }
                                        design.append(promotor1)
                                        reg.append(rep)
                                        coding_seq.pop(0)
                                        color += 1
                                        if gate[1] in baseList():
                                            promotor2 = {
                                                'type': 'Promoter',
                                                'name': gate[1],
                                                'opts': {
                                                    'color': (0, 0, 0),
                                                    'label': gate[1],
                                                    'label_x_offset': -1,
                                                    'label_y_offset': -4,
                                                    'label_size': 5
                                                }
                                            }
                                        else:
                                            promotor2 = {
                                                'type': 'Promoter',
                                                'name': gate[1],
                                                'opts': {
                                                    'color': col_map[color],
                                                    'label': gate[1],
                                                    'label_x_offset': -1,
                                                    'label_y_offset': -4,
                                                    'label_size': 5
                                                }
                                            }
                                            use.append((promotor2, color))
                                            color += 1
                                        design.append(promotor2)
                                        u = {
                                            'type': 'RBS',
                                            'name': 'u' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -6,
                                                'x_extent': 6
                                            }
                                        }
                                        design.append(u)
                                        cds = {
                                            'type': 'CDS',
                                            'name': gate[2],
                                            'opts': {
                                                'color': col_map[color],
                                                'edge_color': col_map[color],
                                                'x_extent': 24,
                                                'label': gate[2],
                                                'label_color': (1, 1, 1),
                                                'label_style': 'italic',
                                                'label_x_offset': -1,
                                                'label_size': 6
                                            }
                                        }
                                        design.append(cds)
                                        coding_seq.append(cds)
                                        terminator = {
                                            'type': 'Terminator',
                                            'name': 't' + str(color),
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'start_pad': -1
                                            }
                                        }
                                        design.append(terminator)

                            else:
                                if len(gate) == 2:  #YFP CDS
                                    promotor = {
                                        'type': 'Promoter',
                                        'name': gate[0],
                                        'opts': {
                                            'color': col_map[color],
                                            'label': gate[0],
                                            'label_x_offset': -5,
                                            'label_y_offset': -4,
                                            'label_size': 5
                                        }
                                    }
                                    rep = {
                                        'type': 'Repression',
                                        'from_part': coding_seq[0],
                                        'to_part': promotor,
                                        'opts': {
                                            'color': col_map[color],
                                            'arc_height': 20
                                        }
                                    }
                                    design.append(promotor)
                                    reg.append(rep)
                                    coding_seq.pop(0)
                                    color += 1
                                    u = {
                                        'type': 'RBS',
                                        'name': 'u' + str(color),
                                        'opts': {
                                            'color': (0, 0, 0),
                                            'start_pad': -6,
                                            'x_extent': 6
                                        }
                                    }
                                    design.append(u)
                                    cds = {
                                        'type': 'CDS',
                                        'name': gate[1],
                                        'opts': {
                                            'color': (1, 1, 1),
                                            'edge_color': (0, 0, 0),
                                            'x_extent': 24,
                                            'label': gate[1],
                                            'label_color': (0, 0, 0),
                                            'label_style': 'italic',
                                            'label_x_offset': -1,
                                            'label_size': 6
                                        }
                                    }
                                    design.append(cds)
                                    coding_seq.append(cds)
                                    terminator = {
                                        'type': 'Terminator',
                                        'name': 't' + str(color),
                                        'opts': {
                                            'color': (0, 0, 0),
                                            'start_pad': -1
                                        }
                                    }
                                    design.append(terminator)

                                elif len(gate) == 3:  #OR Gate for YFP
                                    promotor1 = {
                                        'type': 'Promoter1',
                                        'name': gate[0],
                                        'opts': {
                                            'color': col_map[color],
                                            'label': gate[0],
                                            'label_x_offset': -6,
                                            'label_y_offset': -4,
                                            'label_size': 5
                                        }
                                    }
                                    rep = {
                                        'type': 'Repression',
                                        'from_part': coding_seq[0],
                                        'to_part': promotor1,
                                        'opts': {
                                            'color': col_map[color],
                                            'arc_height': 20
                                        }
                                    }
                                    design.append(promotor1)
                                    reg.append(rep)
                                    coding_seq.pop(0)
                                    color += 1
                                    if gate[1] in baseList():
                                        promotor2 = {
                                            'type': 'Promoter2',
                                            'name': gate[1],
                                            'opts': {
                                                'color': (0, 0, 0),
                                                'label': gate[1],
                                                'label_x_offset': -1,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                    else:
                                        promotor2 = {
                                            'type': 'Promoter2',
                                            'name': gate[1],
                                            'opts': {
                                                'color': col_map[color],
                                                'label': gate[1],
                                                'label_x_offset': -1,
                                                'label_y_offset': -4,
                                                'label_size': 5
                                            }
                                        }
                                        use.append((promotor2, color))
                                        color += 1
                                    design.append(promotor2)
                                    u = {
                                        'type': 'RBS',
                                        'name': 'u' + str(color),
                                        'opts': {
                                            'color': (0, 0, 0),
                                            'start_pad': -6,
                                            'x_extent': 6
                                        }
                                    }
                                    design.append(u)
                                    cds = {
                                        'type': 'CDS',
                                        'name': gate[2],
                                        'opts': {
                                            'color': (1, 1, 1),
                                            'edge_color': (0, 0, 0),
                                            'x_extent': 24,
                                            'label': gate[2],
                                            'label_color': (0, 0, 0),
                                            'label_style': 'italic',
                                            'label_x_offset': -1,
                                            'label_size': 6
                                        }
                                    }
                                    design.append(cds)
                                    coding_seq.append(cds)
                                    terminator = {
                                        'type': 'Terminator',
                                        'name': 't' + str(color),
                                        'opts': {
                                            'color': (0, 0, 0),
                                            'start_pad': -1
                                        }
                                    }
                                    design.append(terminator)

                    else:  #For the rest of the lines
                        endbracket = len(
                            circuits[i][j]) - circuits[i][j][-1::-1].index(")")
                        All_gates = circuits[i][j][:endbracket].split(' ----|')
                        for k in range(len(All_gates)):
                            gate = All_gates[k].split('-> ')
                            if len(gate) == 2:
                                terminator = {
                                    'type': 'Terminator',
                                    'name': 't' + str(color + 2),
                                    'opts': {
                                        'color': (0, 0, 0),
                                        'start_pad': -1
                                    }
                                }
                                cds_color = use[-1][1]
                                cds = {
                                    'type': 'CDS',
                                    'name': gate[1],
                                    'opts': {
                                        'color': col_map[cds_color],
                                        'edge_color': col_map[cds_color],
                                        'x_extent': 24,
                                        'label': gate[1],
                                        'label_color': (1, 1, 1),
                                        'label_style': 'italic',
                                        'label_x_offset': -1,
                                        'label_size': 6
                                    }
                                }
                                u = {
                                    'type': 'RBS',
                                    'name': 'u' + str(color + 2),
                                    'opts': {
                                        'color': (0, 0, 0),
                                        'start_pad': -6,
                                        'x_extent': 6
                                    }
                                }
                                promotor = {
                                    'type': 'Promoter',
                                    'name': gate[0],
                                    'opts': {
                                        'color': (0, 0, 0),
                                        'label': gate[0],
                                        'label_x_offset': -5,
                                        'label_y_offset': -4,
                                        'label_size': 5
                                    }
                                }
                                arc = {
                                    'type': 'Repression',
                                    'from_part': cds,
                                    'to_part': use[-1][0],
                                    'opts': {
                                        'color': col_map[cds_color],
                                        'arc_height': 35 - (j * 5)
                                    }
                                }

                                if j == len(
                                        circuits[i]
                                ) - 1:  #To avoid intersection of the Repression lines
                                    design.insert(0, terminator)
                                    design.insert(0, cds)
                                    design.insert(0, u)
                                    design.insert(0, promotor)

                                else:  #Store it temporarily until because it needs to be appended at the end
                                    seperate.insert(0, terminator)
                                    seperate.insert(0, cds)
                                    seperate.insert(0, u)
                                    seperate.insert(0, promotor)

                                reg.append(arc)
                                use.pop()

                design = seperate + design

                # Set up the axes for the genetic constructs
                ax_dna = plt.axes()

                # Create the DNAplotlib renderer
                dr = dpl.DNARenderer()

                # Render the DNA to axis
                start, end = dr.renderDNA(ax_dna,
                                          design,
                                          dr.SBOL_part_renderers(),
                                          regs=reg,
                                          reg_renderers=dr.std_reg_renderers())

                ax_dna.set_xlim([start, end])
                ax_dna.set_ylim([-40, 40])
                ax_dna.set_aspect('equal')
                ax_dna.set_xticks([])
                ax_dna.set_yticks([])
                ax_dna.axis('off')

                fig.savefig('user_files/Circuit ' + str(file_num) +
                            ' SBOL Visual.png',
                            dpi=700)
                plt.close('all')
def computational_device(nb_input, list_integrase, list_gene_state, title,
                         name_directory, dirc_number):

    # Create the DNAplotlib renderer
    dr = dpl.DNARenderer()

    # Use default renderers and append our custom ones for recombinases
    reg_renderers = dr.std_reg_renderers()
    reg_renderers['Connection'] = rec.flip_arrow
    part_renderers = dr.SBOL_part_renderers()
    part_renderers['RecombinaseSite'] = rec.sbol_recombinase1
    part_renderers['RecombinaseSite2'] = rec.sbol_recombinase2

    # Create the construct programmably to plot
    PF = {'type': 'Promoter', 'name': 'prom', 'fwd': True}
    PR = {'type': 'Promoter', 'name': 'prom', 'fwd': False}
    Tf = {'type': 'Terminator', 'name': 'term', 'fwd': True}
    Tr = {'type': 'Terminator', 'name': 'term', 'fwd': False}

    ##initalization of list
    # list of attB fwd sites
    rec_matrix_attB_fwd = []
    #list of attP fwd sites
    rec_matrix_attP_fwd = []
    # list of attB rev sites
    rec_matrix_attB_rev = []
    # list of attP fwd sites
    rec_matrix_attP_rev = []
    # list with the full design
    design = []

    # for all nb_input add the corresponding attB and attP site in fwd direction to the corresponding list
    for X in range(0, nb_input):

        siteB = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': True,
            'opts': {
                'color': col_map_matrix[list_integrase[X] - 1],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attB_fwd.append(siteB)

        siteP = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': True,
            'opts': {
                'color': col_map_matrix[list_integrase[X] - 1],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attP_fwd.append(siteP)

        siteB = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': False,
            'opts': {
                'color2': col_map_matrix[list_integrase[X] - 1],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attB_rev.append(siteB)

        siteP = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': False,
            'opts': {
                'color2': col_map_matrix[list_integrase[X] - 1],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attP_rev.append(siteP)

    # construction for 2 inputs
    if nb_input == 2:

        if list_gene_state[2] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[2]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[1])
        design.append(PF)
        design.append(rec_matrix_attB_fwd[0])

        if list_gene_state[0] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[0]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[1] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[1]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attP_fwd[1])
        design.append(rec_matrix_attP_rev[0])

    # construction for 3 inputs
    elif nb_input == 3:

        if list_gene_state[3] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[3]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[2])
        design.append(Tf)
        design.append(Tr)

        if list_gene_state[0] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[0]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[0])
        design.append(rec_matrix_attB_rev[1])
        design.append(PR)
        design.append(rec_matrix_attP_rev[0])

        if list_gene_state[1] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[1]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[2] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[2]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attP_fwd[2])
        design.append(rec_matrix_attP_rev[1])

    # construction for 4 inputs
    elif nb_input == 4:

        if list_gene_state[4] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[4]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[3])
        design.append(rec_matrix_attB_fwd[0])
        design.append(rec_matrix_attB_rev[1])

        if list_gene_state[1] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[1]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[0] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[0]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attP_rev[0])
        design.append(rec_matrix_attB_rev[2])
        design.append(PR)
        design.append(rec_matrix_attP_rev[1])

        if list_gene_state[2] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[2]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[3] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[3]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attP_fwd[3])
        design.append(rec_matrix_attP_rev[2])

    # construction for 5 inputs
    elif nb_input == 5:

        if list_gene_state[5] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[5]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[4])
        design.append(rec_matrix_attB_fwd[1])
        design.append(rec_matrix_attB_rev[2])

        if list_gene_state[2] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[2]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[1] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[1]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attB_fwd[0])
        design.append(rec_matrix_attP_fwd[1])
        design.append(Tr)
        design.append(rec_matrix_attP_rev[0])

        design.append(rec_matrix_attB_rev[3])
        design.append(PR)
        design.append(rec_matrix_attP_rev[2])

        if list_gene_state[3] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[3]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(Tf)
        design.append(Tr)

        if list_gene_state[4] != 0:
            design.append(({
                'type': 'CDS',
                'name': 'cds',
                'fwd': False,
                'opts': {
                    'color': (0.8, 0.8, 0.8),
                    'label': str(list_gene_state[4]),
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label_style': 'italic'
                }
            }))

        design.append(rec_matrix_attP_fwd[4])
        design.append(rec_matrix_attP_rev[3])

    ## Design Integrase cassettes

    design_int = []
    i = 0
    sp = {
        'type': 'EmptySpace',
        'name': 's',
        'fwd': True,
        'opts': {
            'x_extent': 1
        }
    }
    name_input = 'abcdefghijklmnopqrstuvwxyz'

    for integrase in range(1, nb_input + 1):
        if integrase != '0':
            i += 1
            design_int.append({
                'type': 'Promoter',
                'name': 'prom',
                'fwd': True,
                'opts': {
                    'label': 'P' + str(name_input[i - 1]),
                    'label_x_offset': -2,
                    'label_y_offset': -6
                }
            })
            int_gene = {
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': col_map_matrix[integrase - 1],
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label': 'int' + str(integrase),
                    'label_style': 'italic'
                }
            }
            design_int.append(int_gene)
            design_int.append({
                'type': 'Terminator',
                'name': 'term',
                'fwd': True,
                'opts': {
                    'color': (0.5, 0.5, 0.5)
                }
            })
            design_int.append(sp)
            design_int.append(sp)
            design_int.append(sp)
            design_int.append(sp)

    # Create the figure
    fig = plt.figure(figsize=(3, 1))
    gs = gridspec.GridSpec(2, 1)
    ax_dna1 = plt.subplot(gs[1])
    ax_dna2 = plt.subplot(gs[0])

    # Redender the DNA to axis
    start, end = dr.renderDNA(ax_dna1, design, part_renderers)
    ax_dna1.set_xlim([start, end])
    ax_dna1.set_ylim([-17, 17])
    ax_dna1.set_aspect('equal')
    ax_dna1.set_xticks([])
    ax_dna1.set_yticks([])
    ax_dna1.axis('off')

    start, end = dr.renderDNA(ax_dna2, design_int, part_renderers)
    ax_dna2.set_xlim([start, end])
    ax_dna2.set_ylim([-13, 13])
    ax_dna2.set_aspect('equal')
    ax_dna2.set_xticks([])
    ax_dna2.set_yticks([])
    ax_dna2.axis('off')

    # Update subplot spacing
    #plt.subplots_adjust(hspace=0.01, left=0.05, right=0.95, top=0.92, bottom=0.01)

    #plt.title(title, fontsize=7)

    # Save the figure
    fig.savefig(name_directory + '/' + dirc_number + '_' + title + '.png',
                dpi=300)

    # Clear the plotting cache
    plt.close('all')
Esempio n. 19
0
def computation_device(inp, strain, int_list, title, name_directory,
                       directory_number):

    # Create the DNAplotlib renderer
    dr = dpl.DNARenderer()

    # Use default renderers and append our custom ones for recombinases
    reg_renderers = dr.std_reg_renderers()
    reg_renderers['Connection'] = rec.flip_arrow
    part_renderers = dr.SBOL_part_renderers()
    part_renderers['RecombinaseSite'] = rec.sbol_recombinase1
    part_renderers['RecombinaseSite2'] = rec.sbol_recombinase2

    # Create the construct programmably to plot
    PF = {'type': 'Promoter', 'name': 'prom', 'fwd': True}
    out_off = {
        'type': 'CDS',
        'name': 'cds',
        'fwd': True,
        'opts': {
            'color': (0.8, 0.8, 0.8),
            'label_x_offset': -2,
            'label_y_offset': -0.5,
            'label_style': 'italic',
            'label': 'GOI'
        }
    }
    term = {'type': 'Terminator', 'name': 'term', 'fwd': True}
    sp = {
        'type': 'EmptySpace',
        'name': 's',
        'fwd': True,
        'opts': {
            'x_extent': 1
        }
    }

    ##initalization of list
    # list of attB sites
    rec_matrix_attB = []
    # list of attP sites
    rec_matrix_attP = []
    # list with the full design
    design = []

    #number of input in this module
    nb_input = int(inp[0])

    # for all nb_input add the corresponding attB and attP site in fwd direction to the corresponding list
    for X in range(0, nb_input):

        siteB = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': True,
            'opts': {
                'color': col_map_matrix[X],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attB.append(siteB)
        siteP = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': True,
            'opts': {
                'color': col_map_matrix[X],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        rec_matrix_attP.append(siteP)

    # number of ZERO correspond to number of total variables (0) - number of ONE (1)
    ZERO = int(inp[0]) - int(inp[1])

    # variables that correspond to ZERO, in reverse order
    for Z in reversed(range(0, ZERO)):
        # append to the design the attB site
        design.append(rec_matrix_attB[Z])
    # append to the design the promoter in fwd direction
    design.append(PF)
    # variable which correspond to ZERO
    for Z in range(0, ZERO):
        # append attP site
        design.append(rec_matrix_attP[Z])
    # variable which correspond to ONE
    for O in range(ZERO, int(inp[0])):
        # add attB site+term+attP site
        design.append(rec_matrix_attB[O])
        design.append(term)
        design.append(rec_matrix_attP[O])
    # append output gene
    design.append(out_off)

    ##DESIGN OF INTEGRASE CASSETTE

    design_int = []
    i = 0
    name_input = 'abcdefghijklmnopqrstuvwxyz'
    #name_input='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    for integrase in int_list:
        i += 1
        if integrase != '0':
            design_int.append({
                'type': 'Promoter',
                'name': 'prom',
                'fwd': True,
                'opts': {
                    'label': 'P' + str(name_input[i - 1]),
                    'label_x_offset': -2,
                    'label_y_offset': -6
                }
            })
            int_gene = {
                'type': 'CDS',
                'name': 'cds',
                'fwd': True,
                'opts': {
                    'color': col_map_matrix[int(integrase) - 1],
                    'label_x_offset': -2,
                    'label_y_offset': -0.5,
                    'label': 'int' + str(integrase),
                    'label_style': 'italic'
                }
            }
            design_int.append(int_gene)
            design_int.append({
                'type': 'Terminator',
                'name': 'term',
                'fwd': True,
                'opts': {
                    'color': (0.5, 0.5, 0.5)
                }
            })
            design_int.append(sp)
            design_int.append(sp)
            design_int.append(sp)
            design_int.append(sp)

    # Create the figure
    fig = plt.figure(figsize=(3, 1))
    gs = gridspec.GridSpec(2, 1)
    ax_dna1 = plt.subplot(gs[1])
    ax_dna2 = plt.subplot(gs[0])

    # Redender the DNA to axis
    start, end = dr.renderDNA(ax_dna1, design, part_renderers)
    ax_dna1.set_xlim([start, end])
    ax_dna1.set_ylim([-18, 18])
    ax_dna1.set_aspect('equal')
    ax_dna1.set_xticks([])
    ax_dna1.set_yticks([])
    ax_dna1.axis('off')

    start, end = dr.renderDNA(ax_dna2, design_int, part_renderers)
    ax_dna2.set_xlim([start, end])
    ax_dna2.set_ylim([-18, 18])
    ax_dna2.set_aspect('equal')
    ax_dna2.set_xticks([])
    ax_dna2.set_yticks([])
    ax_dna2.axis('off')

    # Update subplot spacing
    plt.subplots_adjust(hspace=0.01,
                        left=0.05,
                        right=0.95,
                        top=0.92,
                        bottom=0.01)

    #hfont={'fontname':'Helevetica Neue'}

    #plt.title('For strain '+strain+', the computation device is:', fontsize=4)

    #plt.suptitle(subtitle, x = 0.5, y= 0.3, fontsize=5, **hfont)

    # Save the figure
    fig.savefig(name_directory + '/' + directory_number + '_' + title + '.png',
                dpi=300)

    # Clear the plotting cache
    plt.close('all')
Esempio n. 20
0
def plot_dna(dna_designs, out_filename, plot_params, regs_info):
    # Create the renderer
    if 'axis_y' not in plot_params.keys():
        plot_params['axis_y'] = 35
    left_pad = 0.0
    right_pad = 0.0
    scale = 1.0
    linewidth = 1.0
    fig_y = 5.0
    fig_x = 5.0
    if 'backbone_pad_left' in plot_params.keys():
        left_pad = plot_params['backbone_pad_left']
    if 'backbone_pad_right' in plot_params.keys():
        right_pad = plot_params['backbone_pad_right']
    if 'scale' in plot_params.keys():
        scale = plot_params['scale']
    if 'linewidth' in plot_params.keys():
        linewidth = plot_params['linewidth']
    if 'fig_y' in plot_params.keys():
        fig_y = plot_params['fig_y']
    if 'fig_x' in plot_params.keys():
        fig_x = plot_params['fig_x']
    dr = dpl.DNARenderer(scale=scale,
                         linewidth=linewidth,
                         backbone_pad_left=left_pad,
                         backbone_pad_right=right_pad)

    # We default to the standard regulation renderers
    reg_renderers = dr.std_reg_renderers()
    # We default to the SBOL part renderers
    part_renderers = dr.SBOL_part_renderers()

    # Create the figure
    fig = plt.figure(figsize=(fig_x, fig_y))

    # Cycle through the designs an plot on individual axes
    design_list = sorted(dna_designs.keys())
    if (regs_info != None):
        regs_list = sorted(regs_info.keys())

    num_of_designs = len(design_list)
    ax_list = []
    max_dna_len = 0.0
    for i in range(num_of_designs):
        # Create axis for the design and plot
        regs = None
        if (regs_info != None):
            regs = regs_info[i]
        design = dna_designs[design_list[i]]

        ax = fig.add_subplot(num_of_designs, 1, i + 1)
        if 'show_title' in plot_params.keys(
        ) and plot_params['show_title'] == 'Y':
            ax.set_title(design_list[i], fontsize=8)
        start, end = dr.renderDNA(ax, design, part_renderers, regs,
                                  reg_renderers)

        dna_len = end - start
        if max_dna_len < dna_len:
            max_dna_len = dna_len
        ax_list.append(ax)
    for ax in ax_list:
        ax.set_xticks([])
        ax.set_yticks([])
        # Set bounds
        ax.set_xlim([(-0.01 * max_dna_len) - left_pad,
                     max_dna_len + (0.01 * max_dna_len) + right_pad])
        ax.set_ylim([-plot_params['axis_y'], plot_params['axis_y']])
        ax.set_aspect('equal')
        ax.set_axis_off()

    # Update the size of the figure to fit the constructs drawn
    fig_x_dim = max_dna_len / 70.0
    if fig_x_dim < 1.0:
        fig_x_dim = 1.0
    fig_y_dim = 1.2 * len(ax_list)
    plt.gcf().set_size_inches((fig_x_dim, fig_y_dim))

    # Save the figure
    plt.tight_layout()
    fig.savefig(out_filename, transparent=True, dpi=300)
    # Clear the plotting cache
    plt.close('all')
Esempio n. 21
0
def create_sbol(construct, name):

    # get the circuit string and transform it into an iterable list
    # structure: <part 1 type>:<part 1 name>,<part 2 type>:<part 2 name>
    plasmids = construct.split('//')  # // separates different plasmids

    for idx in range(len(plasmids)):
        plasmids[idx] = plasmids[idx].split(
            ',')  # , separates different parts in the same plasmid

    designs = []

    sp = {
        'type': 'EmptySpace',
        'name': 'S1',
        'fwd': True
    }  # dnaplotlib tag for empty spaces

    max_length = len(max(
        plasmids, key=len))  # get the length (in parts) of the biggest plasmid

    # set font size and line width based on how much the image will be shrinked
    font_size = 20 / max([len(plasmids), max_length / 4])
    line_size = 2 / len(plasmids)

    d = 0
    for plasmid in plasmids:
        designs.append([])
        for part in plasmid:  #set offset for parts names
            if plasmid.index(part) % 2 == 0:
                y_offset = 20
            else:
                y_offset = -15
            part = part.replace(' ', '')  # handle spaces in circuit string
            designs[d].append(sp)
            designs[d].append({
                'type': part.split(':')[0],
                'name': part.split(':')[1],
                'fwd': True,
                'opts': {
                    'label': part.split(':')[1],
                    'label_size': font_size,
                    'label_y_offset': y_offset
                }
            })
        d += 1

    dr = dpl.DNARenderer(linewidth=line_size)  # dnaplotlib renderer object

    if len(
            designs
    ) > 1:  # making subplots only makes sense if there are multiple plasmids
        fig, axs = plt.subplots(len(designs))

        for idx in range(
                len(designs)
        ):  # use dnapltlib's standard drawing commands (got from their github)
            start, end = dr.renderDNA(axs[idx], designs[idx],
                                      dr.SBOL_part_renderers())
            axs[idx].set_xlim([start, end])
            axs[idx].set_ylim([-25, 25])
            axs[idx].set_aspect('equal')
            axs[idx].set_xticks([])
            axs[idx].set_yticks([])
            axs[idx].axis('off')
        fig.set_figwidth(0.75 * max_length)
    else:
        fig = plt.figure()
        ax = plt.axes()
        start, end = dr.renderDNA(ax, designs[0], dr.SBOL_part_renderers())
        ax.set_xlim([start, end])
        ax.set_ylim([-25, 25])
        ax.set_aspect('equal')
        ax.set_xticks([])
        ax.set_yticks([])
        ax.axis('off')

    # save figure with appropriate name and close everything
    fig.savefig('../database/images/part_' + name + '.png')
    plt.close('all')
Esempio n. 22
0
def plot_mean_sigma_genes_v2(INI_file, sigma_info, RNAPs_pos_info):

    # path to the input files (remove the "params.ini" from the path)
    path = INI_file.rpartition("/")[0] + "/"
    if path=="/":
        path="./"
    # read the config file
    config = sim.read_config_file(INI_file)
    # get inputs infos from the config file
    GFF_file = path+config.get('INPUTS', 'GFF')
    TSS_file = path+config.get('INPUTS', 'TSS')
    TTS_file = path+config.get('INPUTS', 'TTS')
    Prot_file = path+config.get('INPUTS', 'BARR_FIX')

    SIGMA_0 = config.getfloat('SIMULATION', 'SIGMA_0')
    DELTA_X = config.getfloat('SIMULATION', 'DELTA_X')

    # load and get BARR_FIX positions
    prot = sim.load_tab_file(Prot_file)
    BARR_FIX = (prot['prot_pos'].values).astype(int)

    # To draw the beautiful genes we need to read the GFF, TSS and TTS files to get some info ;)
    gff_df_raw = sim.load_gff(GFF_file)
    # to get the cov_bp (a verifier)
    genome_size = sim.get_genome_size(gff_df_raw)
    genome = int(genome_size/DELTA_X)
    cov_bp = np.arange(0, genome_size, DELTA_X)
    cov_bp = np.resize(cov_bp, genome)

    gff_df = sim.rename_gff_cols(gff_df_raw)

    tss = sim.load_tab_file(TSS_file)
    Kon = tss['TSS_strength'].values

    tts = sim.load_tab_file(TTS_file)
    Poff = tts['TTS_proba_off'].values

    strands = sim.str2num(gff_df['strand'].values)

    # Create the figure and all axes to draw to
    fig = plt.figure(1, figsize=(9,6)) # 3.2,2.7
    gs = gridspec.GridSpec(2, 1, height_ratios=[9, 3, 1])
    # Color maps for formatting
    col_map = {}
    col_map['red']     = (0.95, 0.30, 0.25)
    col_map['green']   = (0.38, 0.82, 0.32)
    col_map['blue']    = (0.38, 0.65, 0.87)
    col_map['orange']  = (1.00, 0.75, 0.17)
    col_map['purple']  = (0.55, 0.35, 0.64)
    col_map['yellow']  = (0.98, 0.97, 0.35)
    col_map['grey']    = (0.70, 0.70, 0.70)
    col_map['dark_grey'] = (0.60, 0.60, 0.60)
    col_map['light_grey'] = (0.9, 0.9, 0.9)

    # CDS formatting options
    opt_CDSs = []

    Ps = []
    CDSs = []
    Ts = []

    design = []

    for i in gff_df.index.values:
        opt_CDSs.append({'label':'Gene%s \n%.03f'%(str(i+1),Kon[i]), 
                         'label_style':'italic', 
                         'label_y_offset':-5, 
                         'color':col_map['orange']})
        # Design of the construct
        if strands[i] == True:
            # Promoters
            Ps.append({'type':'Promoter', 'name':'P%s'%str(i+1), 'start':tss['TSS_pos'][i], 
                       'end':tss['TSS_pos'][i]+5, 'fwd':strands[i], 'opts':{'color':col_map['green']}})
            # Coding Sequence
            CDSs.append({'type':'CDS', 'name':'CDS%s'%str(i+1), 'start':gff_df['start'][i],  
                         'end':gff_df['end'][i], 'fwd':gff_df['strand'][i], 'opts':opt_CDSs[i]}) 
        else:
            # Promoters
            Ps.append({'type':'Promoter', 'name':'P%s'%str(i+1), 'start':tss['TSS_pos'][i], 
                       'end':tss['TSS_pos'][i]-5, 'fwd':strands[i], 'opts':{'color':col_map['green']}})
            # Coding Sequence
            CDSs.append({'type':'CDS', 'name':'CDS%s'%str(i+1), 'start':gff_df['end'][i],  
                         'end':gff_df['start'][i], 'fwd':gff_df['strand'][i], 'opts':opt_CDSs[i]}) 
        # Terminators
        Ts.append({'type':'Terminator', 'name':'T%s'%str(i+1), 'start':tts['TTS_pos'][i], 
              'end':tts['TTS_pos'][i]+5, 'fwd':strands[i], 'opts':{'color':col_map['red']}})

        # A design is merely a list of parts and their properties
        if strands[i] == True:
            design.append(Ps[i])
            design.append(CDSs[i]) 
            design.append(Ts[i])
        else:
            design.append(Ts[i])
            design.append(CDSs[i]) 
            design.append(Ps[i])
        
    ax_mean_sig = plt.subplot(gs[0])
    ax_dna = plt.subplot(gs[1])

    # Redender the DNA
    dr = dpl.DNARenderer(scale=7, linewidth=1)
    start, end = dr.renderDNA(ax_dna, design, dr.trace_part_renderers())

    # Set bounds and display options for the DNA axis
    dna_len = end-start
    ax_dna.set_xlim([cov_bp[0], cov_bp[-1]]) #start-50
    ax_dna.set_ylim([-8,8])
    #ax_dna.plot(5000, 'ro', markersize=15)
    for xc in BARR_FIX:
        ax_dna.axvline(x=xc, ymin=0.40, ymax=0.60, color='k', linewidth=5)
    
    ax_dna.plot([cov_bp[0],cov_bp[-1]], [0,0], color=(0,0,0), linewidth=1.0, zorder=1)
    ax_dna.axis('off')
    
    # plot of sigma and mean of sigma
    plt.ion()
    ax_mean_sig.plot(cov_bp, sigma_info, linewidth= 1.5)
    ax_mean_sig.legend(loc='best', fontsize = 12)
    ax_mean_sig.set_ylim([-0.2,0.2])
    ax_mean_sig.set_xlim([0, cov_bp[-1]])

    #ax_mean_sig.set_title(r"Title goes here", fontsize = 13)
    ax_mean_sig.set_ylabel(r'Supercoiling density $(\sigma)$')
    ax_mean_sig.set_xlabel('Position (bp)')
    ax_mean_sig.plot(RNAPs_pos_info*DELTA_X, np.full(len(RNAPs_pos_info), SIGMA_0, dtype=float), 'ro', markersize=12, label = "RNA Polymerase")
    ax_mean_sig.set_ylim([-0.2, 0.2])
    plt.pause(0.001)
    plt.gcf().clear()
    plt.show()  
Esempio n. 23
0
    def plot_circuit(self, Input, Regulation=None, savefig=None):
        """Plot the SBOL-compliant gene circuit figure.

        :param Input: Input design from users
        :type Input: str
        :param Regulation: Regulation strings from users
        :type Regulation: str
        :param savefig: path to store the output figure
        :type savefig: str, optional
        :return: max dna design length and export the gene circuit figure
        :rtype: float
        """

        # matplotlib.use("Qt5Agg")
        matplotlib.use("Agg")

        dr = dpl.DNARenderer(linewidth=1.5)

        # Process the arguments
        design, Regulations = self.set_circuit_design(Input, Regulation)

        reg_renderers = dr.std_reg_renderers()
        part_renderers = dr.SBOL_part_renderers()

        # Generate the figure
        fig = plt.figure(figsize=(1.0, 1.0), dpi=100)
        ax = fig.add_subplot(1, 1, 1)

        # Plot the design
        dna_start, dna_end = dr.renderDNA(ax, design, part_renderers,
                                          Regulations, reg_renderers)
        max_dna_len = dna_end - dna_start

        # print("Max Dna length: ", max_dna_len)

        # Format the axis
        ax.set_xticks([])
        ax.set_yticks([])

        # Set bounds
        ax.set_xlim([(-0.0 * max_dna_len), max_dna_len + (0.0 * max_dna_len)])
        ax.set_ylim([-25, 25])
        ax.set_aspect("equal")
        ax.set_axis_off()

        # Update the size of the figure to fit the constructs drawn
        fig_x_dim = max_dna_len / 30
        # print("x_dim: ", fig_x_dim)
        if fig_x_dim < 1.0:
            fig_x_dim = 1.0
        fig_y_dim = 1.8
        plt.gcf().set_size_inches(fig_x_dim, fig_y_dim, forward=True)

        # Save the figure
        plt.tight_layout()

        if savefig is not None:
            fig.savefig(savefig, transparent=True, dpi=300)
        # plt.show()

        return max_dna_len, fig
def legend(nb_input, name_directory, directory_number):

    # Create the DNAplotlib renderer
    dr = dpl.DNARenderer()

    # Use default renderers and append our custom ones for recombinases
    reg_renderers = dr.std_reg_renderers()
    reg_renderers['Connection'] = rec.flip_arrow
    part_renderers = dr.SBOL_part_renderers()
    part_renderers['RecombinaseSite'] = rec.sbol_recombinase1
    part_renderers['RecombinaseSite2'] = rec.sbol_recombinase2

    # list with the full design
    design = []
    subtitle = ''

    # for all nb_input add the corresponding attB and attP site in fwd direction to the corresponding list
    for X in range(0, nb_input):

        siteB = ({
            'type': 'RecombinaseSite',
            'name': 'Site1',
            'fwd': True,
            'opts': {
                'color': col_map_matrix[X],
                'x_extent': 16,
                'y_extent': 12,
                'start_pad': 3,
                'end_pad': 3
            }
        })
        design.append(siteB)
        subtitle += 'int' + str(X + 1) + '    '

    # Create the figure
    fig = plt.figure(figsize=(3, 1))
    gs = gridspec.GridSpec(2, 1)
    ax_dna1 = plt.subplot(gs[0])

    # Redender the DNA to axis
    start, end = dr.renderDNA(ax_dna1, design, part_renderers)
    #start, end = dr.renderDNA(design)
    ax_dna1.set_xlim([start, end])
    ax_dna1.set_ylim([-18, 18])
    ax_dna1.set_aspect('equal')
    ax_dna1.set_xticks([])
    ax_dna1.set_yticks([])
    ax_dna1.axis('off')

    # Update subplot spacing
    plt.subplots_adjust(hspace=0.01,
                        left=0.05,
                        right=0.95,
                        top=0.92,
                        bottom=0.01)

    #plt.title('legend', fontsize=7)

    plt.suptitle(subtitle, x=0.5, y=0.9, fontsize=5)

    # Save the figure
    fig.savefig(name_directory + '/' + directory_number + '_legend.png',
                dpi=300)

    # Clear the plotting cache
    plt.close('all')
Esempio n. 25
0
def plot_dna(dna_designs, dna_design_order, out_filename, plot_params,
             perf_data):
    # Default parameters for the plotting
    if 'axis_y' not in plot_params.keys():
        plot_params['axis_y'] = 35
    left_pad = 0.0
    right_pad = 0.0
    scale = 1.0
    linewidth = 1.0
    fig_y = 5.0
    fig_x = 5.0
    # Update parameters if needed
    if 'backbone_pad_left' in plot_params.keys():
        left_pad = plot_params['backbone_pad_left']
    if 'backbone_pad_right' in plot_params.keys():
        right_pad = plot_params['backbone_pad_right']
    if 'scale' in plot_params.keys():
        scale = plot_params['scale']
    if 'linewidth' in plot_params.keys():
        linewidth = plot_params['linewidth']
    if 'fig_y' in plot_params.keys():
        fig_y = plot_params['fig_y']
    if 'fig_x' in plot_params.keys():
        fig_x = plot_params['fig_x']
    dr = dpl.DNARenderer(scale=scale,
                         linewidth=linewidth,
                         backbone_pad_left=left_pad,
                         backbone_pad_right=right_pad)

    # We default to the SBOL part renderers
    part_renderers = dr.SBOL_part_renderers()

    # Create the figure
    fig = plt.figure(figsize=(3.6, 6.2))

    # Cycle through the designs an plot on individual axes
    design_list = sorted(dna_designs.keys())
    num_of_designs = len(design_list)
    ax_list = []
    max_dna_len = 0.0
    gs = gridspec.GridSpec(num_of_designs, 2, width_ratios=[1, 12])

    # Plot the genetic designs
    for i in range(len(dna_design_order)):
        # Create axis for the design and plot
        design = dna_designs[dna_design_order[i]]
        ax = plt.subplot(gs[i, 1])
        if 'show_title' in plot_params.keys(
        ) and plot_params['show_title'] == 'Y':
            ax.set_title(design_list[i], fontsize=8)
        start, end = dr.renderDNA(ax, design, part_renderers)
        dna_len = end - start
        if max_dna_len < dna_len:
            max_dna_len = dna_len
        ax_list.append(ax)
    for ax in ax_list:
        ax.set_xticks([])
        ax.set_yticks([])
        # Set bounds
        ax.set_xlim([(-0.01 * max_dna_len) - left_pad,
                     max_dna_len + (0.01 * max_dna_len) + right_pad])
        ax.set_ylim([-14, 14])
        ax.set_aspect('equal')
        ax.set_axis_off()

    # Plot the performance data (bar charts)
    perf_vals = extract_dict_attribs(perf_data, dna_design_order, 'Activity')
    perf_sd_vals = extract_dict_attribs(perf_data, dna_design_order,
                                        'Activity_SD')
    ax_perf = plt.subplot(gs[:, 0])
    bar_height = 0.3
    ax_perf.plot([1], [1])
    ax_perf.spines['top'].set_visible(False)
    ax_perf.spines['bottom'].set_visible(False)
    ax_perf.spines['right'].set_visible(False)
    ax_perf.invert_yaxis()
    ax_perf.set_xticks([])
    ax_perf.yaxis.tick_left()
    ax_perf.yaxis.set_ticks_position('left')
    ax_perf.tick_params(axis='y', direction='out')
    ax_perf.tick_params('y',
                        length=3,
                        width=0.8,
                        which='major',
                        pad=2,
                        labelsize=8)
    pos1 = np.arange(len(perf_vals))
    ax_perf.barh(pos1,
                 perf_vals,
                 height=bar_height,
                 color=(0.6, 0.6, 0.6),
                 edgecolor=(0.6, 0.6, 0.6))
    ax_perf.errorbar(perf_vals,
                     pos1 + (bar_height / 2.0),
                     fmt='none',
                     xerr=perf_sd_vals,
                     ecolor=(0, 0, 0),
                     capthick=1)
    ax_perf.set_yticks(pos1 + (bar_height / 2.0))
    ax_perf.set_yticklabels(dna_design_order)
    ax_perf.set_ylim([max(pos1) + 0.65, -0.35])
    ax_perf.set_xlim([0, 1062606 * 1.05])

    # Save the figure
    plt.subplots_adjust(hspace=0.001,
                        wspace=0.05,
                        top=0.99,
                        bottom=0.01,
                        left=0.06,
                        right=0.99)
    fig.savefig(out_filename, transparent=True, dpi=300)

    # Clear the plotting cache
    plt.close('all')
Esempio n. 26
0
# Create the figure
fig = plt.figure(figsize=(3.0, 1.5))
gs = gridspec.GridSpec(1, 1)
ax_dna = plt.subplot(gs[0])

# This is the main sequence
seq1 = 'AATTCCGAGCGCGAGCTTTGCGAGTGA'
draw_sequence(ax_dna, 0, 0, seq1)

# Another sequence to show you can overlay them if needed with an offset
seq2 = 'TTGCGAGTGA'
draw_sequence(ax_dna, 8, 5, seq2)

# Create the DNAplotlib renderer and map of part types to renderering functions
dr = dpl.DNARenderer()
part_renderers = {'PromoterRegion': promoter_region}

# Create the sites to draw
r1 = {
    'type': 'PromoterRegion',
    'name': 'region1',
    'start': 2,
    'end': 13,
    'fwd': True,
    'opts': {
        'y_offset': 10,
        'len_35': 1,
        'len_10': 1,
        'color_35': (0, 0.5, 0.2),
        'color_10': (0.9, 0.2, 0.7)
Esempio n. 27
0
import numpy as np

__author__ = 'Thomas Gorochowski <*****@*****.**>, Voigt Lab, MIT'
__license__ = 'MIT'
__version__ = '1.0'

# Load the design from a GFF file
cur_region = [1700, 15880]
design = dpl.load_design_from_gff('plasmid.gff', 'chrom1', region=cur_region)
profile_fwd = dpl.load_profile_from_bed('plasmid_fwd_profile.txt', 'chrom1',
                                        [0, 22953])
profile_rev = dpl.load_profile_from_bed('plasmid_rev_profile.txt', 'chrom1',
                                        [0, 22953])

# Create the DNAplotlib renderer
dr = dpl.DNARenderer(scale=10.0)
part_renderers = dr.trace_part_renderers()

# Create the figure
fig = plt.figure(figsize=(3.5, 2.0))
gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.2])
ax_dna = plt.subplot(gs[1])

# Redender the DNA to axis
start, end = dr.renderDNA(ax_dna, design, part_renderers)
ax_dna.set_xlim(cur_region)
ax_dna.set_ylim([-5, 8])
ax_dna.axis('off')

ax_profile = plt.subplot(gs[0])
ax_profile.fill_between(list(range(cur_region[0], cur_region[1])),