Package gem

Source Code of gem.PlotForTissue2$THolder

package gem;

import gem.parser.TabDelimitedFileParser;
import gem.util.Binomial;
import gem.util.Kronometre;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;

/**
* 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 PlotForTissue2 implements Constants
{
  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, 24);
  public static final Font labelfont = new Font("Verdana", Font.PLAIN, 12);
  public static final Font idfont = new Font("Verdana", Font.PLAIN, 10);

  static String factorName;
  static boolean[] posCancer;
  static boolean[] posNormal;

  static Map<Gene, Double> gene2change = new HashMap<Gene, Double>();
  static Map<Gene, Double> gene2rankCh = new HashMap<Gene, Double>();
  static Map<String, Integer> tar2modNum = new HashMap<String, Integer>();
  static Map<Gene, Integer> normalMap = new HashMap<Gene, Integer>();
  static List<String> expnames;
  static String comtype;

  static int rowStart = 60;
  static final double FOLLOW_PVAL_THR = 0.1;

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

  public static void main(String[] args) throws Throwable
  {
    Kronometre kron = new Kronometre();
    String file = "result/Result_fdr0.05_var1.0_AR_expo_prostate";

    comtype = "33";
    String plat = "GPL8300";
    List<Triplet> trips = Triplet.readTripsAndAssociate(file + ".xls",
      "resource/expop/expop_1.txt", "resource/expop/expop_2.txt", "resource/expop/expop_3.txt");
//    List<Triplet> trips = Triplet.readTrips(file + ".xls");
    Iterator<Triplet> iter = trips.iterator();
    while (iter.hasNext())
    {
      Triplet t =  iter.next();
      if (t.fac_id.startsWith("M")) iter.remove();
    }
    System.out.println("trips.size() = " + trips.size());
//    CrossPlatformMapper.associateAndClean(trips, "resource/expop/nikidata.txt");
//    CrossPlatformMapper.associateWithGSE6919(trips, plat);

//    trips = Triplet.selectModulator(trips, "SPDEF");

    posCancer = CellTypeMatcher.getCancerProstateInExpop(comtype);
//    posNormal = CellTypeMatcher.getCancerProstateInExpop(comtype + "_primary");
    posNormal = CellTypeMatcher.getBenignProstateInExpop(comtype);
//    posCancer = CrossPlatformMapper.getPosInGSE6919(plat, false);
//    posNormal = CrossPlatformMapper.getPosInGSE6919(plat, true);

//    CellTypeMatcher.randomizeInside(posCancer, posNormal);

    boolean[] pos = CellTypeMatcher.takeOR(posNormal, posCancer);
    CellTypeMatcher.replaceValsToRanks(trips, pos);

    fillChangeMaps(trips);
    keepMostChangedTargetIsoforms(trips);
    fillMappingsAfter(trips);

    generateSVG(trips, file + "_in" + comtype);
//    generatePNG(trips, file);
//    printScores(trips);
    kron.stop();
    kron.print();
  }

  private static void fillMappingsAfter(Collection<Triplet> trips)
  {
    for (Triplet t : trips)
    {
      double gamma = Difference.calcGamma(t);
      String tarNm = t.getTSym() + (gamma > 0 ? "+" : "-");

      if (!tar2modNum.containsKey(tarNm)) tar2modNum.put(tarNm, 0);
      tar2modNum.put(tarNm, tar2modNum.get(tarNm) + 1);
    }
  }

  private static void fillChangeMaps(Collection<Triplet> trips)
  {
    TabDelimitedFileParser parser =
      new TabDelimitedFileParser("resource/expop/deviated-in-cancer-AR.txt");

    Map<String, String> deviationMap = parser.getOneToOneMap("ID", "PresenceInNormal");

    for (Triplet t : trips)
    {
      if (!gene2change.containsKey(t.M)) putToChangeMap(t.M);
      if (!gene2change.containsKey(t.F)) putToChangeMap(t.F);
      if (!gene2change.containsKey(t.T)) putToChangeMap(t.T);

      if (!normalMap.containsKey(t.T))
      {
        double pres = .5;
        if (deviationMap.containsKey(t.T.id))
        {
          pres = Double.parseDouble(deviationMap.get(t.T.id));
        }
        normalMap.put(t.T, pres > .8 ? 1 : pres < .2 ? -1 : 0);
      }
    }
    expnames = CellTypeMatcher.readSampleNames("resource/expop/expop_expnames.txt");
  }

//  static Map<String, Double> remmap = new HashMap<String, Double>();
  private static void putToChangeMap(Gene gene)
  {
    gene2change.put(gene, CellTypeMatcher.getChangeBetweenTissues(gene, posNormal, posCancer));

    gene2rankCh.put(gene, CellTypeMatcher.getMeanChange(gene, posNormal, posCancer));

//    double ch;
//    if (remmap.containsKey(gene.geneid)) ch = remmap.get(gene.geneid);
//    else
//    {
//      ch = Math.random() < .5 ? 0.2 : 0.8;
//      remmap.put(gene.geneid, ch);
//    }
//    gene2change.put(gene, ch);
  }

  private static void keepMostChangedTargetIsoforms(List<Triplet> trips)
  {
    System.out.println("trips.size() = " + trips.size());
    Map<String, Triplet> select = new HashMap<String, Triplet>();
    Map<String, Double> max = new HashMap<String, Double>();

    for (Triplet t : trips)
    {
      if (noChange(t.T)) continue;

//      double ch = Math.abs(gene2change.get(t.T) - 0.5);
      double ch = Math.abs(gene2rankCh.get(t.T));
      String key = t.M.geneid + "-" + t.F.id + "-" + t.T.geneid + (ch>0?"+":"-");

      if (!select.containsKey(key) || max.get(key) < ch)
      {
        select.put(key, t);
        max.put(key, ch);
      }
    }

    for (String key : new HashSet<String>(select.keySet()))
    {
      key = key.substring(0, key.length()-1);

      if (select.containsKey(key + "+") && select.containsKey(key + "-"))
      {
        select.remove(key + "+");
        select.remove(key + "-");
      }
    }

    trips.clear();
    trips.addAll(select.values());
    System.out.println("trips.size() = " + trips.size());
  }

  public static String getExpLabel(int index)
  {
    String s = posNormal[index] ? "N" : posCancer[index] ? "C" : "?";
    String name = expnames.get(index);
    s += "-" + CellTypeMatcher.getExpClass(name) + "-" + name;
    return s;
  }

  private static void saveGroupValues(Group group)
  {
    List<Gene> genes = new ArrayList<Gene>(group.getSize() + 1);
    genes.add(group.getFirstMod());
    for (List<Triplet> trips : group.cats.values())
    {
      for (Triplet t : trips)
      {
        genes.add(t.T);
      }
    }

    try
    {
      String file = "result/group_vals/" + group.getName().replace("|", "-");
      BufferedWriter writer = new BufferedWriter(new FileWriter(file + ".txt"));
      writer.write("Genes/Exps");
      for (int i = 0; i < posNormal.length; i++)
      {
        if (posNormal[i] || posCancer[i]) writer.write("\t" + getExpLabel(i));
      }

      for (Gene gene : genes)
      {
        if (!noChange(gene)) writeGeneValues(writer, gene);
      }

      writer.close();

//      List<Integer> indexes = Hierarchical.getCancerSubtype(genes, posNormal, posCancer);
//      writer = new BufferedWriter(new FileWriter(file  + " - subtype.txt"));
//
//      for (Integer index : indexes)
//      {
//        writer.write(index + "\n");
//      }
//
//      writer.close();

    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  private static void writeGeneValues(BufferedWriter writer, Gene gene)
    throws IOException
  {
    writer.write("\n" + gene.getPrintable());

    for (int i = 0; i < posNormal.length; i++)
    {
      if (posNormal[i] || posCancer[i]) writer.write("\t" + gene.value[i]);
    }
  }

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

    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 + 20 * top + 12;
      int rowbottom = rowCenter + 20 * bottom + 84;
      setText(g2d);
      g2d.setFont(modfont);
      String facName = factor.getSymbol();
      FontMetrics fm = g2d.getFontMetrics();
      int width = fm.stringWidth(facName);

      g2d.setPaint(getColor(
//        factor.calcPresenceOnTissue(posCancer),
        gene2change.get(factor),
        UP_COLOR, DOWN_COLOR, NOTR_COLOR));

      g2d.fillRect(18, rowCenter - 12, width+4, 24);
      setText(g2d);
      g2d.drawString(facName, 20, rowCenter + 10);

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

      g2d.drawString("activates",60,rowCenter-20);
      g2d.drawString("inhibits",60,rowCenter+30);

      for (int col = 0; col < row.length; col++)
      {
        Group group = row[col];
        if (group!=null)
        {
          drawGroup(g2d, group, 60 + 240 * col, rowStart, rowCenter, rowbottom);
          System.out.println(group);
        }
      }
      rowStart = rowbottom;
    }
  }

  private void drawGroup(Graphics2D g2d, Group mod, int x,
    int rowstart, int rowCenter, int rowbottom)
  {
//    if (mod.getFirstFac().id.startsWith("A"))
//      saveGroupValues(mod);

    mod.sortMembers();
    boolean showIsoforms = mod.getName().contains("|");

    g2d.setColor(Color.LIGHT_GRAY);
    g2d.drawRect(x+54,rowstart-50,220,rowbottom-rowstart-20);

    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= ((240 - width) / 2) + (showIsoforms ? 14 : 54);

    g2d.setComposite(text);
    paintPresenceBox(g2d, mod.getChangeListOfMod(), x+margin, rowstart - 44, width, 30);
    setText(g2d);

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

    g2d.setFont(labelfont);
    g2d.drawString("Enhances",x+66,rowstart);
    g2d.drawString("Attenuates",x+134,rowstart);
    g2d.drawString("Inverts",x+214,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) * 20, x, rowCenter);
        g2d.fill(bounds);
        setText(g2d);
        int i=0;
        for (Triplet t : targets)
        {
          i++;
//          double ch = gene.calcPresenceOnTissue(posCancer);
          double ch = gene2change.get(t.T);

          g2d.setPaint(getColor(ch, UP_COLOR, DOWN_COLOR, NOTR_COLOR));
          g2d.fillRect(bounds.x+1, bounds.y-20+i*20, 60, 20);
        }
        i=0;
        for (Triplet t : targets)
        {
          i++;

//          if (Difference.tissueSupportIsGreater(t))
          if (isGoodTarget(t) || isBadTarget(t))
          {
            if (isGoodTarget(t))
            {
              g2d.setPaint(GOOD_TARGET_COLOR);
            }
            else
            {
              g2d.setPaint(BAD_TARGET_COLOR);
            }
            g2d.drawRect(bounds.x+1, bounds.y - 19 + (i * 20), 59, 18);
            g2d.drawRect(bounds.x+2, bounds.y - 18 + (i * 20), 57, 16);
          }
          setText(g2d);
          g2d.drawString(t.getTSym(), bounds.x+4, bounds.y-4+i*20);
        }
      }
    }
  }

  private static boolean noChange(Gene g)
  {
    double dif = gene2change.get(g);
    return dif > .4 && dif < .6;
  }

  private static boolean targetFollowing(Triplet t)
  {
    if (noChange(t.T)) return false;

    double difT = gene2change.get(t.T) - .5;
    double difM = gene2change.get(t.M) - .5;
    double gamma = Difference.calcGamma(t);

    return difT * difM * gamma > 0;
  }

  private static boolean targetConfirmsActivation(Triplet t)
  {
    if (noChange(t.T)) return false;

    double difT = gene2change.get(t.T) - .5;
    double gamma = Difference.calcGamma(t);

    return difT * gamma > 0;
  }

  private static boolean isGoodTarget(Triplet t)
  {
    if (!targetFollowing(t)) return false;
    double globalDifT = normalMap.get(t.T);
    double difT = gene2change.get(t.T) - .5;
    return globalDifT * difT < 0;
  }

  private static boolean isBadTarget(Triplet t)
  {
    if (!targetFollowing(t)) return false;
    double globalDifT = normalMap.get(t.T);
    double difT = gene2change.get(t.T) - .5;
    return globalDifT * difT > 0;
  }

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

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

  public static void generateSVG(List<Triplet> trips, String outFile) throws IOException
  {
    // 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);

    PlotForTissue2 test = new PlotForTissue2();

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

    for (Gene factor : groupedTrips.keySet())
    {
      System.out.println("\nFactor = " + factor.getPrintable());
      List<Triplet> tripGroup = groupedTrips.get(factor);
      HashMap<String, Group> map = process(tripGroup);
      System.out.println("mods before filtering = " + map.size());
      filterMods(map);
      System.out.println("mods after filtering = " + map.size());

      if (!factor.id.startsWith("M"))
        try{writeDownGroups(map.values(),
          ("result/group_vals/" + comtype + "-" + factor.id + ".txt").replace("|", "_"));
        }catch (Throwable throwable){throwable.printStackTrace();}

      if (!map.isEmpty())
      {
        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 + ".svg"), "UTF-8");
    svgGenerator.stream(out, useCSS);
  }

  public static void generatePNG(List<Triplet> trips, String outFile) throws IOException
  {
    PlotForTissue2 test = new PlotForTissue2();

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

    Map<Gene, List<Group>> groupsMap = new HashMap<Gene, List<Group>>();

    for (Gene factor : groupedTrips.keySet())
    {
      if (factor.id.startsWith("M")) continue;
     
      List<Triplet> tripGroup = groupedTrips.get(factor);
      HashMap<String, Group> map = process(tripGroup);
      System.out.println("mods before filtering: " + map.size());
      filterMods(map);
      System.out.println("mods  after filtering: " + map.size());

      if (!map.isEmpty())
      {
        groupsMap.put(factor, new ArrayList<Group>(map.values()));
      }
    }

    List<Integer> heights = new ArrayList<Integer>();
    for (Gene factor : groupsMap.keySet())
    {
      List<Group> groups = groupsMap.get(factor);
      Collections.sort(groups);

      for (int i = 0; i <= ((groups.size()-1) / 5); i++)
      {
        int up = 0;
        int down = 0;
        for (int j = i*5; j < Math.min((i*5) + 5, groups.size()); j++)
        {
          Group g = groups.get(j);
          up = Math.max(up, g.getTop());
          down = Math.max(down, g.getBottom());
        }
        heights.add(up + down);
      }
    }

    int height = rowStart;
    for (Integer h : heights)
    {
      height += (h * 20) + 96;
    }

    // Create a buffered image in which to draw
    int width = 1310;
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // Create a graphics contents on the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, width, height);

    for (Gene factor : groupsMap.keySet())
    {
      test.paint(g2d, groupsMap.get(factor), factor);
    }

    // Save as PNG
    File file = new File(outFile + ".png");
    ImageIO.write(bufferedImage, "png", file);
  }

  static void printScores(List<Triplet> trips) throws IOException
  {
    Map<Gene, List<Triplet>> groupedTrips = groupToFactor(trips);

    for (Gene factor : groupedTrips.keySet())
    {
      List<Triplet> tripGroup = groupedTrips.get(factor);
      HashMap<String, Group> map = process(tripGroup);
      filterMods(map);
      List<Group> grList = new ArrayList<Group>(map.values());
      for (Group group : grList)
      {
        group.calcActivation();
      }
      Collections.sort(grList);

      for (Group group : grList)
      {
        double difM = gene2change.get(
          group.cats.values().iterator().next().iterator().next().M);
        String changeM = difM > 0.5 ? "up" : "down";

        System.out.println(factor.getPrintable() + "\t" + group.getName() + "\t" +
          group.getSize() + "\t" + fmt.format(group.activScore) + "\t" + changeM);
      }
    }
  }
  private static HashMap<String, Group> process(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 = t.M.getSymbol() + "|" + t.M.geneid + "|" + t.M.geneid;

      if (!model.containsKey(modul)) model.put(modul, new Group(t.M));
      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);

      mod.calcActivation();
//      if (mod.activScore > FOLLOW_PVAL_THR)
//      {
//        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, 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
  {
    Gene mod;
    private String name;
    boolean following;
    HashMap<Cat, List<Triplet>> cats = new HashMap<Cat, List<Triplet>>();
    Double activScore;

    public Group(Gene mod)
    {
      this.mod = mod;
      name = mod.getSymbol();
    }

    public int compareTo(Object o)
    {
      Group g = (Group) o;
      return g.getTop() + g.getBottom() - getTop() - getBottom();
//      return ((Group) o).getSize()-this.getSize();
//      return ((Group) o).score.compareTo(score);
    }

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

      return i;
    }

    public Gene getFirstFac()
    {
      return cats.values().iterator().next().iterator().next().F;
    }
    public Gene getFirstMod()
    {
      return cats.values().iterator().next().iterator().next().M;
    }

    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 List<Triplet> getTrips()
    {
      List<Triplet> trips = new ArrayList<Triplet>();
      for (List<Triplet> list : cats.values())
      {
        trips.addAll(list);
      }
      return trips;
    }

    public List<Double> getChangeListOfMod()
    {
      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(gene.calcPresenceOnTissue(cancer));
            list.add(gene2change.get(t.M));
            geneSet.add(t.M);
          }
        }
      }
      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);
        }
      }
    }

    public void calcActivation()
    {
      double activ = 0;
      double total = 0;

      for (Cat cat : cats.keySet())
      {
        List<Triplet> trips = cats.get(cat);

        for (Triplet t : trips)
        {
          if (noChange(t.T)) continue;

          double gamma = Difference.calcGamma(t);
          String nm = t.getTSym() + (gamma > 0 ? "+" : "-");
          activ += Math.signum(gamma) * gene2rankCh.get(t.T) / tar2modNum.get(nm);

//          if (targetConfirmsActivation(t)) activ++;
//          if (Math.random() < .5) good++;
          total += 1D / tar2modNum.get(nm);
        }
      }
//      double difM = gene2change.get(this.getFirstMod()) - .5;
//      following = (activ - (total / 2D)) * difM > 0;
//      if (total == 0) activScore = 0D;
//      else
//      {
//        activScore = Binomial.getPval(activ, total);
//        if (activScore == 0) activScore = 1E-10;
//        activScore = Math.log(activScore);
//        if (activ - (total / 2D) > 0) activScore *= -1;
//      }
      activScore = activ / total;
    }

    public String toString()
    {
      String s = name;
      s += "\t";

      boolean modUp = false;
      boolean modDown = false;

      for (Cat cat : cats.keySet())
      {
        for (Triplet t : cats.get(cat))
        {
          if (noChange(t.M)) continue;
          if (gene2change.get(t.M) > .5) modUp = true;
          if (gene2change.get(t.M) < .5) modDown = true;
        }
      }

      s += modUp && modDown ? "U/D" : modUp ? "U" : modDown ? "D" : "-";
      s += "\t" + fmt.format(activScore.doubleValue());
     
      return s;
    }
  }

  public static void writeDownGroups(Collection<Group> groups, String filename) throws Throwable
  {
    BufferedWriter writer = new BufferedWriter(new FileWriter(filename));

    for (Group group : groups)
    {
      writer.write(group + "\n");
    }

    writer.close();
  }

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

    THolder(Triplet t)
    {
      this.t = t;
      value = Triplet.getGeneToSymbolMap().get(t.target) + t.tar_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 * 68, y - v * (height + 8) + 4, 64, height);
    }

  }

  protected static void printSignatureCommons(Collection<Group> groups)
  {
    for (Group g : groups)
    {
      System.out.print("\t" + g.name);
    }
    for (Group g1 : groups)
    {
      System.out.print("\n" + g1.name);
      for (Group g2 : groups)
      {
        System.out.print("\t");
        if (g1 != g2)
        {
          System.out.print(getCommonSignatureRatio(g1, g2, true));
        }
      }
    }
    System.out.println("");
  }

  protected static double getCommonSignatureRatio(Group g1, Group g2, boolean similar)
  {
    Map<String, Integer> map = new HashMap<String, Integer>();
    List<Triplet> g1trips = g1.getTrips();
    for (Triplet t : g1trips)
    {
      map.put(t.getTSym(), (int) Math.signum(Difference.calcGamma(t)));
    }

    int cnt = 0;
    for (Triplet t : g2.getTrips())
    {
      if (map.containsKey(t.getTSym()))
      {
        if (similar)
          if (((int) Math.signum(Difference.calcGamma(t))) == map.get(t.getTSym()))
          {
            cnt++;
          }
        else
          if (((int) Math.signum(Difference.calcGamma(t))) != map.get(t.getTSym()))
          {
            cnt++;
          }
      }
    }
    return cnt / (double) g1trips.size();
  }

  static final Color UP_COLOR = new Color(255, 120, 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);
  static final Color GOOD_TARGET_COLOR = new Color(255, 255, 0);
  static final Color BAD_TARGET_COLOR = new Color(0, 0, 0);
}
TOP

Related Classes of gem.PlotForTissue2$THolder

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.