예제 #1
0
 def test_render_KGML_modify(self):
     """ Rendering of KGML to PDF, with modification.
     """
     # We test rendering of the original KGML for KO01100,
     # modifying line width for the lipid pathway
     p = self.data
     with open(p[0].infilename) as f:
         pathway = read(f)
         mod_rs = [e for e in pathway.orthologs if
                 len(set(e.name.split()).intersection(self.ko_ids))]
         for r in mod_rs:
             for g in r.graphics:
                 g.width = 10
         kgml_map = KGMLCanvas(pathway)
         kgml_map.draw(p[0].output_stem + '_widths.pdf')
     # We test rendering of the original KGML for KO3070,
     # modifying the reaction colours for each ortholog entry
     with open(p[1].infilename) as f:
         pathway = read(f)
         orthologs = [e for e in pathway.orthologs]
         # Use Biopython's ColorSpiral to generate colours
         cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5, 
                          jitter=0.03)
         colors = cs.get_colors(len(orthologs))
         for o, c in zip(orthologs, colors):
             for g in o.graphics:
                 g.bgcolor = c
         kgml_map = KGMLCanvas(pathway)
         pathway.image = p[1].pathway_image
         kgml_map.import_imagemap = p[1].show_pathway_image
         kgml_map.draw(p[1].output_stem + '_colors.pdf')
예제 #2
0
 def test_render_KGML_modify(self):
     """Rendering of KGML to PDF, with modification."""
     # We test rendering of the original KGML for KO01100,
     # modifying line width for the lipid pathway
     p = self.data
     with open(p[0].infilename) as f:
         pathway = read(f)
         mod_rs = [
             e for e in pathway.orthologs
             if len(set(e.name.split()).intersection(self.ko_ids))
         ]
         for r in mod_rs:
             for g in r.graphics:
                 g.width = 10
         kgml_map = KGMLCanvas(pathway)
         kgml_map.draw(p[0].output_stem + '_widths.pdf')
     # We test rendering of the original KGML for KO3070,
     # modifying the reaction colours for each ortholog entry
     with open(p[1].infilename) as f:
         pathway = read(f)
         orthologs = [e for e in pathway.orthologs]
         # Use Biopython's ColorSpiral to generate colours
         cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5, jitter=0.03)
         colors = cs.get_colors(len(orthologs))
         for o, c in zip(orthologs, colors):
             for g in o.graphics:
                 g.bgcolor = c
         kgml_map = KGMLCanvas(pathway)
         pathway.image = p[1].pathway_image
         kgml_map.import_imagemap = p[1].show_pathway_image
         kgml_map.draw(p[1].output_stem + '_colors.pdf')
예제 #3
0
 def test_render_KGML_transparency(self):
     """Rendering of KGML to PDF, with color alpha channel."""
     # We test rendering of the original KGML for KO01100,
     # modifying alpha channel for the lipid pathway
     p = self.data
     with open(p[0].infilename) as f:
         pathway = read(f)
         mod_rs = [e for e in pathway.orthologs if
                   len(set(e.name.split()).intersection(self.ko_ids))]
         for r in mod_rs:
             for g in r.graphics:
                 # Modify hex colour directly by appending alpha channel
                 # to hex string
                 g.fgcolor = g.fgcolor + "77"
                 g.width = 20
         kgml_map = KGMLCanvas(pathway)
         kgml_map.draw(p[0].output_stem + "_transparency.pdf")
     # We test rendering of the original KGML for KO3070,
     # modifying the alpha channel for each ortholog entry
     with open(p[1].infilename) as f:
         pathway = read(f)
         orthologs = list(pathway.orthologs)
         # Use Biopython's ColorSpiral to generate colours
         cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5,
                          jitter=0.03)
         colors = cs.get_colors(len(orthologs))
         for o, c in zip(orthologs, colors):
             # Modify color tuples to add alpha channel
             c = c + (0.5, )
             for g in o.graphics:
                 g.bgcolor = c
         kgml_map = KGMLCanvas(pathway)
         pathway.image = p[1].pathway_image
         kgml_map.import_imagemap = p[1].show_pathway_image
         kgml_map.draw(p[1].output_stem + "_transparency.pdf")
예제 #4
0
 def test_render_KGML_transparency(self):
     """Rendering of KGML to PDF, with color alpha channel."""
     # We test rendering of the original KGML for KO01100,
     # modifying alpha channel for the lipid pathway
     p = self.data
     with open(p[0].infilename) as f:
         pathway = read(f)
         mod_rs = [e for e in pathway.orthologs if
                   len(set(e.name.split()).intersection(self.ko_ids))]
         for r in mod_rs:
             for g in r.graphics:
                 # Modify hex colour directly by appending alpha channel
                 # to hex string
                 g.fgcolor = g.fgcolor + "77"
                 g.width = 20
         kgml_map = KGMLCanvas(pathway)
         kgml_map.draw(p[0].output_stem + '_transparency.pdf')
     # We test rendering of the original KGML for KO3070,
     # modifying the alpha channel for each ortholog entry
     with open(p[1].infilename) as f:
         pathway = read(f)
         orthologs = [e for e in pathway.orthologs]
         # Use Biopython's ColorSpiral to generate colours
         cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5,
                          jitter=0.03)
         colors = cs.get_colors(len(orthologs))
         for o, c in zip(orthologs, colors):
             # Modify color tuples to add alpha channel
             c = c + (0.5, )
             for g in o.graphics:
                 g.bgcolor = c
         kgml_map = KGMLCanvas(pathway)
         pathway.image = p[1].pathway_image
         kgml_map.import_imagemap = p[1].show_pathway_image
         kgml_map.draw(p[1].output_stem + '_transparency.pdf')
예제 #5
0
 def test_colorlist(self):
     """Get set of eight colours, no jitter, using ColorSpiral."""
     cs = ColorSpiral(a=4, b=0.33, jitter=0)
     colours = list(cs.get_colors(8))
     cstr = ["(%.2f, %.2f, %.2f)" % (r, g, b) for r, g, b in colours]
     expected = \
         ['(0.64, 0.74, 0.81)', '(0.68, 0.52, 0.76)', '(0.72, 0.41, 0.55)',
          '(0.68, 0.39, 0.31)', '(0.63, 0.54, 0.22)', '(0.48, 0.59, 0.13)',
          '(0.24, 0.54, 0.06)', '(0.01, 0.50, -0.00)']
     self.assertEqual(cstr, expected)
예제 #6
0
 def test_colorlist(self):
     """Get set of eight colours, no jitter, using ColorSpiral."""
     cs = ColorSpiral(a=4, b=0.33, jitter=0)
     colours = list(cs.get_colors(8))
     cstr = ["(%.2f, %.2f, %.2f)" % (r, g, b)
                 for r, g, b in colours]
     expected = \
         ['(0.64, 0.74, 0.81)', '(0.68, 0.52, 0.76)', '(0.72, 0.41, 0.55)',
          '(0.68, 0.39, 0.31)', '(0.63, 0.54, 0.22)', '(0.48, 0.59, 0.13)',
          '(0.24, 0.54, 0.06)', '(0.01, 0.50, -0.00)']
     self.assertEqual(cstr, expected)
예제 #7
0
 def test_colorspiral(self):
     """Get set of 16 colours, no jitter, using ColorSpiral."""
     cs = ColorSpiral(a=4, b=0.33, jitter=0)
     radius = A4[0] * 0.025
     for r, g, b in cs.get_colors(16):
         self.c.setFillColor((r, g, b))
         # Convert HSV colour to rectangular coordinates on HSV disc
         h, s, v = colorsys.rgb_to_hsv(r, g, b)
         coords = rect(s * A4[0] * 0.45, h * 2 * pi)
         x, y = self.x_0 + coords.real, self.y_0 + coords.imag
         self.c.ellipse(x - radius, y - radius, x + radius, y + radius,
                        stroke=0, fill=1)
     self.finish()
예제 #8
0
 def test_colorspiral(self):
     """Get set of 16 colours, no jitter, using ColorSpiral."""
     cs = ColorSpiral(a=4, b=0.33, jitter=0)
     radius = A4[0] * 0.025
     for r, g, b in cs.get_colors(16):
         self.c.setFillColor((r, g, b))
         # Convert HSV colour to rectangular coordinates on HSV disc
         h, s, v = colorsys.rgb_to_hsv(r, g, b)
         coords = rect(s * A4[0] * 0.45, h * 2 * pi)
         x, y = self.x_0 + coords.real, self.y_0 + coords.imag
         self.c.ellipse(x - radius, y - radius, x + radius, y + radius,
                        stroke=0, fill=1)
     self.finish()
예제 #9
0
 def test_colorlist(self):
     """Get set of eight colours, no jitter, using ColorSpiral."""
     cs = ColorSpiral(a=4, b=0.33, jitter=0)
     colours = list(cs.get_colors(8))
     cstr = [f"({r:.2f}, {g:.2f}, {b:.2f})" for r, g, b in colours]
     expected = [
         "(0.64, 0.74, 0.81)",
         "(0.68, 0.52, 0.76)",
         "(0.72, 0.41, 0.55)",
         "(0.68, 0.39, 0.31)",
         "(0.63, 0.54, 0.22)",
         "(0.48, 0.59, 0.13)",
         "(0.24, 0.54, 0.06)",
         "(0.01, 0.50, -0.00)",
     ]
     self.assertEqual(cstr, expected)
예제 #10
0
파일: cluster.py 프로젝트: akwon/fammer
def write_clusters(seqfname, tree, clusters, unclustered):
    """Write output files: clusters & unique as FASTA, tree as phyloXML."""
    is_aln = seqfname.endswith('.aln')
    seq_idx = SeqIO.to_dict(
        SeqIO.parse(seqfname, 'clustal' if is_aln else 'fasta'))

    def write_cluster(cluster, fname):
        """Write the sequences of cluster tips to a FASTA file."""
        records = [seq_idx[seqid] for seqid in sorted(cluster)]
        with open(fname, 'w+') as handle:
            for rec in records:
                write_fasta(rec, handle, do_ungap=is_aln)
        logging.info("Wrote %s (%d sequences)", fname, len(records))

    colors = [
        BranchColor(*map(lambda x: int(x * 255), rgb))
        for rgb in ColorSpiral().get_colors(len(clusters))
    ]
    for i, item in enumerate(
            sorted(clusters.iteritems(),
                   reverse=True,
                   key=lambda kv: len(kv[1]))):
        clade, cluster = item
        write_cluster(cluster, os.path.basename(seqfname) + '.' + str(i))
        clade.color = colors[i]
        clade.width = 2
    if unclustered:
        write_cluster(unclustered, os.path.basename(seqfname) + '.Unique')

    treefname = os.path.basename(seqfname) + '.xml'
    Phylo.write(tree, treefname, 'phyloxml')
    logging.info("Wrote %s", treefname)
예제 #11
0
def map2highlighted_map(map_id,
                        ko_list,
                        ko2freq,
                        biodb,
                        outpath='test.pdf',
                        taxon_id=False,
                        n_species=60):
    import re
    from chlamdb.biosqldb import shell_command
    from Bio.Graphics.KGML_vis import KGMLCanvas
    from Bio.Graphics import KGML_vis
    import urllib.request
    from Bio.KEGG.KGML.KGML_pathway import Pathway, Reaction, Relation
    import Bio.KEGG.KGML.KGML_pathway
    from Bio.KEGG.KGML import KGML_parser
    from Bio.Graphics.ColorSpiral import ColorSpiral
    import matplotlib.cm as cm
    from matplotlib.colors import rgb2hex
    import matplotlib as mpl

    values = [float(i) for i in ko2freq.values()]

    norm = mpl.colors.Normalize(vmin=0, vmax=n_species)
    cmap = cm.OrRd
    cmap2 = cm.Greens
    m = cm.ScalarMappable(norm=norm, cmap=cmap)
    m2 = cm.ScalarMappable(norm=norm, cmap=cmap2)

    url_template = 'http://rest.kegg.jp/get/%s/kgml' % re.sub(
        'map', 'ko', map_id)
    print(url_template)
    f = urllib.request.urlopen(url_template)
    from Bio.Graphics import KGML_vis

    pathway = KGML_parser.read(f.read().decode('UTF-8'))

    kgml_map = KGMLCanvas(pathway, show_maps=True)

    # Let's use some arbitrary colours for the orthologs
    cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5, jitter=0.03)
    # Loop over the orthologs in the pathway, and change the
    # background colour
    orthologs = [e for e in pathway.orthologs]
    for o in orthologs:
        match = False
        if 'K00163' in o.name:
            print('##################################')
        ko_temp_list = set([i.rstrip() for i in o.name.split('ko:')])
        if len(ko_temp_list.intersection(set(ko2freq.keys()))) > 0:

            ko_keep = []
            for ko in ko_temp_list:
                if ko in ko2freq:
                    ko_keep.append(ko)
                if ko in ko_list:
                    match = True
            o.name = 'ko:' + ' ko:'.join(ko_keep)
            total = sum([
                int(ko2freq[i])
                for i in ko_temp_list.intersection(set(ko2freq.keys()))
            ])

            for g in o.graphics:
                if match:
                    g.bgcolor = rgb2hex(m2.to_rgba(float(total)))
                else:
                    #print 'no match!!!!'
                    #print ko_temp_list
                    #print ko2freq.keys()
                    #print 'TOTAL:', total
                    g.bgcolor = rgb2hex(m.to_rgba(float(total)))
            o.name = "%s (%s)" % (o.name.split('ko:')[0], total)
        #else:
        #    for g in o.graphics:
        #        g.bgcolor = '#FFFFFF'

    # Default settings are for the KGML elements only

    # We need to use the image map, and turn off the KGML elements, to see
    # only the .png base map. We could have set these values on canvas
    # instantiation
    kgml_map.import_imagemap = True
    kgml_map.show_maps = True
    kgml_map.show_orthologs = True
    kgml_map.draw_relations = False
    kgml_map.show_compounds = False
    kgml_map.show_genes = False
    kgml_map.show_compounds = False
    kgml_map.show_genes = False
    kgml_map.draw(outpath)
    '''
    print 'DIRLISAT:', dir(pathway)
    maps = [m for m in pathway.maps]
    for map in maps:
        for g in map.graphics:
            print g.name
    '''

    #print re.sub('pdf', 'svg', outpath)
    shell_command.shell_command(
        'inkscape %s --export-plain-svg=%s' %
        (outpath, re.sub('pdf', 'svg', outpath)))  # 'pdf2svg %s %s all'
    t = edit_svg_map("%s" % re.sub('pdf', 'svg', outpath),
                     ko2freq.keys(),
                     biodb,
                     map_id,
                     taxon_id=taxon_id)
    #print "%s" % re.sub('pdf', 'svg', outpath)
    t.write("%s" % re.sub('pdf', 'svg', outpath))