Package gem

Source Code of gem.PlotForTissue

package gem;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import gem.util.Progress;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;

/**
* This class draws a plot of results, focusing a specific tissue in expO dataset, color-coding
* genes with their relative expression in that tissue.
*
* @author Ozgun Babur
*/
public class PlotForTissue
{
  static boolean groupMod = true;
  public static final AlphaComposite text =
      AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f);
  public static final AlphaComposite box =
      AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
  public static final Font modfont = new Font("Verdana", Font.PLAIN, 12);
  public static final Font targetfont = new Font("Verdana", Font.PLAIN, 8);
  public static final Font labelfont = new Font("Verdana", Font.PLAIN, 6);
  public static final Font idfont = new Font("Verdana", Font.PLAIN, 5);

  static String factorName;
  static boolean[] pos;

  static int rowStart = 60;

  //public static Font upFont;
  //public static Font downFont;

  public static void main(String[] args) throws Throwable
  {
//    String tissue = "Breast";
    String file = "result/Big_all_fdr0.05_var1.0";

    List<Triplet> trips = Triplet.readTripsAndAssociate(file + ".xls",
      "resource/exp_big_1.txt", "resource/exp_big_2.txt", "resource/exp_big_3.txt", "resource/exp_big_4.txt");
     
//      "resource/experiments_expO_1.txt", "resource/experiments_expO_2.txt");
//      "resource/exp_Treg_1.exp", "resource/exp_Treg_2.exp", "resource/exp_Treg_3.exp");

//    trips = Triplet.selectModulator(trips, "FABP1");
//    trips = Triplet.selectTarget(trips, "LTF");
    trips = Triplet.selectFactor(trips, "MYB", true);

//    pos = CellTypeMatcher.getTissueHitArrayForExpO(tissue);
    pos = CellTypeMatcher.getLeukemiaHitArrayForBigdata();

//    System.out.println("Getting subtypes ...");
//    boolean[][] subtypes = Subtype.getSubtypes(trips, pos, 2);
//    for (boolean[] subtype : subtypes)
//    {
//      System.out.println("subtype : " + Subtype.count(subtype));
//    }
//    pos = subtypes[1];

    CaseCounter.count(trips, pos);

//    generateHistoplot(trips, pos, file + "_" + tissue + ".svg");
    generateHistoplot(trips, pos, file + "_Leukemia.svg");
  }

  public void paint(Graphics2D g2d, java.util.List<Group> modlist, Gene factor)
  {
    Collections.sort(modlist);

    boolean[] fp = factor.getPresentSubset(pos);

    int i = 0;
    Group[][] page = new Group[(modlist.size()/5)+ (modlist.size()%5==0 ? 0 : 1)][5];
    for (Group mod : modlist)
    {
      page[i/5][i%5]=mod;
      i++;
    }
    for (int rowi = 0; rowi < page.length; rowi++)
    {
      Group[] row = page[rowi];
      int top = 0;
      int bottom = 0;
      for (Group mod : row)
      {
        if (mod!=null)
        {
          top = Math.max(top, mod.getTop());
          bottom = Math.max(bottom, mod.getBottom());
        }
      }

      int rowCenter = rowStart + 10 * top + 6;
      int rowbottom = rowCenter + 10 * bottom + 42;
      setText(g2d);
      g2d.setFont(modfont);
      String facName = Triplet.getGeneToSymbolMap().get(factor.geneid);
      FontMetrics fm = g2d.getFontMetrics();
      int width = fm.stringWidth(facName);

      g2d.setPaint(getColor(factor.calcPresenceOnTissue(pos),
        UP_COLOR, DOWN_COLOR, NOTR_COLOR));
      g2d.fillRect(9, rowCenter - 6, width+2, 12);
      setText(g2d);
      g2d.drawString(facName, 10, rowCenter + 5);

      g2d.setFont(idfont);
      String[] id = factor.id.split("\\|");
      g2d.drawString (id[0], 10 + width + 3, rowCenter - 1);
      g2d.drawString (id[1], 10 + width + 3, rowCenter + 6);

      g2d.drawString("activates",30,rowCenter-10);
      g2d.setFont(labelfont);
      g2d.drawString("inhibits",30,rowCenter+15);

      for (int col = 0; col < row.length; col++)
      {
        Group mod = row[col];
        if (mod!=null)
        {
          drawGroup(g2d, mod, 50 + 120 * col, rowStart, rowCenter, rowbottom, fp);
        }
      }
      rowStart = rowbottom;
    }
  }

  private void drawGroup(Graphics2D g2d, Group mod, int x,
    int rowstart, int rowCenter, int rowbottom, boolean[] fp)
  {
    mod.sortMembers();
    boolean showIsoforms = mod.getName().contains("|");

    g2d.setColor(Color.LIGHT_GRAY);
    g2d.drawRect(x+27,rowstart-25,110,rowbottom-rowstart-10);

    g2d.setFont(modfont);
    String name = mod.getName();
    if (showIsoforms) name = name.substring(0, name.indexOf("|"));

    FontMetrics fm = g2d.getFontMetrics();
    int width = fm.stringWidth(name);
    int margin= ((120 - width) / 2) + (showIsoforms ? 7 : 27);

    g2d.setComposite(text);
    paintPresenceBox(g2d,
      groupMod ? mod.getPresenceListOfMod(fp) : mod.getPresenceListOfTar(fp),
      x+margin, rowstart - 22, width, 15);
    setText(g2d);

    if (showIsoforms)
    {
      String[] nm = mod.getName().split("\\|");
      assert nm.length == 3 : "name = " + mod.getName();
      g2d.drawString (nm[0], x+margin, rowstart-10);
      g2d.setFont(idfont);
      g2d.drawString (nm[1], x+margin+width+3, rowstart-16);
      g2d.drawString (nm[2], x+margin+width+3, rowstart-9);
    }
    else
    {
          g2d.drawString (name, x+margin, rowstart-10);
    }

    g2d.setFont(labelfont);
    g2d.drawString("Enhances",x+33,rowstart);
    g2d.drawString("Attenuates",x+67,rowstart);
    g2d.drawString("Inverts",x+107,rowstart);

    for (Cat cat : Cat.values())
    {
      List<Triplet> targets = mod.get(cat);
      if (targets != null)
      {
        setBox(g2d, cat);
        Rectangle bounds = cat.getBounds(mod.getHeight(cat) * 10, x, rowCenter);
        g2d.fill(bounds);
        setText(g2d);
        int i=0;
        for (Triplet t : targets)
        {
          i++;

          g2d.setPaint(getColor(
            groupMod ? t.T.calcPresenceOnTissue(fp) : t.M.calcPresenceOnTissue(fp),
            UP_COLOR, DOWN_COLOR, NOTR_COLOR));
          g2d.fillRect(bounds.x+1, bounds.y-10+i*10, 30, 10);
        }
        setText(g2d);
        i=0;
        for (Triplet t : targets)
        {
          i++;

//          if (Triplet.getGeneToSymbolMap().get(t.target).equals("TMPO"))
//          {
//            System.out.print("");
//          }
          if (TissueInterpreter.isModAffectable(t))
          {
            g2d.drawRect(bounds.x+1, bounds.y-10+i*10, 30, 10);
          }
          g2d.drawString(groupMod ? t.getTSym() : t.getMSym(),
            bounds.x+2, bounds.y-2+i*10);
        }
      }
    }
  }

  private void setBox(Graphics2D g2d, Cat cat)
  {
//    g2d.setPaint(cat.getColor());
    g2d.setPaint(Color.GRAY);
    g2d.setComposite(box);
  }

  private void setText(Graphics2D g2d)
  {
    g2d.setPaint(Color.BLACK);
    g2d.setComposite(text);
  }

  public static void generateHistoplot(java.util.List<Triplet> trips, boolean[] pos, String outFile) throws IOException
  {
    PlotForTissue.pos = pos;

    // Get a DOMImplementation.
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document.
    String svgNS = "http://www.w3.org/2000/svg";
    Document document = domImpl.createDocument(svgNS, "svg", null);

    // Create an instance of the SVG Generator.
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    PlotForTissue test = new PlotForTissue();

    Map<Gene, List<Triplet>> groupedTrips = groupToFactor(trips);

    for (Gene factor : groupedTrips.keySet())
    {
//      Triplet.keepMostSignif(trips);
      List<Triplet> tripGroup = groupedTrips.get(factor);
      HashMap<String, Group> map = process(tripGroup);
      filterMods(map);

      test.paint(svgGenerator, new ArrayList<Group>(map.values()), factor);
    }

    // Finally, stream out SVG to the standard output using
    // UTF-8 encoding.
    boolean useCSS = true; // we want to use CSS style attributes
    Writer out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
    svgGenerator.stream(out, useCSS);
  }

  private static HashMap<String, Group> process(java.util.List<Triplet> trips) throws IOException
  {
    HashMap<String, Group> model = new HashMap<String, Group>();

    for (Triplet t : trips)
    {
      if (factorName == null)
      {
        factorName = t.getFSym();
      }

      String modul = groupMod ? t.getMSym() : t.getTSym();
      modul += "|" + (groupMod ? t.mod_id : t.tar_id);

      if (!model.containsKey(modul)) model.put(modul, new Group(modul, pos));
      Group mod = model.get(modul);

      if (t.categ.startsWith("MoA")) continue;
      Cat cat = Cat.valueOf(t.categ.replace(" ", "_"));

      if (cat == null) continue;

      if (mod.get(cat) == null) mod.put(cat, new ArrayList<Triplet>());
      List<Triplet> tars = mod.get(cat);

      tars.add(t);
    }
    return model;
  }

  private static void filterMods(HashMap<String, Group> map)
  {
    for (String key : new HashSet<String>(map.keySet()))
    {
      Group mod = map.get(key);

      if (mod.getSize() < 1)
      {
        map.remove(key);
      }
    }
  }


  private static Color getColor(double percent, Color c1, Color c0, Color c05)
  {
    if (percent < 0)
    {
      return ABSENT_COLOR;
    }

    if (percent > 0.5)
    {
      return getColor((percent - 0.5) * 2, c1, c05);
    }
    else
    {
      return getColor(percent * 2, c05, c0);
    }
  }
  private static Color getColor(double percent, Color c1, Color c0)
  {
    assert percent >= 0 && percent <= 1 : "percent = " + percent;

    return new Color((int) Math.round(c0.getRed() + ((c1.getRed() - c0.getRed()) * percent)),
      (int) Math.round(c0.getGreen() + ((c1.getGreen() - c0.getGreen()) * percent)),
      (int) Math.round(c0.getBlue() + ((c1.getBlue() - c0.getBlue()) * percent)));
  }

  private static void paintPresenceBox(Graphics2D g2d, java.util.List<Double> ratios,
    int x, int y, int width, int height)
  {
    double range = width / (double) ratios.size();
    for (int i = 0; i < ratios.size(); i++)
    {
      g2d.setPaint(getColor(ratios.get(i), UP_COLOR, DOWN_COLOR, NOTR_COLOR));
      int startx = (int) Math.round(x + (i * range));
      int stopx = (int) Math.round(x + ((i+1) * range));
      g2d.fillRect(startx, y, stopx - startx, height);
    }
  }

  private static Map<Gene, List<Triplet>> groupToFactor(List<Triplet> trips)
  {
    Map<Gene, List<Triplet>> map = new HashMap<Gene, List<Triplet>>();
    for (Triplet t : trips)
    {
      if (!map.containsKey(t.F)) map.put(t.F, new ArrayList<Triplet>());

      map.get(t.F).add(t);
    }
    return map;
  }

  static class Group implements Comparable
  {
    private String name;
    HashMap<Cat, List<Triplet>> cats = new HashMap<Cat, List<Triplet>>();
    boolean[] pos;

    public Group(String modName, boolean[] pos)
    {
      assert modName != null;
      this.name=modName;
      this.pos = pos;
    }

    public int compareTo(Object o)
    {
      return ((Group) o).getSize()-this.getSize();
    }

    public int getSize()
    {
      int i=0;
      for (List<Triplet> trips : cats.values())
      {
        i+=trips==null?0:trips.size();
      }

      return i;
    }


    public int getTop()
    {
      return Math.max(getHeight(Cat.Enhances_Activation),
          Math.max(getHeight(Cat.Attenuates_Activation),
          getHeight(Cat.Inverts_Activation)));
    }

    public int getBottom()
    {
      return Math.max(getHeight(Cat.Enhances_Inhibition),
          Math.max(getHeight(Cat.Attenuates_Inhibition),
          getHeight(Cat.Inverts_Inhibition)));
    }

    public int getHeight(Cat cat)
    {
      return cats.get(cat)==null?0:cats.get(cat).size();
    }
    public String getName()
    {
      return name;
    }

    public List<Triplet> get(Cat cat)
    {
      return cats.get(cat);
    }

    public void put(Cat cat, List<Triplet> targets)
    {
      this.cats.put(cat, targets);
    }

    public int getModStatusInTissue()
    {
      boolean up = false;
      boolean down = false;
      for (Cat cat : cats.keySet())
      {
        for (Triplet t : cats.get(cat))
        {
          if (t.M.calcPresenceOnTissue(pos) > 0.5) up = true;
          else down = true;
        }
      }
      if (up && down) return 0;
      if (up) return 1;
      else return -1;
    }

    public java.util.List<Double> getPresenceListOfMod(boolean[] pos)
    {
      java.util.List<Double> list = new ArrayList<Double>();

      Set<Gene> geneSet = new HashSet<Gene>();
      for (Cat cat : cats.keySet())
      {
        for (Triplet t : cats.get(cat))
        {
          if (!geneSet.contains(t.M))
          {
            list.add(t.M.calcPresenceOnTissue(pos));
            geneSet.add(t.M);
          }
        }
      }
      return list;
    }

    public java.util.List<Double> getPresenceListOfTar(boolean[] pos)
    {
      java.util.List<Double> list = new ArrayList<Double>();

      Set<Gene> geneSet = new HashSet<Gene>();
      for (Cat cat : cats.keySet())
      {
        for (Triplet t : cats.get(cat))
        {
          if (!geneSet.contains(t.T))
          {
            list.add(t.T.calcPresenceOnTissue(pos));
            geneSet.add(t.T);
          }
        }
      }
      return list;
    }
    public void sortMembers()
    {
      for (List<Triplet> list : cats.values())
      {
        List<THolder> hl = new ArrayList<THolder>(list.size());
        for (Triplet t : list)
        {
          hl.add(new THolder(t));
        }
        Collections.sort(hl);
        list.clear();
        for (THolder th : hl)
        {
          list.add(th.t);
        }
      }
    }
  }

  static class THolder implements Comparable
  {
    Triplet t;
    String value;

    THolder(Triplet t)
    {
      this.t = t;
      value = Triplet.getGeneToSymbolMap().get(groupMod ? t.target : t.modulator) +
        (groupMod ? t.tar_id : t.mod_id);
    }

    public int compareTo(Object o)
    {
      return value.compareTo(((THolder)o).value);
    }
  }

  enum Cat
  {
    Enhances_Activation(33, 137, 33, 1, 1),
    Attenuates_Activation(144, 238, 144, 1, 2),
    Inverts_Activation(253, 48, 48, 1, 3),
    Enhances_Inhibition(106, 33, 137, 0, 1),
    Attenuates_Inhibition(210, 143, 238, 0, 2),
    Inverts_Inhibition(253, 207, 47, 0, 3);

    private Color color;
    private int v, h;

    Cat(int r, int g, int b, int v, int h)
    {
      color = new Color(r, g, b);
      this.v = v;
      this.h = h;
    }

    public Color getColor()
    {
      return color;
    }

    public Rectangle getBounds(int height, int x, int y)
    {
      return new Rectangle(x + h * 34, y - v * (height + 4) + 2, 32, height);
    }

  }

  static final Color UP_COLOR = new Color(255, 110, 100);
  static final Color DOWN_COLOR = new Color(100, 150, 255);
  static final Color NOTR_COLOR = new Color(255, 255, 255);
  static final Color ABSENT_COLOR = new Color(255, 255, 200);
}
TOP

Related Classes of gem.PlotForTissue

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.