示例#1
0
  private static boolean checkSize(ResourceLocator locator) {

    if (!PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_SIZE_WARNING)) {
      return true;
    }

    final String path = locator.getPath();
    long size = FileUtils.getLength(path);
    int maxSize = 50000000; // 50 mb
    if (path.endsWith(".gz") || path.endsWith(".bgz")) {
      maxSize /= 4;
    }

    if (size > maxSize) {

      String message =
          "The file "
              + path
              + " is large ("
              + (size / 1000000)
              + " mb).  It is recommended "
              + "that large files be converted to the binary <i>.tdf</i> format using the IGVTools "
              + "<b>tile</b> command. Loading  unconverted ascii fies of this size can lead to poor "
              + "performance or unresponsiveness (freezing).  "
              + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a "
              + "command line program. See the user guide for more details.<br><br>Click <b>Continue</b> "
              + "to continue loading, or <b>Cancel</b> to skip this file.";

      return ConfirmDialog.optionallyShowConfirmDialog(
          message, PreferenceManager.SHOW_SIZE_WARNING, true);
    }
    return true;
  }
示例#2
0
  private JMenu createGenomeSpaceMenu() {

    JMenu menu = new JMenu("GenomeSpace");

    MenuAction menuAction = null;
    menuAction = new LoadFromGSMenuAction("Load File from GenomeSpace...", KeyEvent.VK_U, igv);
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menu.addSeparator();
    menuAction =
        new LoadGenomeFromGSMenuAction("Load Genome from GenomeSpace...", KeyEvent.VK_Z, igv);
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menu.addSeparator();

    menuAction = new GSSaveSessionMenuAction("Save Session to GenomeSpace...", igv);
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new GSOpenSessionMenuAction("Load Session from GenomeSpace...", igv);
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menu.add(new JSeparator());
    menuAction =
        new MenuAction("Logout") {
          @Override
          public void actionPerformed(ActionEvent e) {
            GSUtils.logout();
            if (MessageUtils.confirm(
                "You must shutdown IGV to complete the GenomeSpace logout. Shutdown now?")) {
              doExitApplication();
            }
          }
        };
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menu.add(new JSeparator());
    menuAction =
        new MenuAction("Register... ") {

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              BrowserLauncher.openURL(GENOMESPACE_REG_PAGE);
            } catch (IOException ex) {
              log.error("Error opening browser", ex);
            }
          }
        };
    menuAction.setToolTipText(GENOMESPACE_REG_TOOLTIP);
    menu.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menu.setVisible(
        PreferenceManager.getInstance().getAsBoolean(PreferenceManager.GENOME_SPACE_ENABLE));

    return menu;
  }
示例#3
0
文件: GSUtils.java 项目: CJ-Chen/igv
 private static synchronized String getDMHost() {
   try {
     return (new URL(
             PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_DM_SERVER)))
         .getHost();
   } catch (MalformedURLException e) {
     log.error(e);
     return null;
   }
 }
示例#4
0
文件: DBManager.java 项目: nh13/IGV
  private static ConnectionWrapper createConnection() {
    String driver = "com.mysql.jdbc.Driver";
    try {
      Class.forName(driver).newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    final PreferenceManager preferenceManager = PreferenceManager.getInstance();
    String host = preferenceManager.get(PreferenceManager.DB_HOST);
    String db = preferenceManager.get(PreferenceManager.DB_NAME);
    String port = preferenceManager.get(PreferenceManager.DB_PORT);

    String url = "jdbc:mysql://" + host;
    if (!port.equals("-1")) {
      url += ":" + port;
    }
    url += "/" + db;

    return connect(url);
  }
示例#5
0
 /**
  * Method description
  *
  * @param g
  */
 @Override
 public void paintComponent(Graphics g) {
   super.paintComponent(g);
   if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_ANTIALISING)) {
     ((Graphics2D) g)
         .setRenderingHint(
             RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
   }
   paintLegend(g);
   ((Graphics2D) g)
       .setRenderingHint(
           RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
 }
示例#6
0
  /** Test if the file type can be "tiled". */
  private static void validateIsTilable(String typeString) {

    boolean affective =
        PreferenceManager.getInstance().getAsBoolean(PreferenceManager.AFFECTIVE_ENABLE);
    if (!(typeString.endsWith("cn")
        || typeString.endsWith("igv")
        || typeString.endsWith("wig")
        ||
        // ifile.toLowerCase().endsWith("cpg.txt") ||
        typeString.endsWith("ewig")
        || typeString.endsWith("cn")
        || typeString.endsWith("snp")
        || typeString.endsWith("xcn")
        || typeString.endsWith("gct")
        || typeString.endsWith("tab")
        || typeString.endsWith("mage-tab")
        || typeString.endsWith("bedgraph")
        || Preprocessor.isAlignmentFile(typeString)
        || affective)) {
      throw new PreprocessingException(
          "Tile command not supported for files of type: " + typeString);
    }
  }
示例#7
0
文件: DBManager.java 项目: nh13/IGV
  private static ConnectionWrapper connect(String url) {
    try {
      return new ConnectionWrapper(DriverManager.getConnection(url, username, password));
    } catch (SQLException e) {
      int errorCode = e.getErrorCode();
      if (errorCode == 1044 || errorCode == 1045) {
        String host = PreferenceManager.getInstance().get(PreferenceManager.DB_HOST);

        Frame parent = Globals.isHeadless() ? null : IGV.getMainFrame();
        LoginDialog dlg = new LoginDialog(parent, false, host, false);
        dlg.setVisible(true);
        if (dlg.isCanceled()) {
          throw new RuntimeException("Must login to access" + host);
        }
        username = dlg.getUsername();
        password = new String(dlg.getPassword());
        return connect(url);

      } else {
        MessageUtils.showMessage("<html>Error connecting to database: <br>" + e.getMessage());
        return null;
      }
    }
  }
示例#8
0
  private JMenu createViewMenu() {

    List<JComponent> menuItems = new ArrayList<JComponent>();
    MenuAction menuAction = null;

    // Preferences
    menuAction =
        new MenuAction("Preferences...", null, KeyEvent.VK_P) {
          @Override
          public void actionPerformed(ActionEvent e) {
            UIUtilities.invokeOnEventThread(
                new Runnable() {
                  public void run() {
                    IGV.getInstance().doViewPreferences();
                  }
                });
          }
        };
    menuAction.setToolTipText(PREFERENCE_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction =
        new MenuAction("Color Legends ...", null, KeyEvent.VK_H) {
          @Override
          public void actionPerformed(ActionEvent e) {
            (new LegendDialog(IGV.getMainFrame())).setVisible(true);
          }
        };
    menuAction.setToolTipText(SHOW_HEATMAP_LEGEND_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuItems.add(new JSeparator());

    menuAction =
        new MenuAction("Show Name Panel", null, KeyEvent.VK_A) {
          @Override
          public void actionPerformed(ActionEvent e) {

            JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource();
            if (menuItem.isSelected()) {
              IGV.getInstance().getMainPanel().expandNamePanel();
            } else {
              IGV.getInstance().getMainPanel().collapseNamePanel();
            }
            IGV.getInstance().doRefresh();
          }
        };
    boolean isShowing = IGV.getInstance().getMainPanel().isExpanded();
    JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem();
    menuItem.setSelected(isShowing);
    menuItem.setAction(menuAction);
    menuItems.add(menuItem);

    JMenuItem panelWidthmenuItem = new JMenuItem();
    menuAction =
        new MenuAction("Set Name Panel Width...", null, KeyEvent.VK_A) {
          @Override
          public void actionPerformed(ActionEvent e) {
            MainPanel mainPanel = IGV.getInstance().getMainPanel();
            String currentValue = String.valueOf(mainPanel.getNamePanelWidth());
            String newValue =
                MessageUtils.showInputDialog("Enter track name panel width: ", currentValue);
            if (newValue != null) {
              try {
                Integer w = Integer.parseInt(newValue);
                if (w <= 0 || w == 1000) throw new NumberFormatException();
                PreferenceManager.getInstance().put(PreferenceManager.NAME_PANEL_WIDTH, newValue);
                mainPanel.setNamePanelWidth(w);
              } catch (NumberFormatException ex) {
                MessageUtils.showErrorMessage(
                    "Error: value must be a positive integer < 1000.", ex);
              }
            }
          }
        };
    panelWidthmenuItem.setAction(menuAction);
    menuItems.add(panelWidthmenuItem);

    // Hide or Show the attribute panels
    boolean isShow =
        PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_ATTRIBUTE_VIEWS_KEY);
    IGV.getInstance().doShowAttributeDisplay(isShow); // <= WEIRD doing IGV.getInstance() here!

    menuAction =
        new MenuAction("Show Attribute Display", null, KeyEvent.VK_A) {
          @Override
          public void actionPerformed(ActionEvent e) {

            JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource();
            PreferenceManager.getInstance().setShowAttributeView(menuItem.getState());
            IGV.getInstance().getMainPanel().invalidate();
            IGV.getInstance().doRefresh();
          }
        };
    menuItem = MenuAndToolbarUtils.createMenuItem(menuAction, isShow);
    menuItems.add(menuItem);

    menuAction =
        new MenuAction("Select Attributes to Show...", null, KeyEvent.VK_S) {

          @Override
          public void actionPerformed(ActionEvent e) {
            IGV.getInstance().doSelectDisplayableAttribute();
          }
        };
    menuAction.setToolTipText(SELECT_DISPLAYABLE_ATTRIBUTES_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction =
        new MenuAction("Show Header Panel", null, KeyEvent.VK_A) {
          @Override
          public void actionPerformed(ActionEvent e) {

            JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource();
            if (menuItem.isSelected()) {
              IGV.getInstance().getMainPanel().restoreHeader();
            } else {
              IGV.getInstance().getMainPanel().removeHeader();
            }
            IGV.getInstance().doRefresh();
          }
        };
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction, true));

    menuItems.add(new JSeparator());
    menuAction =
        new MenuAction("Reorder Panels...", null, KeyEvent.VK_S) {

          @Override
          public void actionPerformed(ActionEvent e) {
            ReorderPanelsDialog dlg = new ReorderPanelsDialog(IGV.getMainFrame());
            dlg.setVisible(true);
          }
        };
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuItems.add(new JSeparator());
    menuItems.add(new HistoryMenu("Go to"));

    // Add to IGVPanel menu
    MenuAction dataMenuAction = new MenuAction("View", null, KeyEvent.VK_V);
    viewMenu = MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction);
    return viewMenu;
  }
示例#9
0
  void createFileMenu() {

    List<JComponent> menuItems = new ArrayList<JComponent>();
    MenuAction menuAction = null;
    // We disable certain load items when there is no genome.
    boolean genomeLoaded = GenomeManager.getInstance().getCurrentGenome() != null;

    menuItems.add(new JSeparator());

    // Load menu items
    menuAction = new LoadFilesMenuAction("Load from File...", KeyEvent.VK_L, igv);
    menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_URL, KeyEvent.VK_U, igv);
    menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new LoadFromServerAction("Load from Server...", KeyEvent.VK_S, igv);
    menuAction.setToolTipText(UIConstants.LOAD_SERVER_DATA_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_DAS, KeyEvent.VK_D, igv);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.DB_ENABLED)) {
      menuAction = new LoadFromDatabaseAction("Load from Database...", 0, igv);
      menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));
    }

    String genomeId = IGV.getInstance().getGenomeManager().getGenomeId();
    if (EncodeFileBrowser.genomeSupported(genomeId)) {
      menuAction = new BrowseEncodeAction("Load from ENCODE...", KeyEvent.VK_E, igv);
      menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));
    }

    // Disable loading if no genome loaded. Something of an edge case
    if (!genomeLoaded) {
      for (JComponent menuItem : menuItems) {
        menuItem.setEnabled(false);
      }
    }

    menuItems.add(new JSeparator());

    // Session menu items
    menuAction = new NewSessionMenuAction("New Session...", KeyEvent.VK_N, igv);
    menuAction.setToolTipText(UIConstants.NEW_SESSION_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new OpenSessionMenuAction("Open Session...", KeyEvent.VK_O, igv);
    menuAction.setToolTipText(UIConstants.RESTORE_SESSION_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    menuAction = new SaveSessionMenuAction("Save Session...", KeyEvent.VK_V, igv);
    menuAction.setToolTipText(UIConstants.SAVE_SESSION_TOOLTIP);
    JMenuItem saveSessionItem = MenuAndToolbarUtils.createMenuItem(menuAction);
    menuItems.add(saveSessionItem);
    saveSessionItem.setEnabled(genomeLoaded);

    menuItems.add(new JSeparator());

    // ***** Snapshots
    // Snapshot Application
    menuAction =
        new MenuAction("Save Image ...", null, KeyEvent.VK_A) {
          @Override
          public void actionPerformed(ActionEvent e) {
            igv.saveImage(igv.getMainPanel());
          }
        };

    menuAction.setToolTipText(SAVE_IMAGE_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    // TODO -- change "Exit" to "Close" for BioClipse
    menuItems.add(new JSeparator()); // Exit
    menuAction =
        new MenuAction("Exit", null, KeyEvent.VK_X) {

          @Override
          public void actionPerformed(ActionEvent e) {
            doExitApplication();
          }
        };

    menuAction.setToolTipText(EXIT_TOOLTIP);
    menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction));

    // Empty the recent sessions list before we start to do
    // anything with it
    igv.getRecentSessionList().clear();

    // Retrieve the stored session paths
    String recentSessions = PreferenceManager.getInstance().getRecentSessions();
    if (recentSessions != null) {
      String[] sessions = recentSessions.split(";");
      for (String sessionPath : sessions) {
        if (!igv.getRecentSessionList().contains(sessionPath)) {
          igv.getRecentSessionList().add(sessionPath);
        }
      }
    }

    if (!IGV.getInstance().getRecentSessionList().isEmpty()) {

      menuItems.add(new JSeparator());

      // Now add menu items
      for (final String session : IGV.getInstance().getRecentSessionList()) {
        OpenSessionMenuAction osMenuAction =
            new OpenSessionMenuAction(session, session, IGV.getInstance());
        menuItems.add(MenuAndToolbarUtils.createMenuItem(osMenuAction));
      }
    }

    MenuAction fileMenuAction = new MenuAction("File", null, KeyEvent.VK_F);
    if (fileMenu == null) {
      fileMenu = MenuAndToolbarUtils.createMenu(menuItems, fileMenuAction);
    } else {
      fileMenu.removeAll();
      for (JComponent item : menuItems) {
        fileMenu.add(item);
      }
    }
  }
示例#10
0
 private void okButtonActionPerformed(ActionEvent e) {
   PreferenceManager.getInstance().putToolPath(pluginId, toolName, pathInput.getText());
   setVisible(false);
 }
示例#11
0
  private void loadAlignmentsTrack(ResourceLocator locator, List<Track> newTracks, Genome genome)
      throws IOException {

    try {
      String dsName = locator.getTrackName();

      // If the user tried to load the index,  look for the file (this is a common mistake)
      if (locator.getTypeString().endsWith(".sai") || locator.getTypeString().endsWith(".bai")) {
        MessageUtils.showMessage(
            "<html><b>ERROR:</b> Loading SAM/BAM index files are not supported:  "
                + locator.getPath()
                + "<br>Load the SAM or BAM file directly. ");
        return;
      }

      AlignmentDataManager dataManager = new AlignmentDataManager(locator, genome);

      // Check that alignments we loaded actually match some data.  Many BAM files will contain some
      // sequences
      // not represented in the genome, buf if there are no matches warn the user.
      List<String> seqNames = dataManager.getSequenceNames();
      if (seqNames != null && seqNames.size() > 0) {
        if (!checkSequenceNames(locator.getPath(), genome, seqNames)) {
          return;
        }
      }

      if (locator.getTypeString().endsWith("bam") || locator.getTypeString().endsWith("cram")) {
        if (!dataManager.hasIndex()) {
          MessageUtils.showMessage(
              "<html>Could not load index file for: "
                  + locator.getPath()
                  + "<br>  An index file is required for SAM & BAM files.");
          return;
        }
      }

      AlignmentTrack alignmentTrack =
          new AlignmentTrack(locator, dataManager, genome); // parser.loadTrack(locator, dsName);
      alignmentTrack.setName(dsName);
      alignmentTrack.setVisible(
          PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_ALIGNMENT_TRACK));

      // Create coverage track
      CoverageTrack covTrack =
          new CoverageTrack(locator, dsName + " Coverage", alignmentTrack, genome);
      covTrack.setVisible(
          PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_COV_TRACK));
      newTracks.add(covTrack);
      covTrack.setDataManager(dataManager);
      dataManager.setCoverageTrack(covTrack);

      alignmentTrack.setCoverageTrack(covTrack);

      // Search for precalculated coverage data
      // Skip for GA4GH & SU2C resources
      if (!(Ga4ghAPIHelper.RESOURCE_TYPE.equals(locator.getType())
          || locator.getPath().contains("dataformat=.bam")
          || OAuthUtils.isGoogleCloud(locator.getPath()))) {

        String covPath = locator.getCoverage();
        if (covPath == null) {
          boolean bypassFileAutoDiscovery =
              PreferenceManager.getInstance()
                  .getAsBoolean(PreferenceManager.BYPASS_FILE_AUTO_DISCOVERY);
          String path = locator.getPath();
          if (!bypassFileAutoDiscovery && !path.contains("/query.cgi?")) {
            covPath = path + ".tdf";
          }
        }
        if (covPath != null) {
          if (FileUtils.resourceExists(covPath)) {
            log.debug("Loading TDF for coverage: " + covPath);
            try {
              TDFReader reader = TDFReader.getReader(covPath);
              TDFDataSource ds = new TDFDataSource(reader, 0, dsName + " coverage", genome);
              covTrack.setDataSource(ds);
            } catch (Exception e) {
              log.error("Error loading coverage TDF file", e);
            }
          }
        }
      }

      boolean showSpliceJunctionTrack =
          PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK);

      SpliceJunctionTrack spliceJunctionTrack =
          new SpliceJunctionTrack(
              locator,
              dsName + " Junctions",
              dataManager,
              alignmentTrack,
              SpliceJunctionTrack.StrandOption.BOTH);
      spliceJunctionTrack.setHeight(60);
      spliceJunctionTrack.setVisible(showSpliceJunctionTrack);
      newTracks.add(spliceJunctionTrack);

      alignmentTrack.setSpliceJunctionTrack(spliceJunctionTrack);

      newTracks.add(alignmentTrack);

      log.debug("Alignment track loaded");

    } catch (IndexNotFoundException e) {
      MessageUtils.showMessage(
          "<html>Could not find the index file for  <br><br>&nbsp;&nbsp;"
              + e.getSamFile()
              + "<br><br>Note: The index file can be created using igvtools and must be in the same directory as the .sam file.");
    }
  }
示例#12
0
  /**
   * Render the track in the given rectangle.
   *
   * @param track
   * @param locusScores
   * @param context
   * @param arect
   */
  public synchronized void renderScores(
      Track track, List<LocusScore> locusScores, RenderContext context, Rectangle arect) {

    boolean showMissingData =
        PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_MISSING_DATA_KEY);

    Graphics2D noDataGraphics = context.getGraphic2DForColor(UIConstants.NO_DATA_COLOR);
    Graphics2D tickGraphics = context.getGraphic2DForColor(Color.BLACK);

    Rectangle adjustedRect = calculateDrawingRect(arect);
    double origin = context.getOrigin();
    double locScale = context.getScale();

    Color posColor = track.getColor();
    Color negColor = track.getAltColor();

    // Get the Y axis definition, consisting of minimum, maximum, and base value.  Often
    // the base value is == min value which is == 0.

    DataRange dataRange = track.getDataRange();
    float maxValue = dataRange.getMaximum();
    float baseValue = dataRange.getBaseline();
    float minValue = dataRange.getMinimum();
    boolean isLog = dataRange.isLog();

    if (isLog) {
      minValue = (float) (minValue == 0 ? 0 : Math.log10(minValue));
      maxValue = (float) Math.log10(maxValue);
    }

    // Calculate the Y scale factor.

    double delta = (maxValue - minValue);
    double yScaleFactor = adjustedRect.getHeight() / delta;

    // Calculate the Y position in pixels of the base value.  Clip to bounds of rectangle
    double baseDelta = maxValue - baseValue;
    int baseY = (int) (adjustedRect.getY() + baseDelta * yScaleFactor);
    if (baseY < adjustedRect.y) {
      baseY = adjustedRect.y;
    } else if (baseY > adjustedRect.y + adjustedRect.height) {
      baseY = adjustedRect.y + adjustedRect.height;
    }

    int lastPx = 0;
    for (LocusScore score : locusScores) {

      // Note -- don't cast these to an int until the range is checked.
      // could get an overflow.
      double pX = ((score.getStart() - origin) / locScale);
      double dx = Math.ceil((Math.max(1, score.getEnd() - score.getStart())) / locScale) + 1;
      if ((pX + dx < 0)) {
        continue;
      } else if (pX > adjustedRect.getMaxX()) {
        break;
      }

      float dataY = score.getScore();
      if (isLog && dataY <= 0) {
        continue;
      }

      if (!Float.isNaN(dataY)) {

        // Compute the pixel y location.  Clip to bounds of rectangle.
        double dy = isLog ? Math.log10(dataY) - baseValue : (dataY - baseValue);
        int pY = baseY - (int) (dy * yScaleFactor);
        if (pY < adjustedRect.y) {
          pY = adjustedRect.y;
        } else if (pY > adjustedRect.y + adjustedRect.height) {
          pY = adjustedRect.y + adjustedRect.height;
        }

        Color color = (dataY >= baseValue) ? posColor : negColor;
        drawDataPoint(color, (int) dx, (int) pX, baseY, pY, context);
      }
      if (showMissingData) {

        // Draw from lastPx + 1  to pX - 1;
        int w = (int) pX - lastPx - 4;
        if (w > 0) {
          noDataGraphics.fillRect(lastPx + 2, (int) arect.getY(), w, (int) arect.getHeight());
        }
      }
      if (!Float.isNaN(dataY)) {

        lastPx = (int) pX + (int) dx;
      }
    }
    if (showMissingData) {
      int w = (int) arect.getMaxX() - lastPx - 4;
      if (w > 0) {
        noDataGraphics.fillRect(lastPx + 2, (int) arect.getY(), w, (int) arect.getHeight());
      }
    }
  }
示例#13
0
  @Override
  public void renderBorder(Track track, RenderContext context, Rectangle arect) {

    Rectangle adjustedRect = calculateDrawingRect(arect);

    // Draw boundaries if there is room
    if (adjustedRect.getHeight() >= 10) {

      /// TrackProperties pros = track.getProperties();

      // midline

      DataRange axisDefinition = track.getDataRange();
      float maxValue = axisDefinition.getMaximum();
      float baseValue = axisDefinition.getBaseline();
      float minValue = axisDefinition.getMinimum();

      double maxX = adjustedRect.getMaxX();
      double x = adjustedRect.getX();
      double y = adjustedRect.getY();

      if ((baseValue > minValue) && (baseValue < maxValue)) {
        int baseY = computeYPixelValue(adjustedRect, axisDefinition, baseValue);

        getBaselineGraphics(context).drawLine((int) x, baseY, (int) maxX, baseY);
      }

      PreferenceManager prefs = PreferenceManager.getInstance();

      Color altColor = track.getAltColor();
      Color borderColor =
          (prefs.getAsBoolean(PreferenceManager.CHART_COLOR_BORDERS)
                  && altColor != null
                  && altColor.equals(track.getColor()))
              ? track.getColor()
              : Color.lightGray;
      Graphics2D borderGraphics = context.getGraphic2DForColor(borderColor);

      // Draw the baseline -- todo, this is a wig track option?
      double zeroValue = axisDefinition.getBaseline();
      int zeroY = computeYPixelValue(adjustedRect, axisDefinition, zeroValue);
      borderGraphics.drawLine(adjustedRect.x, zeroY, adjustedRect.x + adjustedRect.width, zeroY);

      // Optionally draw "Y" line  (UCSC track line option)
      if (track.isDrawYLine()) {
        Graphics2D yLineGraphics = context.getGraphic2DForColor(Color.gray);
        int yLine = computeYPixelValue(adjustedRect, axisDefinition, track.getYLine());
        GraphicUtils.drawDashedLine(
            borderGraphics, adjustedRect.x, yLine, adjustedRect.x + adjustedRect.width, yLine);
      }

      // If the chart has + and - numbers draw both borders or none. This
      // needs documented somewhere.
      boolean drawBorders = true;

      if (minValue * maxValue < 0) {
        drawBorders =
            prefs.getAsBoolean(PreferenceManager.CHART_DRAW_BOTTOM_BORDER)
                && prefs.getAsBoolean(PreferenceManager.CHART_DRAW_TOP_BORDER);
      }

      if (drawBorders && prefs.getAsBoolean(PreferenceManager.CHART_DRAW_TOP_BORDER)) {
        borderGraphics.drawLine(
            adjustedRect.x, adjustedRect.y, adjustedRect.x + adjustedRect.width, adjustedRect.y);
      }

      if (drawBorders && prefs.getAsBoolean(PreferenceManager.CHART_DRAW_BOTTOM_BORDER)) {
        borderGraphics.drawLine(
            adjustedRect.x,
            adjustedRect.y + adjustedRect.height,
            adjustedRect.x + adjustedRect.width,
            adjustedRect.y + adjustedRect.height);
      }
    }
    /*
    (CHART_DRAW_TOP_BORDER));
    prefs.setDrawBottomBorder(getBooleanPreference(CHART_DRAW_BOTTOM_BORDER));
    prefs.setColorBorders(getBooleanPreference(CHART_COLOR_BORDERS));
    prefs.setDrawAxis(getBooleanPreference(CHART_DRAW_Y_AXIS));
    prefs.setDrawTrackName(getBooleanPreference(CHART_DRAW_TRACK_NAME));
    prefs.setColorTrackName(getBooleanPreference(CHART_COLOR_TRACK_NAME));
    prefs.setAutoscale(getBooleanPreference(CHART_AUTOSCALE));
    prefs.setShowDataRange(getBooleanPreference(CHART_SHOW_DATA_RANGE));
     */
  }
示例#14
0
  /**
   * Method description
   *
   * @param track
   * @param context
   * @param arect
   */
  @Override
  public void renderAxis(Track track, RenderContext context, Rectangle arect) {

    // For now disable axes for all chromosome view
    if (context.getChr().equals(Globals.CHR_ALL)) {
      return;
    }

    super.renderAxis(track, context, arect);

    Rectangle drawingRect = calculateDrawingRect(arect);

    PreferenceManager prefs = PreferenceManager.getInstance();

    Color labelColor =
        prefs.getAsBoolean(PreferenceManager.CHART_COLOR_TRACK_NAME)
            ? track.getColor()
            : Color.black;
    Graphics2D labelGraphics = context.getGraphic2DForColor(labelColor);

    labelGraphics.setFont(FontManager.getFont(8));

    if (prefs.getAsBoolean(PreferenceManager.CHART_DRAW_TRACK_NAME)) {

      // Only attempt if track height is > 25 pixels
      if (arect.getHeight() > 25) {
        Rectangle labelRect = new Rectangle(arect.x, arect.y + 10, arect.width, 10);
        labelGraphics.setFont(FontManager.getFont(10));
        GraphicUtils.drawCenteredText(track.getName(), labelRect, labelGraphics);
      }
    }

    if (prefs.getAsBoolean(PreferenceManager.CHART_DRAW_Y_AXIS)) {

      Rectangle axisRect = new Rectangle(arect.x, arect.y + 1, AXIS_AREA_WIDTH, arect.height);

      DataRange axisDefinition = track.getDataRange();
      float maxValue = axisDefinition.getMaximum();
      float baseValue = axisDefinition.getBaseline();
      float minValue = axisDefinition.getMinimum();

      // Bottom (minimum tick mark)
      int pY = computeYPixelValue(drawingRect, axisDefinition, minValue);

      labelGraphics.drawLine(
          axisRect.x + AXIS_AREA_WIDTH - 10, pY, axisRect.x + AXIS_AREA_WIDTH - 5, pY);
      GraphicUtils.drawRightJustifiedText(
          formatter.format(minValue), axisRect.x + AXIS_AREA_WIDTH - 15, pY, labelGraphics);

      // Top (maximum tick mark)
      int topPY = computeYPixelValue(drawingRect, axisDefinition, maxValue);

      labelGraphics.drawLine(
          axisRect.x + AXIS_AREA_WIDTH - 10, topPY, axisRect.x + AXIS_AREA_WIDTH - 5, topPY);
      GraphicUtils.drawRightJustifiedText(
          formatter.format(maxValue), axisRect.x + AXIS_AREA_WIDTH - 15, topPY + 4, labelGraphics);

      // Connect top and bottom
      labelGraphics.drawLine(
          axisRect.x + AXIS_AREA_WIDTH - 10, topPY, axisRect.x + AXIS_AREA_WIDTH - 10, pY);

      // Middle tick mark.  Draw only if room
      int midPY = computeYPixelValue(drawingRect, axisDefinition, baseValue);

      if ((midPY < pY - 15) && (midPY > topPY + 15)) {
        labelGraphics.drawLine(
            axisRect.x + AXIS_AREA_WIDTH - 10, midPY, axisRect.x + AXIS_AREA_WIDTH - 5, midPY);
        GraphicUtils.drawRightJustifiedText(
            formatter.format(baseValue),
            axisRect.x + AXIS_AREA_WIDTH - 15,
            midPY + 4,
            labelGraphics);
      }

    } else if (track.isShowDataRange() && arect.height > 20) {
      drawScale(track.getDataRange(), context, arect);
    }
  }
示例#15
0
  /**
   * Construct alignment blocks from the Goby alignment entry. This method uses the convention that
   * '=' denotes a match to the reference.
   *
   * <p>Conventions for storing sequence variations in Goby alignments are described <a
   * href="http://tinyurl.com/goby-sequence-variations">here</a>
   *
   * @param alignmentEntry The Goby alignment entry to use
   */
  public void buildBlocks(Alignments.AlignmentEntry alignmentEntry) {

    ObjectArrayList<AlignmentBlock> blocks = new ObjectArrayList<AlignmentBlock>();
    ObjectArrayList<AlignmentBlock> insertionBlocks = new ObjectArrayList<AlignmentBlock>();

    int start = alignmentEntry.getPosition();
    ByteArrayList bases = new ByteArrayList();
    ByteArrayList scores = new ByteArrayList();
    int readLength = alignmentEntry.getQueryLength();

    byte[] readBases = new byte[readLength];
    byte[] readQual = new byte[readLength];
    Arrays.fill(readBases, (byte) '=');
    if (alignmentEntry.hasReadQualityScores()) {
      readQual = alignmentEntry.getReadQualityScores().toByteArray();
    } else {
      Arrays.fill(readQual, (byte) 40);
    }
    int j = 0;
    int insertedBases = 0;
    int deletedBases = 0;
    final int leftPadding = alignmentEntry.getQueryPosition();
    boolean showSoftClipped =
        PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_SOFT_CLIPPED);
    if (showSoftClipped && entry.hasSoftClippedBasesLeft()) {
      int clipLength = entry.getSoftClippedBasesLeft().length();

      addSoftClipBlock(
          blocks,
          Math.max(0, entry.getPosition() - clipLength),
          entry.getSoftClippedBasesLeft(),
          readQual,
          entry.hasSoftClippedQualityLeft(),
          entry.getSoftClippedQualityLeft().toByteArray(),
          0);
    }
    for (Alignments.SequenceVariation var : alignmentEntry.getSequenceVariationsList()) {
      final String from = var.getFrom();
      final int fromLength = from.length();
      final String to = var.getTo();
      final int toLength = from.length();
      final int sequenceVariationLength = Math.max(fromLength, toLength);
      final ByteString toQuality = var.getToQuality();

      if (hasReadInsertion(from)) {
        bases.clear();
        scores.clear();
        for (int i = 0; i < sequenceVariationLength; i++) {
          final char toChar = i >= toLength ? '-' : to.charAt(i);
          int size = toQuality.size();
          final byte qual = size > 0 && i < size ? toQuality.byteAt(i) : 40;

          bases.add((byte) toChar);
          scores.add(qual);
          deletedBases++;
        }
        addBlock(insertionBlocks, alignmentEntry.getPosition() + var.getPosition(), bases, scores);
        bases.clear();
        scores.clear();
      } else if (!to.contains("-")) {
        for (int i = 0; i < toLength; i++) {
          final int offset = j + var.getPosition() + i - 1 + leftPadding - insertedBases;
          if (offset > 0 && offset < readBases.length) {
            readBases[offset] = (byte) to.charAt(i);
            if (i < toQuality.size()) {
              readQual[offset] = toQuality.byteAt(i);
            }
          }
        }
      } else {
        // has read deletion:
        insertedBases++;
      }
    }

    int pos = start;
    int matchLength = alignmentEntry.getQueryAlignedLength() - deletedBases;
    int endAlignmentRefPosition = matchLength + start;
    bases.clear();
    scores.clear();
    int maxIndex = Math.min(readBases.length, readQual.length);
    while (pos < endAlignmentRefPosition) {
      final int index = pos - start + leftPadding;
      if (index < maxIndex) {
        bases.add(readBases[index]);
        scores.add(readQual[index]);
      } else {
        break;
      }
      ++pos;
    }

    addBlock(blocks, start, bases, scores);
    blocks = introduceDeletions(blocks, entry);
    if (showSoftClipped && entry.hasSoftClippedBasesRight()) {

      int targetAlignedLength = entry.getTargetAlignedLength();
      addSoftClipBlock(
          blocks,
          entry.getPosition() + targetAlignedLength,
          entry.getSoftClippedBasesRight(),
          readQual,
          entry.hasSoftClippedQualityRight(),
          entry.getSoftClippedQualityRight().toByteArray(),
          entry.getQueryAlignedLength() + entry.getSoftClippedBasesLeft().length());
    }
    block = blocks.toArray(new AlignmentBlock[blocks.size()]);
    Arrays.sort(block, blockComparator);
    insertionBlock = insertionBlocks.toArray(new AlignmentBlock[insertionBlocks.size()]);
    Arrays.sort(insertionBlock, blockComparator);
    ObjectArrayList<GobyAlignment> list = null;

    if (alignmentEntry.hasSplicedForwardAlignmentLink()
        || alignmentEntry.hasSplicedBackwardAlignmentLink()) {
      // if has a forward link, store a reference to this alignment in the reader (which represents
      // the window scope)
      list = iterator.cacheSpliceComponent(this);
      if (list.size() > 1 && spliceListIsValid(list)) {

        final GobyAlignment spliceHeadAlignment = list.get(0);

        ObjectArrayList<AlignmentBlock> splicedBlocks = new ObjectArrayList<AlignmentBlock>();
        splicedBlocks.addAll(ObjectArrayList.wrap(spliceHeadAlignment.block));
        splicedBlocks.addAll(blocks);
        spliceHeadAlignment.block = splicedBlocks.toArray(new AlignmentBlock[splicedBlocks.size()]);

        ObjectArrayList<AlignmentBlock> splicedInsertionBlocks =
            new ObjectArrayList<AlignmentBlock>();
        splicedInsertionBlocks.addAll(ObjectArrayList.wrap(spliceHeadAlignment.insertionBlock));
        splicedInsertionBlocks.addAll(insertionBlocks);
        spliceHeadAlignment.insertionBlock =
            splicedInsertionBlocks.toArray(new AlignmentBlock[splicedInsertionBlocks.size()]);

        if (spliceHeadAlignment.gapTypes == null) {
          spliceHeadAlignment.gapTypes = new CharArrayList(10);
        }
        spliceHeadAlignment.gapTypes.add(SamAlignment.SKIPPED_REGION);

        // Since the previous alignment carries this information, we clear up block and
        // insertionBlock
        // in this alignment, but keep any softClips:
        this.block = keepSoftClips(block);
        this.insertionBlock = new AlignmentBlock[0];
      }
    }
  }