diff --git "a/data/dataset_Nucleic_acids.csv" "b/data/dataset_Nucleic_acids.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Nucleic_acids.csv" @@ -0,0 +1,83750 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/Globals.java",".java","6528","121","package symap; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Font; +import java.io.File; + +/****************************************** + * Global constants and prt routines + * See util:Jhtml.java for more constants for Help pages + * See SyMAPmanager:printVerions() for banner including java version + * See DBconn2 for checking database variables + * Search DIR_SELF for code snippets that depend on how isSelf is processed and displayed + * Version changes may be in (1) database.Version, (2) in code calling DBconn2.tableCheckAddColumn or (3) Version.isVerLt + */ +public class Globals { + public static final String VERSION = ""v5.7.9c""; // see Version.isVerLt (if add char, must be single, e.g. v5.7.5b) + public static final String DATE = "" (4-Jan-26)""; + public static final String VERDATE = VERSION + "" "" + DATE; + public static final int DBVER = 7; // CAS512 v3, CAS520 v4, CAS522 v5, CAS543 v6, CAS546 v7 + public static final String DBVERSTR = ""db"" + DBVER; + public static final String JARVERION = ""17.0.11""; // verify with 'jar xvf symap.jar META-INF', view META_INF + + public static String MAIN_PARAMS = ""symap.config""; // default; changed on command line -c + + public static final String PERSISTENT_PROPS_FILE = "".symap_saved_props""; // under user's directory; see props.PersistenProps + + // Set in SyMAPmanager + public static boolean INFO=false; // -ii; popup indices, query overlap, case-insensitive; also set on -tt and -dd + public static boolean TRACE=false; // -tt; write files for query and anchor2 + public static boolean DEBUG=false; // -dd; use for possible error + public static boolean DBDEBUG=false; // -dbd; adds fields to DB + + public static boolean bMySQL=false; // -sql; check MySQL + public static boolean bTrim=true; // -a do not trim 2D alignments; see closeup.AlignPool + public static boolean bRedoSum=false; // -s redo summary + public static boolean bQueryOlap=false; // -go show gene olap for algo2 instead of exon (was -q CAS578) + public static boolean bQueryPgeneF=false; // -pg run old PgeneF algo instead of new Cluster; (was -g CAS578) + public static boolean bQuerySaveLgClust=false; // -ac Merge all clusters, regardless of size + + public static final String exonTag = ""Exon #""; // type exon + public static final String geneTag = ""Gene #""; // type gene + + // These are the pseudo_annot.type values + public static final String geneType = ""gene""; // this is hard-coded many places; search 'gene' + public static final String exonType = ""exon""; + public static final String pseudoType = ""pseudo""; // pseudo type + public static final String gapType = ""gap""; + public static final String centType = ""centromere""; + + public static final String pseudoChar = ""~""; // pseudo tag; + public static final String minorAnno = ""*""; // used in Query and Anno popup for hit to non-assigned anno + public static final String DOT = ""."", SDOT=""\\."";// separates block, collinear, gene#; second is for split + public static final int abbrevLen = 5; // max length of abbreviation of project name; CAS578 + + public static final int MAX_CLOSEUP_BP=50000; // Used in CloseUp and Query; + public static final String MAX_CLOSEUP_K = ""50kb""; + public static final int MAX_2D_DISPLAY=30000; // Query and Sfilter; + public static final String MAX_2D_DISPLAY_K = ""30kb""; + public static final int MAX_YELLOW_BOX=50000; // used in SeqFilter for drawing yellow boxes + + public static final int T=0, Q=1; // for target (2) and query (1); + + public static final String IGN = ""IGN""; // self-synteny; for Report + public static final String SS_X = ""X"", SS_Z=""Y"";// Self-synteny opposite project ends with this + + public static final int NO_VALUE = Integer.MIN_VALUE; + + public static final int LEFT_ORIENT = -1; + public static final int CENTER_ORIENT = 0; + public static final int RIGHT_ORIENT = 1; + + // Cursor Types + public static final Cursor DEFAULT_CURSOR = Cursor.getDefaultCursor(); + public static final Cursor WAIT_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); + public static final Cursor HAND_CURSOR = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); + public static final Cursor S_RESIZE_CURSOR = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); + public static final Cursor MOVE_CURSOR = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); + public static final Cursor CROSSHAIR_CURSOR = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + + public static final Font textFont = new Font(Font.MONOSPACED,Font.PLAIN,12); + public static final int textHeight = 12; + public static final Color white = Color.white; + + // Exports + public static String alignDir = ""queryMSA""; + public static String getExport() { + String saveDir = System.getProperty(""user.dir"") + ""/exports/""; + File temp = new File(saveDir); + if(!temp.exists()) { + System.out.println(""Create "" + saveDir); + temp.mkdir(); + } + return saveDir; + } + + // positive is the gap between (s1,e1) and (s2, e2); negative is the overlap + // works for contained; copied from anchor2.Arg.java + public static int pGap_nOlap(int s1, int e1, int s2, int e2) { + return -(Math.min(e1,e2) - Math.max(s1,s2) + 1); + } + + // outputs + public static String bToStr(boolean b) {return (b) ? ""T"" : ""F"";} + public static void prt(String msg) {System.out.println(msg);} // permanent message + public static void prtStdErr(String msg) {System.err.println(msg);} // permanent message; + public static void xprt(String msg) {System.out.println(msg);} // temp message + public static void rprt(String msg) {System.err.print("" "" + msg + ""... \r"");}// to stderr + public static void rclear() { + System.err.print("" \r"");} + public static void eprt(String msg) {System.err.println(""***Error: "" + msg);} + public static void die(String msg) {eprt(msg); System.exit(-1);} + + public static void dtprt(String msg) {if (TRACE || DEBUG) System.out.println(msg);} + public static void tprt(String msg) {if (TRACE) System.out.println(msg);} + public static void tprt(int num, String msg) {if (TRACE) System.out.format(""%,10d %s\n"",num, msg);} + public static void dprt(String msg) {if (DEBUG) System.out.println(msg);} + public static void deprt(String msg) {if (DEBUG) System.err.println(msg);} + public static String toTF(boolean b) {return (b) ? ""T"" : ""F"";} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/Ext.java",".java","6725","204","package symap; + +import java.io.File; + +import util.ErrorReport; +import util.Jhtml; + +/***************************************************** + * This file checks what architecture and what /ext subdirectories to use. + * extSubDir is set at startup, and cannot be changed; hence, it is okay these variables are static + */ +public class Ext { + private static final String extDir = ""ext/""; // directory of external programs + private static final String dirMummer=""mummer/"", dirMuscle=""muscle/"", dirMafft=""mafft/""; + private static String archDir; // set on startup (linux64, mac, macM4); user can set in symap.config + + private static String mummer4Path=null; // can put full mummer4 path in symap.config; + + public static final String exNucmer=""nucmer"", exPromer=""promer"", exCoords=""show-coords""; // accessed in AlignMain + private static final String exMuscle=""muscle"", exMafft=""mafft.bat""; + + public static String getPlatform() { + return System.getProperty(""os.name"") + "":"" + System.getProperty(""os.arch""); + } + /************************************************************** + * SyMAPmanager reading config; can physically set; otherwise, will calculate + */ + public static boolean setArch(String userArch) { + if (userArch!=null) { + archDir = userArch; + if (!archDir.endsWith(""/"")) archDir = archDir + ""/""; + return checkMUMmer(); + } + String plat = System.getProperty(""os.name"").toLowerCase(); + + if (plat.contains(""linux"")) { + archDir = ""lintel64/""; + return true; + } + if (!plat.contains(""mac"")) { + System.err.println(""The os.name is not lintel64 or Mac OS X""); + System.err.println(""There are no executables for your machine""); + System.err.println(""See "" + Jhtml.SYS_GUIDE_URL + Jhtml.ext); + return false; + } + // Mac OS X + String arch = System.getProperty(""os.arch"").toLowerCase(); + if (arch.equals(""aarch64"")) { + archDir = ""macM4/""; // checked in isMacM4 + return true; + } + if (arch.equals(""x86_64"")) { + archDir = ""mac/""; + return true; + } + System.err.println(""The Mac OS X architecture is not x86_64 or aarch64""); + System.err.println(""There are no executables for your machine""); + System.err.println(""See "" + Jhtml.SYS_GUIDE_URL + Jhtml.ext); + return false; + } + /************************************************************** + * SyMAPmanager reading config; add mummer4 stuff, which can be set in config file; + */ + public static void setMummer4Path(String mummer) { + mummer4Path=mummer; + // /m4 /m4/ /m4/bin /m4/bin/ + if (!mummer4Path.endsWith(""/bin"")) mummer4Path += ""/bin""; + if (!mummer4Path.endsWith(""/"")) mummer4Path += ""/""; + + checkDir(mummer4Path); + checkFile(mummer4Path+ exNucmer); + checkFile(mummer4Path+ exPromer); + checkFile(mummer4Path+ exCoords); + } + /***********************************************************************************/ + public static String getMuscleCmd() { + String cmd = extDir + dirMuscle + archDir + exMuscle; + if (!checkFile(cmd)) return null; + return cmd; + } + public static String getMafftCmd() { + String cmd = extDir + dirMafft + archDir + exMafft; + if (!checkFile(cmd)) return null; + return cmd; + } + + public static boolean isMummer4Path() {return mummer4Path!=null;} + public static String getMummerPath() { // mummer + if (mummer4Path!=null) return mummer4Path; + + String path = extDir + dirMummer + archDir; + if (!checkDir(path)) return """"; + + return path; + } + /***********************************************************************************/ + public static boolean isMac() { + return System.getProperty(""os.name"").toLowerCase().contains(""mac""); + } + public static boolean isMacM4() { + return archDir.equals(""macM4/""); + } + /************************************************************** + * Check ext directory when database is created or opened + * .. not checking blat since that is probably obsolete + */ + static public void checkExt() { // only called with database is created + try { + if (mummer4Path!=null) return; // already checked + + System.err.println(""Check external programs in "" + extDir + "" for "" + archDir); + + if (!checkDir(extDir)) { + System.err.println(""No "" + extDir + "" directory. Will not be able to run any external programs.""); + return; + } + checkMUMmer(); + + if (getMafftCmd()==null) { + System.err.println("" Will not be able to run MAFFT from SyMAP Queries""); + return; + } + + if (getMuscleCmd()==null) { + System.err.println("" Will not be able to run MUSCLE from SyMAP Queries""); + return; + } + + if (isMac()) { + String m = "" On Mac, MUMmer executables needs to be verified for 1st time use; \n see ""; + String u = Jhtml.TROUBLE_GUIDE_URL + Jhtml.macVerify; + System.out.println(m+u); + } + System.out.println(""Check complete\n""); + } + catch (Exception e) {ErrorReport.print(e, ""Checking executables""); } + } + // more mummer hard-coded in AlignRun.cleanup + static private boolean checkMUMmer() { + String mpath = getMummerPath(); + if (!checkDir(mpath)) { + System.err.println("" Will not be able to run MUMmer from SyMAP""); + return false; + } + checkFile(mpath+ ""mummer""); + checkFile(mpath+ exNucmer); + checkFile(mpath+ exPromer); + checkFile(mpath+ exCoords); + + if (mummer4Path==null) { // using supplied mummer v3; v4 already checked, but to be sure... + checkFile(mpath+ ""mgaps""); + checkDir(mpath+ ""aux_bin""); + checkFile(mpath+ ""aux_bin/prepro""); + checkFile(mpath+ ""aux_bin/postpro""); + checkFile(mpath+ ""aux_bin/prenuc""); + checkFile(mpath+ ""aux_bin/postnuc""); + checkDir(mpath+""scripts""); + } + + return true; + } + /**********************************************************/ + static private boolean checkFile(String fileName) { + try { + File file = new File(fileName); + + if (!file.exists()) { + System.err.println(""*** file does not exists: "" + fileName); + return false; + } + if (!file.isFile()) { + System.err.println(""*** is not a file: "" + fileName); + return false; + } + if (!file.canExecute()) { + System.err.println(""*** file is not executable: "" + fileName); + return false; + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Checking file "" + fileName); return false;} + } + static private boolean checkDir(String dirName) { + try { + File dir = new File(dirName); + + if (!dir.exists()) { + System.err.println(""*** directory does not exists: "" + dirName); + return false; + } + if (!dir.isDirectory()) { + System.err.println(""*** is not a directory: "" + dirName); + return false; + } + if (!dir.canRead()) { + System.err.println(""*** directory is not readable: "" + dirName); + return false; + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Checking directory "" + dirName); return false;} + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/FilterHandler.java",".java","1934","63","package symap.drawingpanel; + +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import javax.swing.JButton; + +import symap.mapper.Mapper; +import symap.mapper.Hfilter; +import symap.sequence.Sequence; +import symap.sequence.Sfilter; + +/******************************************************************** + * Used to open Sfilter and Hfilter + */ +public class FilterHandler implements ActionListener { + protected DrawingPanel drawingPanel; + protected Hfilter hFilter=null; + protected Sfilter sFilter=null; + protected JButton button; + + public FilterHandler(DrawingPanel dp) { + button = new JButton(); + button.setMargin(new Insets(2,4,2,4)); + this.drawingPanel = dp; + + button.addActionListener(this); + } + public void setHfilter(Mapper mapperObj) { // called in Mapper + if (hFilter != null) hFilter.closeFilter(); + hFilter = null; + if (mapperObj != null) { + hFilter = new Hfilter(drawingPanel.getFrame(),drawingPanel, mapperObj); + button.setText(hFilter.getTitle()); + } + } + public void setSfilter(Object seqObj) { // the object is a sequence Track + if (sFilter != null) sFilter.closeFilter(); + sFilter = null; + if (seqObj != null) { + sFilter = new Sfilter(drawingPanel.getFrame(),drawingPanel, (Sequence) seqObj); + button.setText(""Sequence Filter""); + } + } + public void hide() { + if (hFilter != null) hFilter.closeFilter(); + else if (sFilter != null) sFilter.closeFilter(); + } + public void actionPerformed(ActionEvent e) { + if (e.getSource() == button) { + if (hFilter != null && hFilter.canShow()) hFilter.displayHitFilter(); + else if (sFilter != null && sFilter.canShow()) sFilter.displaySeqFilter(); + } + } + public void showPopup(MouseEvent e) { + if (hFilter!=null) hFilter.showPopup(e); + else if (sFilter!=null) sFilter.showPopup(e); + } + public void closeFilter() {hide();} + public JButton getFilterButton() {return button;} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/ControlPanel.java",".java","15454","386","package symap.drawingpanel; + +import java.awt.Component; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; + +import colordialog.ColorDialogHandler; +import symap.Globals; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import util.ImageViewer; +import util.Jcomp; +import util.Jhtml; + +/** + * 2D drawingpanel Control Panel + */ +public class ControlPanel extends JPanel implements HelpListener { + private static final long serialVersionUID = 1L; + // These are accessed in DrawingPanel to match button text with function + protected static final String MOUSE_FUNCTION_ZOOM_ALL = ""Zoom All Tracks""; + protected static final String MOUSE_FUNCTION_ZOOM_SINGLE = ""Zoom Select Track""; + protected static final String MOUSE_FUNCTION_CLOSEUP = ""Align (Max "" + Globals.MAX_CLOSEUP_K + "")""; + protected static final String MOUSE_FUNCTION_SEQ = ""Seq Options""; + + private JButton homeButton, backButton, forwardButton; // Home does not clear highlighting + private JButton zoomPopupButton; + private JRadioButtonMenuItem zoomAllRadio = new JRadioButtonMenuItem(MOUSE_FUNCTION_ZOOM_ALL); + private JRadioButtonMenuItem zoomSelRadio = new JRadioButtonMenuItem(MOUSE_FUNCTION_ZOOM_SINGLE); + private JCheckBox zoomBox = new JCheckBox(""""); + + private JButton showPopupButton; + private JRadioButtonMenuItem showAlignRadio = new JRadioButtonMenuItem(MOUSE_FUNCTION_CLOSEUP); + private JRadioButtonMenuItem showSeqRadio = new JRadioButtonMenuItem(MOUSE_FUNCTION_SEQ); + private JCheckBox showBox = new JCheckBox(""""); + + private JButton plusButton, minusButton, shrinkButton, scaleButton; + private JButton showImageButton, editColorsButton, helpButtonLg, helpButtonSm; + + private DrawingPanel dp; + private HistoryControl hc; + private ColorDialogHandler cdh; + + public ControlPanel(DrawingPanel dp, HistoryControl hc, ColorDialogHandler cdh, HelpBar bar, boolean bIsCE){ + super(); + this.dp = dp; + this.hc = hc; + this.cdh = cdh; + + homeButton = Jcomp.createIconButton(this,bar,null,""/images/home.gif"", + ""Home: Go to original zoom view.""); + backButton = Jcomp.createIconButton(this,bar,null,""/images/back.gif"", + ""Back: Go back in zoom history""); + forwardButton = Jcomp.createIconButton(this,bar,null,""/images/forward.gif"", + ""Forward: Go forward in zoom history""); + + if (hc != null) hc.setButtons(homeButton,backButton,forwardButton); // See HistoryControl + + minusButton = Jcomp.createIconButton(this,bar,buttonListener,""/images/minus.gif"", + ""Decrease the bases shown""); + plusButton = Jcomp.createIconButton(this,bar,buttonListener,""/images/plus.gif"", + ""Increase the bases shown""); + shrinkButton = Jcomp.createIconButton(this,bar,buttonListener,""/images/shrink.png"", + ""Shrink space between tracks""); + scaleButton = Jcomp.createBorderIconButton(this,bar,buttonListener,""/images/scale.gif"", + ""Scale: Draw all of the tracks to bp scale""); + showImageButton = Jcomp.createIconButton(this, bar,buttonListener,""/images/print.gif"", + ""Save: Save as image.""); + editColorsButton = Jcomp.createIconButton(this,bar,buttonListener,""/images/colorchooser.gif"", + ""Colors: Edit the color settings""); + + helpButtonLg = Jhtml.createHelpIconUserLg(Jhtml.align2d); + helpButtonSm= Jcomp.createIconButton(this,bar,buttonListener,""/images/info.png"", + ""Quick Help Popup""); + + createMouseFunctionSelector(bar); // for drag&drop + + zoomPopupButton = Jcomp.createButtonGray(this,bar, null,""Zoom"", + ""Click checkmark to activate; Select button for menu; see Info (i)""); + showPopupButton = Jcomp.createButtonGray(this,bar, null,""Show"", + ""Click checkmark to activate; Select button for menu; see Info (i)""); + createSelectPopups(); + + JPanel row = Jcomp.createRowPanelGray(); + + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + setLayout(gbl); // If row.setLayout(gbl), cannot add Separators, but ipadx, etc work + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.gridheight = 1; + gbc.ipadx = gbc.ipady = 0; + + String sp0="""", sp1="" "", sp2="" ""; + if (hc != null) { + addToGrid(row, gbl, gbc, homeButton, sp1); + addToGrid(row, gbl, gbc, backButton, sp1); + addToGrid(row, gbl, gbc, forwardButton, sp2); + } + addToGrid(row, gbl, gbc, plusButton, sp1); + addToGrid(row, gbl, gbc, minusButton, sp2); + addToGrid(row, gbl, gbc, shrinkButton, sp2); + addToGrid(row, gbl, gbc, scaleButton, sp2); + + addToGrid(row, gbl, gbc, zoomBox, sp0); + addToGrid(row, gbl, gbc, zoomPopupButton, sp1); + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp1); // End home functions + + addToGrid(row, gbl, gbc, showBox, sp0); + addToGrid(row, gbl, gbc, showPopupButton, sp1); + + addToGrid(row, gbl, gbc, editColorsButton, sp2); + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp2); // End edit display + + addToGrid(row, gbl, gbc, showImageButton, sp1); + addToGrid(row, gbl, gbc, helpButtonLg, sp1); + addToGrid(row, gbl, gbc, helpButtonSm, sp1); + + add(row); + } + + private void addToGrid(JPanel cp, GridBagLayout gbl, GridBagConstraints gbc, Component comp, String sp) { + gbl.setConstraints(comp,gbc); + cp.add(comp); + if (sp.length()>0) addToGrid(cp, gbl,gbc,new JLabel(sp),""""); + } + + private void createSelectPopups() { + PopupListener listener = new PopupListener(); + zoomAllRadio.addActionListener(listener); + zoomSelRadio.addActionListener(listener); + showAlignRadio.addActionListener(listener); + showSeqRadio.addActionListener(listener); + + ///// zoom + JPopupMenu zoomPopupMenu = new JPopupMenu(""Zoom""); zoomPopupMenu.setBackground(Globals.white); + JMenuItem zpopupTitle = new JMenuItem(""Select Region of Track""); + zpopupTitle.setEnabled(false); + zoomPopupMenu.add(zpopupTitle); + zoomPopupMenu.addSeparator(); + zoomPopupMenu.add(zoomAllRadio); + zoomPopupMenu.add(zoomSelRadio); + ButtonGroup grp = new ButtonGroup(); + grp.add(zoomAllRadio);grp.add(zoomSelRadio); + + zoomPopupButton.setComponentPopupMenu(zoomPopupMenu); // zoomPopupButton create in main + zoomBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + boolean b = zoomBox.isSelected(); + zoomPopupButton.setEnabled(b); + showPopupButton.setEnabled(!b); + showBox.setSelected(!b); + + if (zoomAllRadio.isSelected()) dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_ALL); + else dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_SINGLE); + } + }); + zoomPopupButton.addMouseListener(new MouseAdapter() { // allows either left/right mouse to popup + public void mousePressed(MouseEvent e) { + zoomPopupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + }); + zoomBox.setSelected(true); + zoomPopupButton.setEnabled(true); + zoomAllRadio.setSelected(true); + + ////// show + JPopupMenu showPopupMenu = new JPopupMenu(""Show""); showPopupMenu.setBackground(Globals.white); + JMenuItem spopupTitle = new JMenuItem(""Select Region of Track""); + spopupTitle.setEnabled(false); + showPopupMenu.add(spopupTitle); + showPopupMenu.addSeparator(); + showPopupMenu.add(showAlignRadio); + showPopupMenu.add(showSeqRadio); + ButtonGroup grp2 = new ButtonGroup(); + grp2.add(showAlignRadio); grp2.add(showSeqRadio); + + showPopupButton.setComponentPopupMenu(showPopupMenu); // showPopupButton create in main + showBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + boolean b = showBox.isSelected(); + zoomPopupButton.setEnabled(!b); + showPopupButton.setEnabled(b); + zoomBox.setSelected(!b); + + if (showAlignRadio.isSelected()) dp.setMouseFunction(MOUSE_FUNCTION_CLOSEUP); + else dp.setMouseFunction(MOUSE_FUNCTION_SEQ); + } + }); + showPopupButton.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + showPopupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + }); + showBox.setSelected(false); + showPopupButton.setEnabled(false); + showAlignRadio.setSelected(true); + } + + private class PopupListener implements ActionListener { + private PopupListener() { } + public void actionPerformed(ActionEvent event) { + Object src = event.getSource(); + if (src == zoomAllRadio) { + zoomAllRadio.setSelected(true); + dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_ALL); + zoomPopupButton.setText(""Zoom""); + } + else if (src == zoomSelRadio) { + zoomSelRadio.setSelected(true); + dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_SINGLE); + zoomPopupButton.setText(""Zoom Select""); + } + else if (src == showAlignRadio) { + showAlignRadio.setSelected(true); + dp.setMouseFunction(MOUSE_FUNCTION_CLOSEUP); + showPopupButton.setText(""Show""); + } + else if (src == showSeqRadio) { + showSeqRadio.setSelected(true); + dp.setMouseFunction(MOUSE_FUNCTION_SEQ); + showPopupButton.setText(""Show Seq""); + } + } + } + private ActionListener buttonListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + final Object source = e.getSource(); + if (source == scaleButton) { + dp.isToScale = !dp.isToScale; + scaleButton.setBackground(Jcomp.getBorderColor(dp.isToScale )); + dp.drawToScale(); + } + + else if (source == minusButton) dp.changeShowRegion(0.5); + else if (source == plusButton) dp.changeShowRegion(2.0); + else if (source == shrinkButton) dp.shrinkSpace(); + + else if (source == editColorsButton) cdh.showX(); + else if (source == showImageButton) ImageViewer.showImage(""Exp_2D"", (JPanel)dp); + else if (source == helpButtonSm) popupHelp(); + } + }; + + ////////////////////////////////////////////////// + // Use to be a functional drop-down for these functions; still used for Drag&drop to work + private JComboBox createMouseFunctionSelector(HelpBar bar) { + String [] labels = { MOUSE_FUNCTION_ZOOM_ALL,MOUSE_FUNCTION_ZOOM_SINGLE,MOUSE_FUNCTION_CLOSEUP,MOUSE_FUNCTION_SEQ}; + JComboBox comboMouseFunctions = new JComboBox (labels); + + comboMouseFunctions.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String item = (String) comboMouseFunctions.getSelectedItem(); + dp.setMouseFunction(item); + } + }); + comboMouseFunctions.setSelectedIndex(0); + if (bar != null) bar.addHelpListener(comboMouseFunctions,this); + return comboMouseFunctions; + } + ////////////////////////////////////////////////////////// + protected void setPanelEnabled(boolean enable) { + scaleButton.setEnabled(enable); + showImageButton.setEnabled(enable); + editColorsButton.setEnabled(enable); + + minusButton.setEnabled(enable); + plusButton.setEnabled(enable); + shrinkButton.setEnabled(enable); + if (hc != null) hc.setEnabled(enable); + } + + protected void clear() { + dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_ALL); + zoomBox.setSelected(true); showBox.setSelected(false); + + scaleButton.setSelected(false); + dp.isToScale = false; + scaleButton.setBackground(Jcomp.getBorderColor(false)); + } + + public String getHelpText(MouseEvent event) { // symap.frame.HelpBar + Component comp = (Component)event.getSource(); + Object source = event.getSource(); + String msg = comp.getName(); + if (source == scaleButton) { + if (dp.isToScale) msg += ""; Scaled"" ; + else msg += ""; Not scaled""; + } + else if (source == backButton) { + msg += ""; Back: "" + hc.nBack(); + } + else if (source == forwardButton) { + msg += ""; Forward: "" + hc.nForward(); + } + return msg; + } + public void setHistory(boolean toScale, String mouseFunction) { // drawingPanel.DrawingPanel + scaleButton.setSelected(toScale); + dp.isToScale = toScale; + scaleButton.setBackground(Jcomp.getBorderColor(toScale)); + + // always put back to Zoom as Show is not a history event + showPopupButton.setSelected(false); + showBox.setSelected(false); + showPopupButton.setEnabled(false); + showPopupButton.setText(""Show""); // Show is not a coordinate change, so even if set to SEQ, wasn't activated + + boolean bAll = !mouseFunction.equals(MOUSE_FUNCTION_ZOOM_SINGLE); + if (bAll) dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_ALL); + else dp.setMouseFunction(MOUSE_FUNCTION_ZOOM_SINGLE); + + zoomPopupButton.setSelected(true); + zoomBox.setSelected(true); + zoomPopupButton.setEnabled(true); + String label = (bAll) ? ""Zoom"" : ""Zoom Select""; + zoomPopupButton.setText(label); + + zoomAllRadio.setSelected(bAll); + zoomSelRadio.setSelected(!bAll); + } + + ///////////////// (i) //////////////////////////////////////// + + static final private String SEQ_help = ""Track Information:"" + + ""\n Hover on gene for information."" + + ""\n Right-click on gene for popup with the full description."" + + ""\n Right-click in track space for subset filter popup."" + + ""\n Problem: if there are more than 2 tracks and the sequence 'Annotation' is"" + + ""\n shown for the 2nd track, the mouse hover sometimes does not work correctly "" + + ""\n in the 3rd track."" + + ""\n\n""; + + static final private String HIT_help = ""Hit-wire Information:"" + + ""\n Hover on hit-wire for information (it will be highlighted)."" + + ""\n Right-click on hit-wire for popup for full information "" + + ""\n (it must be highlighted to be clickable)."" + + ""\n Right-click in white space of hit area for subset filter popup."" + + ""\n\n""; + + static final private String FIL_help = ""History Events (Home, > and <):"" + + ""\n Changing the coordinates of the display is a history event."" + + ""\n Coordinates are changed by any of the icons in the Control panel up to the first '|',"" + + ""\n plus the Sequence Filter coordinate changes."" + + ""\n Use < and > icons to go back and forward through history events."" + + ""\n Use the home icon to go back to starting display."" + + ""\n\n""; + + static final String DRAG_help = + ""The 'Zoom' and 'Show' buttons respond to selecting a region in a track."" + + ""\nTo select a region, position the mouse over a track, press the left mouse button and drag, "" + + ""\n release the button at the end of the region to be selected."" + + ""\nThe mouse function used depends on which button is checked, and which item "" + + ""\n in the checked Zoom or Show popup menu is selected."" + + ""\n Zoom: "" + + ""\n "" + MOUSE_FUNCTION_ZOOM_ALL + "": zoom the region and all tracks to match (default)."" + + ""\n "" + MOUSE_FUNCTION_ZOOM_SINGLE + "": only zoom the selected region."" + + ""\n Show: "" + + ""\n "" + MOUSE_FUNCTION_CLOSEUP + "": the region will be aligned with the "" + + ""\n opposite track in a popup window (default)."" + + ""\n "" + MOUSE_FUNCTION_SEQ + "": a popup menu will provide options to"" + + ""\n view the underlying sequence in a popup window."" + + ""\n\n""; + ; + static final String Q_HELP = ""See ? for details\n""; + + private void popupHelp() { + util.Popup.displayInfoMonoSpace(this, ""2d Control Quick Help"", + SEQ_help+HIT_help+FIL_help+DRAG_help+Q_HELP, false); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/Frame2d.java",".java","6532","204","package symap.drawingpanel; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.ContainerEvent; +import java.awt.event.ContainerListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +import props.PersistentProps; +import symap.Globals; +import symap.frame.HelpBar; +import util.ErrorReport; + +/*********************************************************** + * The 2D frame containing the drawingpanel, controlpanel and optional helpbar if on the bottom + * SyMAP2d creates the components of 2D display, and this puts them together + */ +public class Frame2d extends JFrame implements KeyListener, ContainerListener{ + private static final long serialVersionUID = 1L; + private static final String DISPLAY_SIZE_COOKIE = ""SyMAPDisplaySize""; + private static final String DISPLAY_POSITION_COOKIE = ""SyMAPDispayPosition""; + + private PersistentProps sizeProp, positionProp; + + private ControlPanel cp; + private DrawingPanel dp; + private SyMAP2d symap2d; + + public Frame2d(SyMAP2d symap2d, ControlPanel cp, DrawingPanel dp, HelpBar hb, + boolean showHelpBar, PersistentProps persistentProps) { + super(""SyMAP ""+ Globals.VERSION); + addComponentListener(new CompListener()); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + this.symap2d = symap2d; + this.cp = cp; + this.dp = dp; + + if (persistentProps != null) { + sizeProp = persistentProps.copy(DISPLAY_SIZE_COOKIE); + positionProp = persistentProps.copy(DISPLAY_POSITION_COOKIE); + } + dp.setListener(this); + dp.setCntl(cp); // so drawing panel has access for history + + Container container = getContentPane(); + container.setLayout(new BorderLayout()); + + JPanel bottomPanel = new JPanel(new BorderLayout()); + bottomPanel.add(cp,BorderLayout.NORTH); + bottomPanel.add(dp.getView(),BorderLayout.CENTER); + + container.add(bottomPanel,BorderLayout.CENTER); + if (hb != null && showHelpBar) // Otherwise, put in Explorer on left + container.add(hb, BorderLayout.SOUTH); + + setSizeAndLocationByProp(util.Jcomp.getScreenBounds(this)); + + addKeyAndContainerListenerRecursively(this); + } + // Called for non-Explorer 2d: so can close connection + public void dispose() { // override + symap2d.clear(); + super.dispose(); + } + public void showX() {// For non-explorer 2d; had to rename show() to something different + try { + if (isShowing()) dp.closeFilters(); + + Dimension d = new Dimension(); + int nMaps = dp.getNumMaps(); + int nAnnots = dp.getNumAnnots(); + int width = Math.min(1000, 300 + 300*nMaps + 130*nAnnots); + d.setSize(width, 900); + setSize(d); + super.setVisible(true); // Has to be displayed first, or the build will not happen + + // sort of fixes DotPlot Sequence.buildGraphics timing problem; it displays a flash of window + if (!dp.amake()) super.setVisible(false); + } + catch (Exception e) {ErrorReport.print(e, ""Show non-explorer 2d"");} + } + + public void hideX() { + dp.closeFilters(); + super.setVisible(false); + } + + protected void setFrameEnabled(boolean enable) { // DrawingPanel and Frame2d + if (enable) dp.getParent().setCursor(Globals.DEFAULT_CURSOR); + else dp.getParent().setCursor(Globals.WAIT_CURSOR); + + if (cp != null) cp.setPanelEnabled(enable); + + dp.setVisible(enable); + } + + protected Frame getFrame() {return (Frame)this;} + + /*********************************************************/ + private void setSizeAndLocationByProp(Rectangle defaultRect) { + Dimension dimP = getDisplayProp(positionProp); + if (dimP != null) setLocation(new Point(dimP.width,dimP.height)); + else setLocation(new Point(defaultRect.x,defaultRect.y)); + + Dimension dimS = getDisplayProp(sizeProp); + if (dimS != null) setSize(dimS); + else setSize(new Dimension(defaultRect.width,defaultRect.height)); + } + + private void addKeyAndContainerListenerRecursively(Component c) { + c.removeKeyListener(this); + c.addKeyListener(this); + if (c instanceof Container){ + Container cont = (Container)c; + cont.removeContainerListener(this); + cont.addContainerListener(this); + Component[] children = cont.getComponents(); + for(int i = 0; i < children.length; i++){ + addKeyAndContainerListenerRecursively(children[i]); + } + } + } + + private void removeKeyAndContainerListenerRecursively(Component c) { + c.removeKeyListener(this); + if(c instanceof Container){ + Container cont = (Container)c; + cont.removeContainerListener(this); + Component[] children = cont.getComponents(); + for(int i = 0; i < children.length; i++){ + removeKeyAndContainerListenerRecursively(children[i]); + } + } + } + + public void componentAdded(ContainerEvent e) { + addKeyAndContainerListenerRecursively(e.getChild()); + } + + public void componentRemoved(ContainerEvent e) { + removeKeyAndContainerListenerRecursively(e.getChild()); + } + public void keyReleased(KeyEvent e) { } + public void keyTyped(KeyEvent e) { } + public void keyPressed(KeyEvent e) { } + + private class CompListener implements ComponentListener { + public void componentMoved(ComponentEvent e) { + setDisplayProp(positionProp,getLocation()); + } + public void componentResized(ComponentEvent e) { + setDisplayProp(positionProp,getLocation()); + setDisplayProp(sizeProp,getSize()); + } + public void componentHidden(ComponentEvent e) { } + public void componentShown(ComponentEvent e) { } + + private void setDisplayProp(PersistentProps prop, Point p) { + setDisplayProp(prop,new Dimension(p.x,p.y)); + } + private void setDisplayProp(PersistentProps prop, Dimension dim) { + if (prop != null) { + if (dim != null) { + String ds = dim.width + "","" + dim.height; + prop.setProp(ds); + } + else System.err.println(""Dimension is null in Frame2d#setDisplayProp (PersistentProps,Dimension)!!!!""); + } + } + } + + private Dimension getDisplayProp(PersistentProps prop) { + if (prop == null) return null; + + Dimension dim = null; + String ds = prop.getProp(); + if (ds != null && ds.length() > 0) { + int ind = ds.indexOf(','); + if (ind >= 0) { + try { + int w = Integer.parseInt(ds.substring(0,ind)); + int h = Integer.parseInt(ds.substring(ind+1)); + dim = new Dimension(w,h); + } + catch (Exception e) {ErrorReport.print(e, ""get display plops"");} + } + } + return dim; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/HistoryListener.java",".java","246","9","package symap.drawingpanel; + +/** + * Used by the HistoryControl as the object to update when the history needs to be changed. + */ +public interface HistoryListener {// DrawingPanel, Symap2d, HistoryControl + public void setHistory(Object obj); +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/HistoryControl.java",".java","3759","135","package symap.drawingpanel; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Vector; + +import javax.swing.JButton; + +/** + * Create and control History Events. Created in SyMAP2d + */ +public class HistoryControl implements ActionListener { + private HistoryListener listener; + private JButton home, back, forward; + private History history; + + public HistoryControl() { this.history = new History(); }// SyMAP2d + + public synchronized void setListener(HistoryListener listener) { // SyMAP2d + this.listener = listener; + } + + protected synchronized void setButtons(JButton home, JButton back, JButton forward) { // Control panel + if (this.home != home) { + if (this.home != null) this.home.removeActionListener(this); + this.home = home; + home.addActionListener(this); + } + if (this.back != back) { + if (this.back != null) this.back.removeActionListener(this); + this.back = back; + back.addActionListener(this); + } + if (this.forward != forward) { + if (this.forward != null) this.forward.removeActionListener(this); + this.forward = forward; + forward.addActionListener(this); + } + } + + protected void add(Object obj) {// the object is DrawingPanelData class within DrawingPanel + history.add(obj); + setButtons(); + } + + protected void replace(Object obj) { + history.replace(obj); + } + protected synchronized void setEnabled(boolean enable) { // ControlPanel + if (!enable) { + home.setEnabled(false); + back.setEnabled(false); + forward.setEnabled(false); + } + else { + setButtons(); + } + } + + private synchronized void setButtons() { + home.setEnabled(history.isHome()); + back.setEnabled(history.isBack()); + forward.setEnabled(history.isForward()); + } + + public void actionPerformed(ActionEvent e) { + Object source = e.getSource(); + Object obj = null; + if (source == home) {obj = history.goHome();} + else if (source == back) {obj = history.goBack();} + else if (source == forward) {obj = history.goForward();} + if (obj != null) { + setButtons(); + listener.setHistory(obj); + } + } + protected void clear() {history.clear();} // called from SyMAP2d did not need History object + protected int nBack() {return history.index;} + protected int nForward() { + return history.historyVec.size()-history.index-1;} + /** + * Class History stores a history list with a current pointer. + * If it goes Home or back, then a new one is added, all remaining are lost but not freed. + */ + private class History { + private Vector historyVec = new Vector (50); + private int index = -1; + private int size = 50; + + private History() { } + + private synchronized void add(Object obj) { + historyVec.setSize(++index); + historyVec.add(obj); + if (historyVec.size() > size) { + historyVec.remove(0); + index--; + } + } + private synchronized void replace(Object obj) { + historyVec.set(index, obj); + } + private synchronized Object goHome() { // HistoryControl.actionPerformed + if (index > 0) { + index = 0; + return historyVec.get(0); + } + return null; + } + private synchronized Object goBack() { // HistoryControl.actionPerformed + if (index > 0) { + --index; + return historyVec.get(index); + } + return null; + } + private synchronized Object goForward() {// HistoryControl.actionPerformed + if (historyVec.size() > index+1) { + ++index; + return historyVec.get(index); + } + return null; + } + + protected synchronized boolean isHome() {return index > 0;} + protected synchronized boolean isBack() {return index > 0;} + protected synchronized boolean isForward() {return historyVec.size() > index+1;} + + private synchronized void clear() { // SyMAP2.HistoryControl.clear, HistoryControl.actionPerformed + index = -1; + historyVec.clear(); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/SyMAP2d.java",".java","2442","78","package symap.drawingpanel; + +import colordialog.*; +import database.DBconn2; +import props.*; +import symap.closeup.CloseUp; +import symap.frame.HelpBar; +import symapQuery.TableMainPanel; + +/** + * SyMAP sets up the 2D display for (see frame.ChrExpFrame for full Chromosome explorer): + * manager.SyMAPFrame.regenerate2DView + * dotplot.Data + * blockview.Block2Frame + * symapQuery.tableDataPanel.showSynteny + */ +public class SyMAP2d { + private Frame2d frame; + private DrawingPanel drawingPanel; + private ControlPanel controlPanel; + private HelpBar helpBar; + + private DBconn2 tdbc2; + private HistoryControl historyControl; + private PersistentProps persistentProps; + private CloseUp closeup; + private ColorDialogHandler colorDialogHandler; + + /** Dotplot, Block2Frame, Query **/ + public SyMAP2d(DBconn2 dbc2, TableMainPanel theTablePanel) { + this(dbc2, null, theTablePanel); + } + /** symap.frame.ChrExpFrame.regenerate2Dview + * hb==null is from dotplot or blocks display, so not full ChrExp + ***/ + public SyMAP2d(DBconn2 dbc2, HelpBar hb, TableMainPanel theTablePanel) + { + String type = (hb==null) ? ""P"" : ""E""; + this.tdbc2 = new DBconn2(""SyMAP2d"" + type + ""-"" + DBconn2.getNumConn(), dbc2); + + persistentProps = new PersistentProps(); + + if (hb == null) helpBar = new HelpBar(-1, 17); + else helpBar = hb; // for full explorer + + historyControl = new HistoryControl(); + + drawingPanel = new DrawingPanel(theTablePanel, tdbc2, historyControl, helpBar); + + historyControl.setListener(drawingPanel); + + colorDialogHandler = new ColorDialogHandler(persistentProps); // This sets changed colors + + controlPanel = new ControlPanel(drawingPanel, historyControl, colorDialogHandler, helpBar, (hb!=null)); + + frame = new Frame2d(this, controlPanel, drawingPanel, helpBar, hb==null, persistentProps); + + closeup = new CloseUp(drawingPanel, colorDialogHandler); + + drawingPanel.setCloseUp(closeup); + + colorDialogHandler.addListener((ColorListener)drawingPanel); + } + + public void clear() { // Frame2d.displose() called for non-Explorer 2d + tdbc2.close(); + clearLast(); + } + public void clearLast() { // ChrExpFrame when creating a new 2d; do not close tdc2 + drawingPanel.clearData(); // clear caches + historyControl.clear(); // clear history + controlPanel.clear(); + } + public Frame2d getFrame() {return frame;} + + public DrawingPanel getDrawingPanel() {return drawingPanel;} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/drawingpanel/DrawingPanel.java",".java","17512","496","package symap.drawingpanel; + +import java.awt.Color; +import java.awt.Frame; +import java.awt.Graphics; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import java.util.Vector; + +import database.DBconn2; +import colordialog.ColorListener; +import props.PropsDB; +import symap.Globals; +import symap.frame.HelpBar; + +import symap.mapper.HitData; +import symap.mapper.HfilterData; +import symap.mapper.Mapper; +import symap.mapper.MapperData; +import symap.sequence.Sequence; +import symap.sequence.TrackData; +import symap.sequence.TrackHolder; +import symap.sequence.TrackLayout; +import symap.closeup.CloseUp; + +import symapQuery.TableMainPanel; + +import util.ErrorReport; +import util.Popup; + +/** + * The DrawingPanel is the area that the maps are drawn onto. + * Used by Explorer for 2D right hand side, and for DotPlot, Query and Blocks for popup 2D + * + * 1. Create frame. 2. Assign trackholders. 3. Assign Sequence. + */ +public class DrawingPanel extends JPanel implements ColorListener, HistoryListener { + private static final long serialVersionUID = 1L; + + private static Color backgroundColor = Color.white; + + public double trackDistance = 100; // distance between tracks, used in TrackLayout; can be changed (was PADDING) + public boolean isToScale=false; // Tells TrackLayout tracks should be same size. + public String selectMouseFunction = null; // Set by ControlPanel for Selected Track Region + + private Mapper[] mappers; + private TrackHolder[] trackHolders; + private HistoryControl historyControl; + private Frame2d frame2dListener; + private PropsDB propDB = null; + private CloseUp closeup; + private ControlPanel cntlPanel; // for reset + + private DBconn2 dbc2; + + private JPanel buttonPanel = null; // Filter buttons added in TrackLayout + private JScrollPane scrollPane = null; + private HelpBar helpbar = null; // if non-explorer, helpbar goes at bottom + private TableMainPanel queryPanel = null; // special for Query + + private int numTracks = 0, numMaps=0; + + private boolean bUpdateHistory = true, bReplaceHistory = false; + + private void dprt(String msg) {symap.Globals.dprt(""DP: "" + msg);} + + // Called in frame.SyMAP2d; the explorer reuses the drawing panel, non-explorers do not. + public DrawingPanel(TableMainPanel listPanel, DBconn2 dbc2, HistoryControl hc, HelpBar bar) { + super(); + setBackground(backgroundColor); + + this.dbc2 = dbc2; // made copy in SyMAP2d, close in SyMAP2d + propDB = new PropsDB(dbc2); + historyControl = hc; + helpbar = bar; + queryPanel = listPanel; + + buttonPanel = new JPanel(null); // Filter buttons are added in TrackLayout + buttonPanel.setOpaque(false); + + scrollPane = new JScrollPane(this); + scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + scrollPane.getVerticalScrollBar().setUnitIncrement(50); + scrollPane.getHorizontalScrollBar().setUnitIncrement(50); + scrollPane.getViewport().setBackground(backgroundColor); + + scrollPane.setColumnHeaderView(buttonPanel); + scrollPane.getColumnHeader().setBackground(backgroundColor); + } + // Initialized tracks; called from all 2d inits + public void setTracks(int num) { + numTracks = num; ; + if (num>3) numTracks = num + (num-3); // after 3, ref is duplicated,e.g 1R3R4 num=4+1 + numMaps=numTracks-1; + + trackHolders = new TrackHolder[numTracks]; // assign seqObj in setSequenceTrack below + for (int i = 0; i < trackHolders.length; i++) { + int o = (i == 0) ? Globals.LEFT_ORIENT : Globals.RIGHT_ORIENT ; + trackHolders[i] = new TrackHolder(this, helpbar, (i+1), o); + add(trackHolders[i]); + } + + mappers = new Mapper[numMaps]; + for (int i = 0; i < mappers.length; i++) { + FilterHandler fh = new FilterHandler(this); + mappers[i] = new Mapper(this,trackHolders[i],trackHolders[i+1], fh, dbc2, propDB, helpbar, queryPanel); + add(mappers[i]); + mappers[i].setLocation(0,0); + } + + setLayout(new TrackLayout(this, trackHolders,mappers,buttonPanel)); + } + + // Called by all functions that display 2d; assigns sequence to a track + public Sequence setSequenceTrack(int position, int projIdx, int grpIdx, Color color) {// position starts at 1 + TrackHolder holder = trackHolders[position-1]; + Sequence track = new Sequence(this,holder); + + track.setup(projIdx, grpIdx); // sets all necessary in Sequence, read DB for anno + + track.setBackground(color); + track.setPosition(position); + + trackHolders[position-1].setTrack(track); + if (position>1) { + Sequence otrack = trackHolders[position-2].getTrack(); + track.setOtherProject(otrack.getProjIdx()); + otrack.setOtherProject(track.getProjIdx()); + } + + bUpdateHistory = true; // 1st history of stack + + return (Sequence) track; // for Query.TableDataPanel to set show defaults + } + + public void paint(Graphics g) { + super.paint(g); + for (Mapper m : mappers) { + if (m.isActive()) + m.paintComponent(g); + else dprt(""mapper timing problem""); + } + } + + protected void setListener(Frame2d dpl) { this.frame2dListener = dpl;} // Frame2d + protected void setCntl(ControlPanel cp) { this.cntlPanel = cp; } // Frame2d reset for History + + protected Frame getFrame() { // FilterHandler + if (frame2dListener != null) return frame2dListener.getFrame(); + else return null; + } + public void setFrameEnabled(boolean enabled) { + if (frame2dListener != null) frame2dListener.setFrameEnabled(enabled); + } + + public PropsDB getPropDB() {return propDB;} + public DBconn2 getDBC() {return dbc2; } // CloseUpDialog, Sequence, TextShowSeq; + protected JComponent getView() {return scrollPane;} + protected void setCloseUp(CloseUp closeup) {this.closeup = closeup;} + + public CloseUp getCloseUp() {return closeup;} + + public int getViewHeight() { return scrollPane.getViewport().getHeight();} + + public void resetColors() {// ColorDialogHandler + setBackground(backgroundColor); + + scrollPane.getViewport().setBackground(backgroundColor); + + scrollPane.getColumnHeader().setBackground(backgroundColor); + + buttonPanel.setBackground(backgroundColor); + setTrackBuild(); + + amake(); + } + + ///////////////////////////////////// + public Vector getHitsInRange(Sequence seqObj, int start, int end) {//closeup.TextShowSeq + Vector list = new Vector (); + for (Mapper m : mappers) { + if (m.isActive()) { + Sequence t1 = m.getTrack1(); // left + Sequence t2 = m.getTrack2(); // right + if (t1 == seqObj || t2 == seqObj) + list.addAll(m.getHitsInRange(seqObj,start,end)); + } + } + return list; + } + + /* Called by all functions that display 2d + * The ends of the map are locked till the next build if the track at pos is a Sequence.*/ + public boolean setTrackEnds(int pos, double startBP, double endBP) throws IllegalArgumentException { + Sequence track = trackHolders[pos-1].getTrack(); + if (track != null) { + track.setStartBP((int)Math.round(startBP),true); + track.setEndBP((int)Math.round(endBP),true); + setUpdateHistory(); + return true; + } + return false; + } + // set defaults for: symapQuery Show Synteny from table and dotplot.Data + public void setHitFilter(int map, HfilterData hf) { + mappers[map-1].getHitFilter().setChanged(hf, ""DP setHitFilter""); + } + + private Sequence getOpposingTrack(Sequence src, int orientation) { + for (int i = 0; i < numMaps; i++) { + Sequence t1 = mappers[i].getTrack1(); // left + Sequence t2 = mappers[i].getTrack2(); // right + + if (t1 == src && orientation == Globals.RIGHT_ORIENT) return t2; + else if (t2 == src && orientation == Globals.LEFT_ORIENT) return t1; + } + return null; + } + ///// Zoom //////////////////// + private void zoomTracks(Sequence src, int start, int end, int orientation ) { + Sequence t = getOpposingTrack(src, orientation); + if (t==null) return; + + int[] minMax = null; + for (Mapper m : mappers) { + Sequence t1 = m.getTrack1(); // left + Sequence t2 = m.getTrack2(); // right + if ((t1 == src && t2 == t) || (t1 == t && t2 == src)) + minMax = m.getMinMax(src, start, end); + } + + if (minMax != null) { + int pad = (minMax[1] - minMax[0]) / 20; // 5% + minMax[0] = Math.max(0, minMax[0]-pad); + minMax[1] = Math.min((int)t.getTrackSize()-1, minMax[1]+pad); + t.setEnd(minMax[1]); + t.setStart(minMax[0]); + zoomTracks(t, minMax[0], minMax[1], orientation); // recursive + } + } + + public void zoomAllTracks(Sequence src, int start, int end) { + zoomTracks(src, start, end, Globals.LEFT_ORIENT); + zoomTracks(src, start, end, Globals.RIGHT_ORIENT); + } + + public void setMouseFunction(String s) { selectMouseFunction = s; } + public String getMouseFunction() { return (selectMouseFunction == null ? """" : selectMouseFunction); } + public boolean isMouseFunction() { + return ControlPanel.MOUSE_FUNCTION_ZOOM_ALL.equals(selectMouseFunction) || + ControlPanel.MOUSE_FUNCTION_ZOOM_SINGLE.equals(selectMouseFunction) || + ControlPanel.MOUSE_FUNCTION_CLOSEUP.equals(selectMouseFunction) || + ControlPanel.MOUSE_FUNCTION_SEQ.equals(selectMouseFunction); + } + public boolean isMouseFunctionZoom() { + return ControlPanel.MOUSE_FUNCTION_ZOOM_ALL.equals(selectMouseFunction) || + ControlPanel.MOUSE_FUNCTION_ZOOM_SINGLE.equals(selectMouseFunction); + } + public boolean isMouseFunctionPop() { + return ControlPanel.MOUSE_FUNCTION_CLOSEUP.equals(selectMouseFunction) || + ControlPanel.MOUSE_FUNCTION_SEQ.equals(selectMouseFunction); + } + public boolean isMouseFunctionSeq() { return ControlPanel.MOUSE_FUNCTION_SEQ.equals(selectMouseFunction); } + public boolean isMouseFunctionCloseup() { return ControlPanel.MOUSE_FUNCTION_CLOSEUP.equals(selectMouseFunction); } + public boolean isMouseFunctionZoomSingle() { return ControlPanel.MOUSE_FUNCTION_ZOOM_SINGLE.equals(selectMouseFunction); } + public boolean isMouseFunctionZoomAll() { return ControlPanel.MOUSE_FUNCTION_ZOOM_ALL.equals(selectMouseFunction); } + + // ControlPanel: + up 2, - down 0.5 + protected boolean changeShowRegion(double factor) { + setUpdateHistory(); + + if (factor > 1) { + boolean fullyExpanded = true; + + for (int i = 0; i < numTracks; i++) { + if (!trackHolders[i].getTrack().fullyExpanded()) { + fullyExpanded = false; + break; + } + } + if (fullyExpanded) return true; + } + for (int i = 0; i < numTracks; i++) trackHolders[i].getTrack().changeAlignRegion(factor); + + smake(""dp: changedShowRegion""); + return true; + } + protected void shrinkSpace() { + if (trackDistance>10) trackDistance-=5; + setUpdateHistory(); + smake(""dp: shrinkspace""); + } + protected void drawToScale() { // ControlPanel + setUpdateHistory(); + if (isToScale) { // isToScale is changed from ControlPanel + double bpPerPixel = 0; + Sequence track = null; + for (int i = 0; i < numTracks; i++) { + track = trackHolders[i].getTrack(); + bpPerPixel = Math.max(bpPerPixel,track.getBpPerPixel()); + } + if (bpPerPixel == 0 && track != null) bpPerPixel = track.getBpPerPixel(); + for (int i = 0; i < numTracks; i++) + trackHolders[i].getTrack().setBpPerPixel(bpPerPixel); + } + else { + for (int i = 0; i < numTracks; i++) + trackHolders[i].getTrack().setDefPixel(); + } + smake(""dp: drawtoscale""); + } + + public void setVisible(boolean visible) { + for (int i = 0; i < numMaps; i++) mappers[i].setVisible(visible); + for (int i = 0; i < numTracks; i++) trackHolders[i].setVisible(visible); + + if (visible) doLayout(); + + super.setVisible(visible); + + getView().repaint(); + } + + public int getNumMaps() {return numMaps;}// Frame2d and Sequence + + public int getNumAnnots() {// Frame2d; for query, the annotation filter is turned on; make room + int ret = 0; + for (int i = 0; i < trackHolders.length; i++) { + TrackHolder th = trackHolders[i]; + if (th != null) { + Sequence t = th.getTrack(); + if (t.getShowAnnot()) ret++; + } + } + return ret; + } + + public String toString() { + return ""[ Drawing Panel: {"" + java.util.Arrays.asList(mappers).toString() + ""} ]""; + } + + //////////Clears ////////////////// + public void setTrackBuild() { // resetColor, Sequence.clearAllBuild + for (int i = 0; i < numTracks; i++) + if (trackHolders[i].getTrack() != null) + trackHolders[i].getTrack().setTrackBuild(); // hasBuild=false + } + protected void clearData() { + if (numMaps==0) return; + + closeFilters(); + + for (int i = 0; i < trackHolders.length; i++) trackHolders[i].getTrack().clearData(); + trackHolders = null; + for (int i=0; i 0) { + lblDesc = new JLabel("" "" + strDescription); + lblDesc.setFont(new Font(lblDesc.getFont().getName(), Font.PLAIN, lblDesc.getFont().getSize())); + } + + if (hasSeparator) + sep = new JSeparator(); + + panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + + collapse(); + + super.add( expandButton ); + if (lblDesc != null) super.add( lblDesc ); + if (sep != null) super.add( sep ); + super.add( panel ); + + collapsedSize = new Dimension(200, getPreferredSize().height); + } + + public Component add(Component comp) { + panel.add(comp); + return comp; + } + + private static ImageIcon createImageIcon(String path) { + java.net.URL imgURL = CollapsiblePanel.class.getResource(path); + if (imgURL != null) + return new ImageIcon(imgURL); + else { + System.err.println(""Couldn't find icon: ""+path); + return null; + } + } + + private void collapse() { + collapsed = true; + expandButton.setIcon(expandIcon); + expandButton.setToolTipText(""Show""); + if (sep != null) sep.setVisible(false); + panel.setVisible(false); + if (collapsedSize != null) setMaximumSize(collapsedSize); // prevent vertical stretching problem + } + + protected void expand() { + collapsed = false; + expandButton.setIcon(collapseIcon); + expandButton.setToolTipText(""Hide""); + if (sep != null) sep.setVisible(true); + panel.setVisible(true); + setMaximumSize(null); + } + + protected void doClick() { + expandButton.doClick(); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/MapLeft.java",".java","3630","141","package symap.frame; + +/************************************************************** + * Contains data for the ChromosomeExplorer icons + */ +import java.util.TreeSet; +import java.util.Vector; + +import symap.manager.Mproject; + +public class MapLeft { + private Mproject[] projects; + private ChrInfo[] allChrs; + private Block[] blocks; + private ChrInfo reference; + + private float maxBpPerUnit = 0; + private boolean bChanged = false; + + // Created in frame.ChrExpInit + protected MapLeft() { reference = null;} + + protected void setProjects(Mproject[] projects) {this.projects = projects;} + + protected void setChrs(ChrInfo[] tracks) { + this.allChrs = tracks; + reference = tracks[0]; + + for (ChrInfo t : tracks) + maxBpPerUnit = Math.max(maxBpPerUnit, t.getSizeBP()); + } + + protected void setBlocks(Block[] blocks) {this.blocks = blocks;} + + // symap.frame.ChrExpFrame + protected ChrInfo[] getChrs(int nProjID) { + Vector out = new Vector(); + + for (ChrInfo t : allChrs) + if (t.getProjIdx() == nProjID) + out.add(t); + + return out.toArray(new ChrInfo[0]); + } + // symap.frame.ProjIcons + protected ChrInfo[] getChrs(int nProjID,TreeSet grpIdxWithSynteny) { + Vector out = new Vector(); + + for (ChrInfo t : allChrs){ + if (t.getProjIdx() == nProjID){ + if (grpIdxWithSynteny.contains(t.getGroupIdx())){ + out.add(t); + } + } + } + return out.toArray(new ChrInfo[0]); + } + + protected Block[] getBlocksForProject(int nProjID) { + Vector out = new Vector(); + + for (Block b : blocks) + if (b.getProj1Idx() == nProjID) + out.add(b); + else if (b.getProj2Idx() == nProjID) + out.add(b.swap()); + + return out.toArray(new Block[0]); + } + + protected Mproject[] getProjects() { return projects; } + + protected int[] getVisibleProjectIDs() { // returns reference as first in list + Vector out = new Vector(); + out.add( reference.getProjIdx() ); + for (Mproject p : projects) { + if (getNumVisibleChrs(p.getID()) > 0) + out.add(p.getID()); + } + + int[] out2 = new int[out.size()]; + for (int i = 0; i < out2.length; i++) + out2[i] = out.get(i); + + return out2; + } + + protected int[] getVisibleGroupIDs() { // returns reference as first in list + int[] out = new int[getNumVisibleChrs()+1]; + out[0] = reference.getGroupIdx(); + int i = 1; + for (ChrInfo t : getVisibleChrs()) + out[i++] = t.getGroupIdx(); + return out; + } + + protected void setRefChr(ChrInfo reference) { + this.reference = reference; + bChanged = true; + } + + protected ChrInfo getRefChr() { return reference; } + protected boolean isRefChr(ChrInfo t) { return t == reference; } + + protected int getNumVisibleChrs() { // excluding the reference track + int n = 0; + for (ChrInfo t : allChrs) + if (t.isVisible() && t != reference) n++; + return n; + } + + private int getNumVisibleChrs(int nProjID) { + int n = 0; + for (ChrInfo t : allChrs) + if (t.isVisible() && t.getProjIdx() == nProjID) n++; + return n; + } + + protected ChrInfo[] getVisibleChrs() { // excluding the reference track + Vector visible = new Vector(); + for (ChrInfo t : allChrs) + if (t.isVisible() && t != reference) visible.add(t); + return visible.toArray(new ChrInfo[0]); + } + + protected void hideVisibleChrs() { // excluding the reference + for (ChrInfo t : allChrs) + if (t != reference) t.setVisible(false); + bChanged = true; + } + + protected void setVisibleChr(ChrInfo t, boolean visible) { + t.setVisible(visible); + bChanged = true; + } + + protected float getMaxBpPerUnit() { return maxBpPerUnit; } + + protected boolean hasChanged() { return bChanged; } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/ChrInfo.java",".java","1553","48","package symap.frame; + +import java.util.Vector; + +import symap.manager.Mproject; + +import java.awt.Color; + +/*********************************************** + * Created in ChrExpInit; used by Mapper, ChrExpInit, ChrExpFrame and ProjIcons + */ +public class ChrInfo { + protected Mproject project; + private String strGroupName; + private int nGroupIdx; + private int sizeBP; + private boolean bVisible = false; + + protected ChrInfo(Mproject project, String strGroupName, int nGroupIdx) { + this.project = project; + this.strGroupName = strGroupName; + this.nGroupIdx = nGroupIdx; + } + + public String toString() { return strGroupName; } + protected String getGroupName() { return strGroupName; } // frame.ProjIcons + + protected boolean isVisible() { return bVisible; } // Mapper + protected void setVisible( boolean bVisible ) { this.bVisible = bVisible; } // Mapper + + protected int getProjIdx() { return project.getID(); } // Mapper, ChrExpInit, ChrExpFrame + protected int getGroupIdx() { return nGroupIdx; } // Mapper, ChrExpInit, ChrExpFrame, ProjIcons + + protected int getSizeBP() { return sizeBP; } // ProjIcons, Mapper + protected void setSizeBP( int sizeBP ) { this.sizeBP = sizeBP; } // ChrExpInit; length of chromosome + + protected Color getColor() { return project.getColor(); } // ChrExpFrame.show2DView + + // Static + protected static ChrInfo getChrByGroupIdx(Vector tracks, int grpIdx) { // ChrExpInit.loadAllBlocks + for (ChrInfo t : tracks) { + if (t.getGroupIdx() == grpIdx) + return t; + } + return null; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/HelpBar.java",".java","4468","153","package symap.frame; + +import java.awt.Component; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.HashMap; + +import javax.swing.BoxLayout; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JTextArea; + +import javax.swing.text.DefaultCaret; +import javax.swing.BorderFactory; + +import colordialog.ColorListener; + +/****************************************************************** + * Help Box on left side of Chromosome explorer and bottom of other displays + */ +public class HelpBar extends JPanel + implements MouseListener, MouseMotionListener, ActionListener, ColorListener { + private static final long serialVersionUID = 1L; + private static final Font helpFont = new Font(""Courier"", 0, 12); + private static final Color helpColor = Color.black; + private static final Color helpBackgroundColor = Color.white; + private final String helpText = ""Move the mouse over an object for further information.""; + + private JTextArea helpLabel = null; + private Object currentHelpObj = null; + + private HashMap comps; + + public HelpBar(int width, int height) {// Values -1, 17 if help is on the bottom + super(false); + + comps = new HashMap(); + + setLayout(new BoxLayout(this,BoxLayout.X_AXIS)); + + if (width <= 0) width = Toolkit.getDefaultToolkit().getScreenSize().width; + setPreferredSize(new Dimension(width,height)); + + helpLabel = new JTextArea(); + helpLabel.setBorder( BorderFactory.createEmptyBorder(0, 5, 0, 5) ); + helpLabel.setLineWrap(true); + helpLabel.setWrapStyleWord(true); + helpLabel.setEditable(false); + ((DefaultCaret)helpLabel.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE); // disable auto-scroll (for scrollpane in SyMAPFrame3D) + + helpLabel.setOpaque(true); + helpLabel.setBackground(helpBackgroundColor); + helpLabel.setForeground(helpColor); + helpLabel.setFont(helpFont); + helpLabel.setMaximumSize(new Dimension(width*10,height*10)); + helpLabel.setMinimumSize(new Dimension(0,height)); + + add(helpLabel); + } + public void setHelp(String help, Object obj) { + if (help == null || help.equals("""")) { + help = helpText; // default help + } + else { + if (getSize().height < 50) { // Query 2D shows as one line at bottom + help = help.replaceAll(""\n"", "" ""); + help = help.replaceAll("": "", "": ""); + help = help.replaceAll("": "", "": ""); + help = help.replaceAll("": "", "": ""); + help = help.replaceAll("" "", "" ""); // remove additional extra spacing; CAS578 + } + } + helpLabel.setText(help); + currentHelpObj = obj; + } + + public void addHelpListener(Component comp) { + synchronized (comps) { + comps.put(comp,comp); + + comp.addMouseListener(this); + comp.addMouseMotionListener(this); + } + } + + public void addHelpListener(Component comp, HelpListener listener) { + synchronized (comps) { + comps.put(comp,listener); + + comp.addMouseListener(this); + comp.addMouseMotionListener(this); + } + } + + public void removeHelpListener(Component comp) { + synchronized (comps) { + comps.remove(comp); + + comp.removeMouseListener(this); + comp.removeMouseMotionListener(this); + if (currentHelpObj == comp) + setHelp("""",null); + } + } + + public void mouseMoved(MouseEvent e) { + synchronized (comps) { + Object obj = comps.get(e.getSource()); + if (obj != null) { + if (obj instanceof HelpListener) { + setHelp( ((HelpListener)obj).getHelpText(e), e.getSource() ); + } + else if (obj instanceof JComponent) { + setHelp( ((JComponent)obj).getToolTipText(e), e.getSource() ); + } + } + else if (e.getSource() instanceof JComponent) { + setHelp( ((JComponent)e.getSource()).getToolTipText(e), e.getSource() ); + } + } + } + + public void mouseEntered(MouseEvent e) { + mouseMoved(e); + } + + public void mouseExited(MouseEvent e) { + if (e.getSource() == currentHelpObj) { + setHelp("""",null); + } + } + + public void mouseDragged(MouseEvent e) { } + public void mouseClicked(MouseEvent e) { } + public void mousePressed(MouseEvent e) { } + public void mouseReleased(MouseEvent e) { } + + public void actionPerformed(ActionEvent e) {} + public void resetColors() { + if (helpLabel != null) { + helpLabel.setBackground(helpBackgroundColor); + helpLabel.setForeground(helpColor); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/ChrExpInit.java",".java","5597","167","package symap.frame; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import java.awt.Color; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Vector; + +import util.ErrorReport; +import database.DBconn2; +import symap.manager.Mproject; + +/********************************************************* + * Called when Chromosome Explorer is selected; loads projects, tracks, blocks and initializes track + * ChrExpFrame does the actual drawing of the icons on left using the mapper created here. + */ + +public class ChrExpInit implements PropertyChangeListener { + private ChrExpFrame expFrame; + private DBconn2 tdbc2; + + private Vector projects = new Vector(); + private Vector allChrs = new Vector(); + private MapLeft mapper = new MapLeft(); + + private static final Color[] projectColors = { Color.cyan, Color.green, new Color(0.8f, 0.5f, 1.0f), + Color.yellow, Color.orange }; + + /*************************************************************************/ + public ChrExpInit(String title, DBconn2 dbc2, Vector selectedProjVec) throws SQLException { // Called by ManagerFrame + tdbc2 = new DBconn2(""ChrExp-"" + DBconn2.getNumConn(), dbc2); // closed in ChrExpFrame + + for (Mproject p : selectedProjVec) addProject( p.getDBName() ); + makeDS(); + + expFrame = new ChrExpFrame(title, tdbc2, mapper); // finish mapper before this call, so it can be directly used + } + public ChrExpFrame getExpFrame() {return expFrame;} // managerFrame setVisible + + public void propertyChange(PropertyChangeEvent evt) {if (expFrame != null) expFrame.repaint();} + + private boolean addProject(String strName) { + try { + Mproject p = loadProject(strName); + if ( p != null ) { + p.setColor( projectColors[projects.size() % (projectColors.length)] ); + allChrs.addAll( loadProjectTracks(p) ); + projects.add( p ); + return true; + } + } + catch (Exception e) {ErrorReport.print(e, ""Add project for Explorer"");} + return false; + } + + private boolean makeDS() { // called after all projects are added + try { + Vector blocks = loadAllBlocks(allChrs); + + mapper.setProjects(projects.toArray(new Mproject[0])); + mapper.setChrs(allChrs.toArray(new ChrInfo[0])); + mapper.setBlocks(blocks.toArray(new Block[0])); + + projects = null; + allChrs = null; + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Build Explorer"");} + return false; + } + + private Mproject loadProject(String strProjName) throws Exception{ + int nProjIdx = -1; + String loaddate=""""; // put on left side by name + + ResultSet rs = tdbc2.executeQuery(""SELECT p.idx, p.loaddate "" + + ""FROM projects AS p where p.name='""+strProjName+""'""); + + if ( rs.next() ) { + nProjIdx = rs.getInt(1); + loaddate = rs.getString(2); + } + rs.close(); + + if (nProjIdx < 0) { + System.err.println(""Project '""+strProjName+""' not loaded.""); + return null; + } + + Mproject p = new Mproject(tdbc2, nProjIdx, strProjName, loaddate); + p.loadDataFromDB(); + p.loadParamsFromDB(); + return p; + } + + private Vector loadProjectTracks(Mproject p) { + try { + Vector projTracks = new Vector(); + + // Get group(s) and create track(s) + String qry = ""SELECT idx,name FROM xgroups WHERE proj_idx="" + p.getID() + + "" AND sort_order > 0 ORDER BY sort_order""; + ResultSet rs = tdbc2.executeQuery(qry); + while( rs.next() ) { + int nGroupIdx = rs.getInt(1); + String strGroupName = rs.getString(2); + projTracks.add(new ChrInfo(p, strGroupName, nGroupIdx)); + } + rs.close(); + + if (projTracks.isEmpty()) { + System.err.println(""No groups found for project "" + p.getID() + "" in database.""); + return projTracks; // empty + } + + // Initialize tracks + for (ChrInfo t : projTracks) { + rs = tdbc2.executeQuery(""SELECT length FROM pseudos WHERE (grp_idx=""+t.getGroupIdx()+"")""); + while( rs.next() ) { + t.setSizeBP( rs.getInt(1) ); + } + rs.close(); + } + return projTracks; + } catch (Exception e) {ErrorReport.print(e, ""Load tracks""); return null;} + } + + private Vector loadAllBlocks(Vector tracks) { + Vector blocks = new Vector(); + + try { // Load blocks for each track + String s = """"; + for (ChrInfo t : tracks) + s += t.getGroupIdx() + (t == tracks.lastElement() ? """" : "",""); + String strGroupList = ""("" + s + "")""; + String strQ = ""SELECT idx,grp1_idx,grp2_idx,start1,end1,start2,end2, corr FROM blocks "" + + ""WHERE (grp1_idx IN ""+strGroupList+"" AND grp2_idx IN ""+strGroupList+"")""; + + ResultSet rs = tdbc2.executeQuery(strQ); + while( rs.next() ) { + int blockIdx = rs.getInt(1); + int grp1_idx = rs.getInt(2); + int grp2_idx = rs.getInt(3); + int start1 = rs.getInt(4); + int end1 = rs.getInt(5); + int start2 = rs.getInt(6); + int end2 = rs.getInt(7); + float corr = rs.getFloat(8); + + ChrInfo t1 = ChrInfo.getChrByGroupIdx(tracks, grp1_idx); + ChrInfo t2 = ChrInfo.getChrByGroupIdx(tracks, grp2_idx); + + Block b = new Block(blockIdx, t1.getProjIdx(), t2.getProjIdx(), + t1.getGroupIdx(), t2.getGroupIdx(), start1, end1, start2, end2, corr); + if (!blocks.contains(b)) { + blocks.add(b); + } + } + rs.close(); + return blocks; + } catch (Exception e) {ErrorReport.print(e, ""Load blocks""); return null;} + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/ProjIcons.java",".java","6074","203","package symap.frame; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.TreeSet; + +import javax.swing.JComponent; + +import symap.manager.Mproject; + +/************************************************* + * Called by ChrExpFrame. Draw Chromosome Icons to for a project + */ +public class ProjIcons extends JComponent implements MouseListener, MouseMotionListener { + private static final long serialVersionUID = 1L; + private final static double MAX_CHR_HEIGHT = 80; + private final static int MIN_CHR_HEIGHT = 15; + private final static int WIDTH = 12; + private final static int GAP = 5; + private final static int FONT_HEIGHT = 11;//*fm.getHeight()*/ + private Mproject project; + private Block[] blocks; + private ChrInfo[] tracks; // chromosome + private MapLeft mapper; + private ActionListener listener; + private int lineSize = 15; + private int chrHeight = 0; + private int maxTracks = lineSize*30; + + protected ProjIcons(MapLeft mapper, Mproject project, ActionListener listener, + TreeSet grpIdxWithSynteny) { + super(); + + this.mapper = mapper; + this.project = project; + this.listener = listener; + this.tracks = mapper.getChrs(project.getID(),grpIdxWithSynteny); + this.blocks = mapper.getBlocksForProject(project.getID()); + + int height = 0; + for (ChrInfo t : tracks) + height = Math.max(height, (int)(MAX_CHR_HEIGHT * t.getSizeBP() / mapper.getMaxBpPerUnit())); + + chrHeight = height + 5; + if (tracks.length > maxTracks) + System.out.println(project.getDisplayName() + "" has more than "" + maxTracks + "" sequences.\nThe first "" + maxTracks + "" will be shown.""); + + int numTracks = Math.min(tracks.length,maxTracks); + while (numTracks > lineSize && numTracks % lineSize > 0 && numTracks % lineSize < 4) + { + lineSize++; // Don't put just one or two on a new line + } + int width = lineSize * (WIDTH + GAP) + GAP; + int nRows = 1 + numTracks/lineSize; + int compHeight = (chrHeight + FONT_HEIGHT + 10)*nRows; + Dimension d = new Dimension(width,compHeight); + setMinimumSize(d); + setMaximumSize(d); + setPreferredSize(d); + + addMouseListener(this); + addMouseMotionListener(this); + } + + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D)g; + int x = 5; + int y = FONT_HEIGHT; + + // Draw each chromosome + // Label box runs from y-FONT_HEIGHT to y + // Chromosome rectangle runs from y+6 to y+6+height + g2.setFont(new Font(g2.getFont().getName(), Font.PLAIN, 9)); + FontMetrics fm = g2.getFontMetrics(); + int nTrack = 0; + int numTracks = 1; + for (ChrInfo t : tracks) { + int height = (int)(MAX_CHR_HEIGHT * t.getSizeBP() / mapper.getMaxBpPerUnit()); + height = Math.max(height,MIN_CHR_HEIGHT); + boolean isVisible = (t.isVisible() || t == mapper.getRefChr()); + + int strWidth = fm.stringWidth(t.getGroupName()); + if (t == mapper.getRefChr()) { + g2.setColor(Color.RED); + g2.drawRect(x-1, y-FONT_HEIGHT/*fm.getHeight()*/, WIDTH+1, FONT_HEIGHT/*fm.getHeight()*/+3); + } + else + g2.setColor(Color.BLACK); + g2.drawString(t.getGroupName(), x+(WIDTH-strWidth)/2, y); + + if (isVisible) + g2.setColor(project.getColor()); + else + g2.setColor(project.getColor().darker().darker()); + + g2.fillRect(x, y+6, WIDTH, height); + + if (isVisible) + g2.setColor(Color.red); + else + g2.setColor(Color.red.darker()); + + for (Block b : blocks) { + // Make this project be the query and the reference be the target + if (b.isTarget(project.getID())) + b = b.swap(); + + if ((b.getGroup2Idx() == mapper.getRefChr().getGroupIdx() || mapper.isRefChr(t)) + && b.getGroup1Idx() == t.getGroupIdx()) + { + long startBP = (long) b.getStart1(); // this does not work right unless long + long endBP = (long) b.getEnd1(); + + int startY = (int)(height * startBP / t.getSizeBP()); + int endY = (int)(height * endBP / t.getSizeBP()); + int heightY = Math.max(1,Math.abs(endY-startY)); + g2.fillRect(x, y+6+startY, WIDTH, heightY); + } + } + + x += WIDTH+GAP; + nTrack++; + numTracks++; + if (numTracks > maxTracks) break; + + if (nTrack % lineSize == 0){ + x = 5; + y += chrHeight + FONT_HEIGHT + 10; + nTrack = 0; + } + } + } + + public void mouseClicked(MouseEvent e) { + int xClick = e.getX(); + int yClick = e.getY(); + int x = 5; + int y = FONT_HEIGHT; + boolean bChanged = false; + + int nTrack = 0; + int numTracks = 0; + for (ChrInfo t : tracks) { + if (!mapper.isRefChr(t)) { + if (xClick >= x && xClick <= x+WIDTH + && yClick >= y && yClick <= y+chrHeight+6) + { // Rectangle clicked: add/remove track + mapper.setVisibleChr(t, !t.isVisible()); + bChanged = true; + break; + } + else if (xClick >= x && xClick <= x+WIDTH + && yClick >= y-19 && yClick < y) + { // Number clicked: change reference + mapper.setRefChr(t); + mapper.hideVisibleChrs(); // clear selection (excluding reference) + bChanged = true; + break; + } + } + + x += WIDTH+5; + nTrack++; + numTracks++; + if (numTracks > maxTracks) break; + + if (nTrack % lineSize == 0) { + x = 5; + y += chrHeight + FONT_HEIGHT + 10; + nTrack = 0; + } + } + + if (bChanged) { // Call parent handler to redraw all displays of this type + if (listener != null) + listener.actionPerformed( new ActionEvent(this, -1, ""Redraw"") ); + } + } + + public void mouseEntered(MouseEvent e) { + setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) ); + } + public void mouseExited(MouseEvent e) { + setCursor( Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) ); + } + + public void mouseDragged(MouseEvent e) { } + public void mousePressed(MouseEvent e) { } + public void mouseReleased(MouseEvent e) { } + public void mouseMoved(MouseEvent e) { } + public String toString() { return project.getDBName(); } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/Block.java",".java","1514","48","package symap.frame; + +/********************************************************* + * Represents blocks for the ProjIcons on the left side of the explorer + */ +public class Block { + private int nBlockIdx; + private int nProj1Idx, nProj2Idx; + private int nGroup1Idx, nGroup2Idx; + private int start1, end1; + private int start2, end2; + private float corr; + + protected Block(int nBlockIdx, int nProj1Idx, int nProj2Idx, int nGroup1Idx, int nGroup2Idx, + int start1, int end1, int start2, int end2, float corr) + { + this.nBlockIdx = nBlockIdx; + this.nProj1Idx = nProj1Idx; + this.nProj2Idx = nProj2Idx; + this.nGroup1Idx = nGroup1Idx; + this.nGroup2Idx = nGroup2Idx; + this.start1 = start1; + this.end1 = end1; + this.start2 = start2; + this.end2 = end2; + this.corr = corr; + } + + public boolean equals(Object obj) { // override Object method + return ( nBlockIdx == ((Block)obj).nBlockIdx ); + } + + protected boolean isTarget(int nProjIdx) { return nProj2Idx == nProjIdx; } // projIdxon + + protected Block swap() { + return new Block(nBlockIdx, nProj2Idx, nProj1Idx, nGroup2Idx, nGroup1Idx, start2, end2, start1, end1, corr); + } + + protected int getStart1() { return start1; } + protected int getEnd1() { return end1; } + protected int getStart2() { return start2; } + protected int getEnd2() { return end2; } + protected int getProj1Idx() { return nProj1Idx; } + protected int getProj2Idx() { return nProj2Idx; } + protected int getGroup1Idx() { return nGroup1Idx; } + protected int getGroup2Idx() { return nGroup2Idx; } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/HelpListener.java",".java","136","8","package symap.frame; + +import java.awt.event.MouseEvent; + +public interface HelpListener { + public String getHelpText(MouseEvent e); +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/frame/ChrExpFrame.java",".java","16230","476","package symap.frame; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.TreeSet; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSplitPane; +import javax.swing.WindowConstants; +import javax.swing.border.BevelBorder; + +import symap.drawingpanel.DrawingPanel; +import symap.drawingpanel.Frame2d; +import symap.drawingpanel.SyMAP2d; +import symap.manager.Mproject; +import util.ErrorReport; +import util.LinkLabel; +import util.Jhtml; +import util.Jcomp; +import circview.CircFrame; +import database.DBconn2; +import dotplot.DotPlotFrame; + +/***************************************************** + * Chromosome Explorer: Displays left side and controls right (circle, 2d, dotplot) + */ +public class ChrExpFrame extends JFrame implements HelpListener { + private static final long serialVersionUID = 1L; + + private final int MIN_WIDTH = 1100, MIN_HEIGHT = 900; // cardPanel will be 825; + + private int VIEW_CIRC = 1, VIEW_2D = 2, VIEW_DP = 3; + + private MutexButtonPanel viewControlBar; + private JButton btnShow2D, btnShowDotplot, btnShowCircle; + private JPanel controlPanel, cardPanel; + private JSplitPane splitPane; + + private HelpBar helpBar; + + private MapLeft mapper; + private SyMAP2d symap2D = null; + private DotPlotFrame dotplot = null; + private CircFrame circframe = null; + private DBconn2 tdbc2, circdbc=null; + + private int selectedView = 1; + private int screenWidth, screenHeight; + + private ChrInfo[] lastSelectedTracks=null; // for 2d so not to recreate if same + private ChrInfo lastRef=null; + + // called by symap.frame.ChrExpInit + protected ChrExpFrame(String title, DBconn2 tdbc2, MapLeft mapper) { + super(title); + this.tdbc2 = tdbc2; + this.mapper = mapper; + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + Rectangle screenRect = Jcomp.getScreenBounds(this); + screenWidth = Math.min(MIN_WIDTH, screenRect.width); + screenHeight = Math.min(MIN_HEIGHT, screenRect.height); + setSize(screenWidth, screenHeight); + setLocationRelativeTo(null); + + // Using a card layout to switch views between 2D, Circle, Dotplot + cardPanel = new JPanel(); + cardPanel.setLayout( new CardLayout() ); + + // Create split pane for Control Panel + splitPane = new MySplitPane(JSplitPane.HORIZONTAL_SPLIT); + splitPane.setContinuousLayout(true); // picture redraws continuously + splitPane.setDividerLocation(screenWidth * 1/4); // behaves best using this instead of fix width + splitPane.setBorder(null); + splitPane.setRightComponent(cardPanel); + + setLayout(new BorderLayout()); + add(splitPane, BorderLayout.CENTER); + + helpBar = new HelpBar(425, 130); + helpBar.setBorder( BorderFactory.createLineBorder(Color.LIGHT_GRAY) ); + + createControlPanel(); // adds to Left side of splitPane; + showCircleView(); // adds to cardPanel, which is on Right side + } + + public void dispose() { // override + setVisible(false); + tdbc2.close(); + if (circframe!=null) circframe.clear(); + circframe=null; + + if (symap2D != null) symap2D.clear(); + symap2D = null; + if (dotplot != null) dotplot.clear(); + dotplot = null; + super.dispose(); + } + + private JPanel createViewControlBar() { + viewControlBar = new MutexButtonPanel(""Views:"", 5); + viewControlBar.setAlignmentX(Component.LEFT_ALIGNMENT); + viewControlBar.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createEtchedBorder(), + BorderFactory.createEmptyBorder(5, 5, 5, 5))); + + btnShowCircle = new JButton(""Circle""); + btnShowCircle.setEnabled(true); + btnShowCircle.setSelected(true); + btnShowCircle.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Jcomp.setCursorBusy(getContentPane(), true); + showCircleView(); + selectedView = viewControlBar.getSelected(); + Jcomp.setCursorBusy(getContentPane(), false); + } + }); + viewControlBar.addButton(btnShowCircle); + helpBar.addHelpListener(btnShowCircle, new HelpListener() { + public String getHelpText(MouseEvent e) { + return ""Show Circle View: Click this button to switch to the circle view.""; + } + }); + + btnShow2D = new JButton(""2D""); + btnShow2D.setEnabled(false); + btnShow2D.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Jcomp.setCursorBusy(getContentPane(), true); + boolean success = show2DView(); + if (success) + selectedView = viewControlBar.getSelected(); + else { // revert to previous view + viewControlBar.setSelected(selectedView); + viewControlBar.getSelectedButton().setEnabled(true); + } + Jcomp.setCursorBusy(getContentPane(), false); + } + }); + + viewControlBar.addButton(btnShow2D); + helpBar.addHelpListener(btnShow2D, new HelpListener() { + public String getHelpText(MouseEvent e) { + return ""Show 2D View: Click this button to switch to the 2D view.""; + } + }); + + btnShowDotplot = new JButton(""Dot Plot""); + btnShowDotplot.setEnabled(false); + btnShowDotplot.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Jcomp.setCursorBusy(getContentPane(), true); + showDotplotView(); + selectedView = viewControlBar.getSelected(); + Jcomp.setCursorBusy(getContentPane(), false); + } + }); + viewControlBar.addButton(btnShowDotplot); + helpBar.addHelpListener(btnShowDotplot, new HelpListener() { + public String getHelpText(MouseEvent e) { + return ""Show Dotplot View: Click this button to switch to the Dotplot view.""; + } + }); + + return viewControlBar; + } + + private ActionListener projectChange = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (mapper.hasChanged()) { + controlPanel.repaint();// Repaint project panels + + // Regenerate main display + btnShow2D.setEnabled( mapper.getNumVisibleChrs() > 0 ); + btnShowDotplot.setEnabled( mapper.getNumVisibleChrs() > 0 ); + btnShowCircle.setEnabled( true ); + + if (viewControlBar.getSelected() == VIEW_CIRC) showCircleView(); + } + } + }; + + private void createControlPanel() { + // Create project graphical menus + JPanel projPanel = new JPanel(); + projPanel.setLayout(new BoxLayout(projPanel, BoxLayout.Y_AXIS)); + + Mproject[] projects = mapper.getProjects(); + + // First figure out which groups have synteny in this set + TreeSet grpIdxWithSynteny = new TreeSet(); + for (Mproject p : projects) { + Block[] blks = mapper.getBlocksForProject(p.getID()); + for (Block blk : blks) { + grpIdxWithSynteny.add(blk.getGroup1Idx()); + grpIdxWithSynteny.add(blk.getGroup2Idx()); + } + } + + for (Mproject p : projects) { + ProjIcons pd = new ProjIcons(mapper, p, projectChange, grpIdxWithSynteny); + helpBar.addHelpListener(pd,this); + + CollapsiblePanel cp = new CollapsiblePanel(p.getDisplayName(), null, false); + cp.add(pd); + cp.expand(); + + projPanel.add(cp); + } + + // Create instructions panel + LinkLabel infoLink = new LinkLabel(""Click for online help""); + infoLink.setFont(new Font(infoLink.getFont().getName(), Font.PLAIN, infoLink.getFont().getSize())); + infoLink.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Jcomp.setCursorBusy(ChrExpFrame.this, true); + if ( !Jhtml.tryOpenURL(Jhtml.USER_GUIDE_URL) ) + System.err.println(""Error opening URL: "" + Jhtml.USER_GUIDE_URL); + Jcomp.setCursorBusy(ChrExpFrame.this, false); + } + }); + + CollapsiblePanel infoCollapsiblePanel = new CollapsiblePanel(""Information"", null, false); + infoCollapsiblePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); + infoCollapsiblePanel.add( helpBar ); + infoCollapsiblePanel.add( infoLink ); + infoCollapsiblePanel.expand(); + + // Setup top-level panel + controlPanel = new JPanel(); + controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS)); + controlPanel.setBorder( BorderFactory.createEmptyBorder(0, 5, 0, 0) ); + controlPanel.add( projPanel ); + controlPanel.add( infoCollapsiblePanel ); controlPanel.add( Box.createVerticalStrut(20) ); + controlPanel.add( createViewControlBar() ); controlPanel.add( Box.createVerticalStrut(10) ); + controlPanel.add( Box.createVerticalGlue() ); + + splitPane.setLeftComponent(controlPanel); + } + /////////////////////////////////////////////////////////////////// + private void showCircleView(){ + double [] lastParams = (circframe!=null) ? circframe.getLastParams() : null; // reuse settings + + int[] pidxList = new int[mapper.getProjects().length]; + TreeSet shownGroups = new TreeSet(); + boolean hasSelf = false; // do not show self-align is this is none + + int refIdx=-1; // have priority colors + for (int i = 0; i < mapper.getProjects().length; i++){ + Mproject pg = mapper.getProjects()[i]; + int pid = pg.getID(); + pidxList[i] = pid; + + if (pg.hasSelf()) hasSelf=true; + + for (ChrInfo t : mapper.getChrs(pid)){ + if (t.isVisible() || mapper.getRefChr() == t) { + shownGroups.add(t.getGroupIdx()); + if (mapper.getRefChr() == t) refIdx=pid; + } + } + } + if (circdbc==null) circdbc = new DBconn2(""CircleE-"" + DBconn2.getNumConn(), tdbc2); + + circframe = new CircFrame(circdbc, pidxList, shownGroups, helpBar, refIdx, hasSelf, lastParams); // have to recreate everytime + + cardPanel.add(circframe.getContentPane(), Integer.toString(VIEW_CIRC)); // ok to add more than once + ((CardLayout)cardPanel.getLayout()).show(cardPanel, Integer.toString(VIEW_CIRC)); + } + /////////////////////////////////////////////////////////////////// + private void showDotplotView() { + // Get selected projects/groups + int[] projects = mapper.getVisibleProjectIDs(); + int[] groups = mapper.getVisibleGroupIDs(); + + // Split into x and y groups + int[] xGroups = new int[] { groups[0] }; + int[] yGroups = new int[groups.length-1]; + for (int i = 1; i < groups.length; i++) + yGroups[i-1] = groups[i]; + + // Create dotplot frame + if (dotplot == null) dotplot = new DotPlotFrame("""", tdbc2, projects, xGroups, yGroups, helpBar, false); + else dotplot.getData().initialize(projects, xGroups, yGroups); + + // Switch to dotplot display + cardPanel.add(dotplot.getContentPane(), Integer.toString(VIEW_DP)); // ok to add more than once + ((CardLayout)cardPanel.getLayout()).show(cardPanel, Integer.toString(VIEW_DP)); + } + /////////////////////////////////////////////////////////////////////////////// + private boolean show2DView() { + try { + ChrInfo ref = mapper.getRefChr(); + ChrInfo[] selectedTracks = mapper.getVisibleChrs(); // no reference tracks + + if (selectedTracks.length > 4 && + JOptionPane.showConfirmDialog(null,""This view may take a while to load and/or cause SyMAP to run out of memory, try anyway?"",""Warning"", + JOptionPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE) != JOptionPane.YES_OPTION) + return false; + + DrawingPanel dp; + boolean noRedo= (lastRef!=null && ref == lastRef && selectedTracks.length==lastSelectedTracks.length); + if (noRedo) { // do not redo if exact same, otherwise, totally redo + for (int i=0; i 0) constraints.insets = new Insets(0, 0, 0, pad); + + JLabel label = new JLabel(title); + label.setFont(label.getFont().deriveFont(Font.PLAIN)); + ((GridBagLayout)getLayout()).setConstraints(label, constraints); + add(label); + label.setMinimumSize(label.getPreferredSize()); + } + + private void addButton(JButton button) { + button.setMargin(new Insets(0, 0, 0, 0)); + button.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); + button.addActionListener(this); + if (getComponentCount() == 1) // select first button + setSelected(button); + + ((GridBagLayout)getLayout()).setConstraints(button, constraints); + add(button); + + setMaximumSize(getPreferredSize()); + } + + private JButton getSelectedButton() { + Component[] comps = getComponents(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof JButton) { + JButton b = (JButton)comps[i]; + if (b.isSelected()) + return b; + } + } + return null; + } + + private int getSelected() { + Component[] comps = getComponents(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof JButton) { + JButton b = (JButton)comps[i]; + if (b.isSelected()){ + return i; + } + } + } + return -1; + } + + private void setSelected(int n) { + Component c = getComponent(n); + if (c != null && c instanceof JButton) + setSelected((JButton)c); + } + + private void setSelected(JButton button) { + for (Component c : getComponents()) {// De-select all buttons + if (c instanceof JButton) { + JButton b = (JButton)c; + b.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); + b.setSelected(false); + b.setEnabled(true); + } + } + + if (btnShow2D != null) btnShow2D.setEnabled( mapper.getNumVisibleChrs() > 0 ); + if (btnShowDotplot != null) btnShowDotplot.setEnabled( mapper.getNumVisibleChrs() > 0 ); + if (btnShowCircle != null) btnShowCircle.setEnabled(true); // if click blocks on right, can reduce tracks + + button.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); + button.setSelected(true); + button.setEnabled(false); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() != null && e.getSource() instanceof JButton) + setSelected((JButton)e.getSource()); + } + } + + private class MySplitPane extends JSplitPane { + private static final long serialVersionUID = 1L; + + public MySplitPane(int newOrientation) { + super(newOrientation); + } + } + + public String getHelpText(MouseEvent e) { + Object o = e.getSource(); + + if (o instanceof ProjIcons) + return ""Click a chromosome to add/remove it from the scene.\n"" + + ""Click the chromosome number to make it the reference.\n""; + + return null; + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/Ruler.java",".java","5705","183","package symap.closeup; + +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.Color; +import java.awt.Font; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import java.awt.geom.Dimension2D; +import javax.swing.SwingUtilities; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; + +/*********************************************** + * Called by CloseUpComponent + */ +public class Ruler { + private static final double TICK_TEXT_OFFSET = 5; + + private Dimension2D rDim, lDim, tDim; + private double tickSpace; + + private double lineThickness; + private int start, end; + private boolean tickText; + + private ArrowLine arrowLine = new ArrowLine(); + private Rectangle2D.Double bounds = new Rectangle2D.Double(); + private double[] points = new double[0]; + + protected Ruler(Dimension2D lArrowDim, Dimension2D rArrowDim, Dimension2D tickDim, + boolean showTickText, double tickSpace, double lineThickness) { //, int orientation) { + setRuler(0,0,lArrowDim,rArrowDim,tickDim,showTickText,tickSpace,lineThickness);//,orientation); + } + + protected void paint(Graphics2D g2, Color rulerColor, Color fontColor, Font font) { + if (rulerColor != null) g2.setPaint(rulerColor); + g2.draw(arrowLine); + g2.fill(arrowLine); + + if (points.length > 0) { + if (tDim != null) { + Rectangle2D.Double tick = new Rectangle2D.Double(); + tick.width = tDim.getWidth(); + tick.height = tDim.getHeight(); + tick.y = arrowLine.getBounds().getY() + (arrowLine.getBounds().getHeight()-tick.height) / 2.0; + double tickOffset = tick.width/2.0; + for (int i = 0; i < points.length; ++i) { + tick.x = points[i] - tickOffset; + g2.draw(tick); + g2.fill(tick); + } + } + if (tickText) { + AffineTransform saveAt = g2.getTransform(); + g2.setPaint(fontColor); + g2.setFont(font); + double unitPerPixel = getUnitPerPixel(); + FontMetrics fm = g2.getFontMetrics(font); + float fontOffset = (fm.getAscent()+fm.getDescent())/2f; + float y = (float)(arrowLine.getBounds().getY() + arrowLine.getBounds().getHeight() / 2.0 - + (tDim == null ? 0 : tDim.getHeight()/2.0) - TICK_TEXT_OFFSET); + for (int i = 0; i < points.length; ++i) { + g2.rotate(-Math.PI/4.0,(float)points[i],y); + String x = String.format(""%,d"", getUnit(points[i],unitPerPixel)); + g2.drawString(x.toString(),(float)points[i]-fontOffset,y); + g2.setTransform(saveAt); + } + } + } + } + + private int getUnit(double point, double unitPerPixel) { + if (start < end) + return (int)Math.round((point - bounds.x) * unitPerPixel) + start; + else + return end - (int)Math.round((point - bounds.x) * unitPerPixel); + } + + private double[] getPoints(FontMetrics fm) { + List points = new ArrayList(); + if ((tickText && tickSpace > 0) || (tickSpace > 0 && tDim != null && tDim.getWidth() > 0 && tDim.getWidth() > lineThickness)) { + double x = bounds.x + bounds.getWidth()/2.0; + double m = bounds.x + fm.getAscent() + fm.getDescent(); + while (x >= m) { + points.add(x); + x -= tickSpace; + } + m = bounds.x + bounds.getWidth() - fm.getAscent() - fm.getDescent(); + x = bounds.x + bounds.getWidth()/2.0 + tickSpace; + while (x <= m) { + points.add(x); + x += tickSpace; + } + } + double[] ret = new double[points.size()]; + for (int i = 0; i < ret.length; ++i) + ret[i] = (points.get(i)).doubleValue(); + Arrays.sort(ret); + return ret; + } + + protected void setBounds(int start, int end, double x, double y, + double unitsPerPixel, FontMetrics tickFontMetrics) + { + if (tickText && tickFontMetrics == null) + throw new IllegalArgumentException( + ""FontMetrics required in set bounds for a Ruler showing tick text.""); + + this.start = start; + this.end = end; + + bounds.x = x; + bounds.y = y; + + bounds.width = Math.abs(start-end)/unitsPerPixel; + bounds.height = getHeight(Math.max(start,end),tickFontMetrics); + + + if (bounds.width < 300) + bounds.width = 300; + + Rectangle2D.Double lineRect = new Rectangle2D.Double(); + lineRect.x = bounds.x; + lineRect.width = bounds.width; + lineRect.height = getLineHeight(); + lineRect.y = bounds.y + bounds.height - lineRect.height; + + arrowLine.setBounds(lineRect,lineThickness,lDim,rDim); + + points = getPoints(tickFontMetrics); + } + + protected Rectangle2D getBounds() { + return bounds; + } + + protected void setRuler(int start, int end, Dimension2D lDim, Dimension2D rDim, Dimension2D tDim, + boolean tickText, double tickSpace, double lineThickness) { //, int orientation) { + this.start = start; + this.end = end; + this.lDim = lDim; + this.rDim = rDim; + this.tDim = tDim; + this.tickText = tickText; + this.tickSpace = tickSpace; + this.lineThickness = lineThickness; + } + + private double getHeight(int maxNumber, FontMetrics fm) { + double maxLineHeight = getLineHeight(); + double maxStringWidth = getMaxStringWidth(maxNumber,fm); + if (!tickText) return maxLineHeight; + return Math.max(maxLineHeight,maxStringWidth+ + TICK_TEXT_OFFSET+(tDim == null ? 0 : (tDim.getHeight()+maxLineHeight)/2.0)); + } + + private double getMaxStringWidth(int maxNumber, FontMetrics fm) { + if (!tickText) return 0; + int max = 0; + int stop = Math.max(0,maxNumber - 100); + for (; maxNumber >= stop; --maxNumber) { + String x = String.format(""%d"", maxNumber); + max = Math.max(SwingUtilities.computeStringWidth(fm,x),max); + } + return max; + } + + private double getLineHeight() { + double max = lineThickness; + if (lDim != null) max = Math.max(max,lDim.getHeight()); + if (rDim != null) max = Math.max(max,rDim.getHeight()); + if (tDim != null) max = Math.max(max,tDim.getHeight()); + return max; + } + + private double getUnitPerPixel() { + return Math.abs(end-start)/bounds.width; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/HitAlignment.java",".java","10710","298","package symap.closeup; + +import java.awt.BasicStroke; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics2D; +import java.awt.geom.AffineTransform; +import java.awt.geom.Dimension2D; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; +import javax.swing.Icon; +import java.awt.geom.Point2D; + +import symap.mapper.HitData; + +/**************************************************** + * Display Hit Alignments; created in AlignPool; drawn from CloseUpComponent + */ +public class HitAlignment implements Comparable { + public static final String tokS="" "", tokO="" ""; + private final String tokpS="" "", tokpO="" ""; + private final boolean drawLine=false; + + private HitData hitDataObj; + private String proj1, proj2; + private int sStart, sEnd, oStart, oEnd; // non-aligned ends + private int alignWidth, startOffset; + private SeqData otherData, selectData, matchData; // aligned sequences + private String scoreStr, numSubHit=""""; + + private double[] misses, inserts, deletes; + private boolean selected; + private ArrowLine hitLine; + private Rectangle2D.Double bounds; + private int layer; + + protected HitAlignment(HitData hd, String proj1, String proj2, + SeqData selectAlign, SeqData otherAlign, SeqData match, + int selectStart, int selectEnd, int otherStart, int otherEnd, + int fullAlignWidth, int offset, String scoreStr, String numSubHit) + { + this.hitDataObj = hd; + this.proj1 = proj1; + this.proj2 = proj2; + this.sStart = selectStart; + this.sEnd = selectEnd; + this.oStart = otherStart; + this.oEnd = otherEnd; + this.alignWidth = fullAlignWidth; + this.selectData = selectAlign; + this.otherData = otherAlign; + this.matchData = match; + this.startOffset = offset; + this.scoreStr = scoreStr; + this.numSubHit = numSubHit; + layer = 1; + + // these calculate where to put marks along the hit line of graphics + misses = SeqData.getQueryMisses(selectAlign, otherAlign); + inserts = SeqData.getQueryInserts(selectAlign, otherAlign); + deletes = SeqData.getQueryDeletes(selectAlign, otherAlign); + selected = false; + } + // for reverse text alignments + protected HitAlignment(HitAlignment ha, + SeqData selectAlign, SeqData otherAlign, SeqData match, + int selectStart, int selectEnd, int otherStart, int otherEnd, + int fullAlignWidth, int offset, String scoreStr) + { + this.hitDataObj = ha.hitDataObj; + this.proj1 = ha.proj1; + this.proj2 = ha.proj2; + this.sStart = selectStart; + this.sEnd = selectEnd; + this.oStart = otherStart; + this.oEnd = otherEnd; + this.alignWidth = fullAlignWidth; + this.selectData = selectAlign; + this.otherData = otherAlign; + this.matchData = match; + this.startOffset = offset; + this.scoreStr = scoreStr; + this.numSubHit = ha.numSubHit; + layer = 1; + } + + // for TextPopup and closeup + protected String toText(boolean isClose, String p1, String p2) { + String sSeq = selectData.toString(), nSeq = otherData.toString(); + String mSeq = matchData.toString(); + + String sCoord = SeqData.coordsStr(selectData.getStrand(), sStart, sEnd); + String nCoord = SeqData.coordsStr(otherData.getStrand(), oStart, oEnd); + String hitN = hitDataObj.getName() + ""."" + numSubHit; + + if (isClose) { + int max = Math.max(p2.length(), p1.length())+1; + String format = ""%-"" + max + ""s ""; + + String desc = String.format(format, hitN) + scoreStr; + String sName = String.format(format, p1); + String nName = String.format(format, p2); + + return ""\n "" + desc + + ""\n "" + sName + sCoord + + ""\n "" + nName + nCoord + ""\n"" + + ""\n "" + sSeq + + ""\n "" + mSeq + + ""\n "" + nSeq + "" \n""; + } + else { // the text formatter puts the S and N before each align name + String sName = String.format(""%s"", p1 + tokpS); + String nName = String.format(""%s"", p2 + tokpO); + return (hitN + "" "" + scoreStr) + ""\t"" + sName + sCoord + "" "" + nName + nCoord + + ""\t"" + sSeq + ""\t"" + mSeq + ""\t"" + nSeq; + } + } + + protected String toTextAA(String p1, String p2) { + String qd = selectData.toString(), td = otherData.toString(); + String mk = matchData.toString(); + + String qn = p1 + tokpS; + String tn = p2 + tokpO; + + String qc = SeqData.coordsStr(sStart, sEnd); + String tc = SeqData.coordsStr(oStart, oEnd); + + String desc = hitDataObj.getName() + ""."" + numSubHit; + + return desc + ""\t"" + qn + qc + "" ""+ tn + tc + ""\t"" + qd + ""\t"" + mk + ""\t"" + td; + } + // for TextShowInfo + protected int [] getCoords( ) { + int [] coords = new int[4]; + coords[0]=sStart+startOffset; + coords[1]=sEnd; + coords[2]=oStart+startOffset; + coords[3]=oEnd; + return coords; + } + /*******************************************************************/ + protected void setBounds(int startBP, double pixelStart, double bpPerPixel, double y) { + setBounds( getX(startBP, pixelStart, bpPerPixel), y, bpPerPixel ); + } + private void setBounds(double x, double y, double bpPerPixel) { + if (bounds == null) { + hitLine = new ArrowLine(); + bounds = new Rectangle2D.Double(); + bounds.height = CloseUpComponent.HIT_HEIGHT; + } + bounds.y = y; + bounds.x = x; + bounds.width = alignWidth / bpPerPixel; + + hitLine.setBounds(bounds, CloseUpComponent.LINE_HEIGHT, CloseUpComponent.ARROW_DIM,ArrowLine.NO_ARROW); + } + + protected void paintLine (Graphics2D g2, double bpPerPixel, int startBP, int pixelStart) { + if (drawLine) { + double x1 = getX(startBP, pixelStart, bpPerPixel); + double x2 = alignWidth/bpPerPixel; + Rectangle2D dotLine = new Rectangle2D.Double(x1, bounds.y, x2, 1); + BasicStroke saveStroke = (BasicStroke) g2.getStroke(); + + g2.setColor(Color.gray); + g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {2f}, 0f)); + g2.draw(dotLine); + g2.setStroke(saveStroke); + } + } + + protected void paintName(Graphics2D g2, FontMetrics fm, Color fontColor, double vertSpace, double bpPerPixel) { + String m = hitDataObj.getName().replace(""Hit "", """"); + String n = m + ""."" + numSubHit.substring(0, numSubHit.indexOf(""/"")); + double w = alignWidth/bpPerPixel; + double x = bounds.x + (w - fm.stringWidth(n)) / 2.0; + double y = bounds.y - vertSpace; + g2.setPaint(fontColor); + g2.setFont(fm.getFont()); + g2.drawString(n,(float)x,(float)y); + } + + protected void paint(Graphics2D g2) { + Color c = CloseUpComponent.hitColor; + if (!selected) g2.setPaint(c); + else g2.setPaint(c.brighter()); + + g2.draw(hitLine); + g2.fill(hitLine); + + double startOffsetWidth = 0; + double endOffsetWidth = 0; + Rectangle2D hb = hitLine.getBounds(); + double hbWidth = hb.getWidth() - startOffsetWidth - endOffsetWidth; + double hbX = hb.getX() + startOffsetWidth; + Line2D.Double line = new Line2D.Double(); + + line.y1 = hb.getY()+ ( (hb.getHeight() - CloseUpComponent.MISS_HEIGHT) / 2.0 ); + line.y2 = line.y1 + CloseUpComponent.MISS_HEIGHT; + if (!selected) g2.setPaint(CloseUpComponent.missColor.darker()); + else g2.setPaint(CloseUpComponent.missColor); + for (int i = 0; i < misses.length; i++) { + line.x1 = line.x2 = misses[i] * hbWidth + hbX; + g2.draw(line); + } + + line.y1 = hb.getY() + ( (hb.getHeight() - CloseUpComponent.DELETE_HEIGHT) / 2.0 ); + line.y2 = line.y1 + CloseUpComponent.DELETE_HEIGHT; + if (!selected) g2.setPaint(CloseUpComponent.deleteColor.darker()); + else g2.setPaint(CloseUpComponent.deleteColor); + for (int i = 0; i < deletes.length; i++) { + line.x1 = line.x2 = deletes[i] * hbWidth + hbX; + g2.draw(line); + } + + double xOffset = hbX - CloseUpComponent.INSERT_DIM.width/2.0; + InsIcon arrow = new InsIcon(CloseUpComponent.INSERT_DIM); + line.y1 = hb.getY() + (hb.getHeight()/2.0) - CloseUpComponent.INSERT_OFFSET - CloseUpComponent.INSERT_DIM.height; + if (!selected) g2.setPaint(CloseUpComponent.insertColor.darker()); + else g2.setPaint(CloseUpComponent.insertColor); + for (int i = 0; i < inserts.length; i++) { + line.x1 = inserts[i] * hbWidth + xOffset; + arrow.paint(g2,line.x1,line.y1,InsIcon.POINT_DOWN); + } + } + // Get starting x of the arrowed line. + private double getX(int startBP, double pixelStart, double bpPerPixel) { + return (getMinSelectCoord()-startBP) / bpPerPixel + pixelStart; + } + private long getID() {return hitDataObj.getID(); } + private int getMinSelectCoord () {return (sStart < sEnd) ? sStart+startOffset : sEnd+startOffset; } + + // CloseUpComponent + protected int getWidthAlign () {return alignWidth; } + protected void setLayer (int layer) {this.layer = layer + 1; } + protected int getLayer () {return this.layer; } + protected boolean contains(Point2D p) {return bounds.contains(p); } + + // CloseUpDialog + protected void setSelected (boolean status) {this.selected = status; } + protected int getAend() {return sStart + alignWidth; } + + // AlignPool.alignSubHitRev, CloseUpComponent.assignHitLayers, CloseUpDialog.setvView, HitAlignment.compareTo + protected int getSstart() {return sStart; } + protected int getSend() {return sEnd; } + + // AlignPool.alignSubHitRev + protected int getOstart() {return oStart; } + protected int getOend() {return oEnd; } + protected String getSelectSeq() {return selectData.getSeq();} + protected String getOtherSeq() {return otherData.getSeq();} + protected char getSelectStrand() {return selectData.getStrand();} + protected char getOtherStrand() {return otherData.getStrand();} + protected String getSubHitName() {return hitDataObj.getName() + ""."" + numSubHit;} + + public boolean equals(Object obj) { + return obj instanceof HitAlignment && ((HitAlignment)obj).getID() == getID(); + } + public int compareTo(HitAlignment ha) { + return getSstart() - ha.getSend(); + } + public String toString() {return toText(true, proj1, proj2); } + + /**************************************************************** + * Insert Icon; Arrow down + */ + public class InsIcon implements Icon { + public static final double POINT_DOWN = 0; + private Dimension2D dim; + private Line2D line = new Line2D.Double(); + + public InsIcon(Dimension2D dim) {this.dim = dim;} + + public int getIconHeight() {return (int)dim.getHeight();} + + public int getIconWidth() {return (int)dim.getWidth();} + + public void paintIcon(Component c, Graphics g, int x, int y) { + paint((Graphics2D)g,(double)x,(double)y, POINT_DOWN); + } + public void paint(Graphics2D g2, double x, double y, double direction) { + AffineTransform saveAt = g2.getTransform(); + + g2.rotate(direction,x+dim.getWidth()/2.0,y+dim.getHeight()/2.0); + + line.setLine(x,y,x + dim.getWidth()/2.0,y+dim.getHeight()); + g2.draw(line); + line.setLine(line.getX2(),line.getY2(),x+dim.getWidth(),y); + g2.draw(line); + + g2.setTransform(saveAt); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/CloseUpComponent.java",".java","8521","257","package symap.closeup; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Point; +import java.awt.Graphics; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.FontMetrics; +import java.awt.geom.Dimension2D; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.JComponent; + +import props.PropertiesReader; +import symap.drawingpanel.SyMAP2d; + +import java.util.Vector; +import java.util.Arrays; +import java.util.TreeMap; + +/*************************************************************** + * Displays the graphical portion of the Closeup Align + */ +public class CloseUpComponent extends JComponent { + private static final long serialVersionUID = 1L; + + private HitAlignment[] hitAlign; + private GeneAlignment[] geneAlign; + private int startGr, endGr; // start and end of graphics + private Ruler ruler; + private Vector listeners; + + /****************************************************** + * XXX + */ + protected CloseUpComponent() { + super(); + setBackground(backgroundColor); + listeners = new Vector(); + addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + notifyListenersOfClick(getHitAlignment(e.getPoint())); + } + }); + ruler = new Ruler(RULER_ARROW_DIM, RULER_ARROW_DIM, RULER_TICK_DIM, + true, RULER_TICK_SPACE, RULER_LINE_THICKNESS); + } + + public void paintComponent(Graphics g) { + super.paintComponent(g); + if (geneAlign == null || hitAlign == null) return; // will have 0 length if no genes + + double bpPerPixel = 1; + + Graphics2D g2 = (Graphics2D) g; + ruler.paint(g2, rulerColor, rulerFontColor, rulerFont); + FontMetrics fm = getFontMetrics(hitFont); + + // Paint the hit segments + for (int i = 0; i < hitAlign.length; ++i) { + hitAlign[i].paintName(g2, fm, hitFontColor, FONT_SPACE, bpPerPixel); + hitAlign[i].paintLine(g2, bpPerPixel, startGr, HORZ_BORDER); + hitAlign[i].paint(g2); + } + + // Paint the genes + fm = getFontMetrics(geneFont); + for (int i = 0; i < geneAlign.length; ++i) + geneAlign[i].paint(g2, fm, geneFontColor, FONT_SPACE); + } + public void setPreferredSize(Dimension d) { + setPreferredSize(d.width); + } + /****************************************************************************/ + + private void setPreferredSize(double width) { + double grLen = Math.abs(endGr - startGr) + 1; + + double lenBP = grLen/(width-2 * HORZ_BORDER); + + double bpPerPixel = Math.max(1, lenBP); + + ruler.setBounds(startGr, endGr, HORZ_BORDER, VERT_BORDER, bpPerPixel, getFontMetrics(rulerFont)); + + // height + double ht = ruler.getBounds().getX() + ruler.getBounds().getHeight()+ RULER_OFFSET; + ht = buildHitLayers(ht, bpPerPixel); + if (geneAlign!=null) + ht = buildGeneLayers(ht, bpPerPixel); + + Dimension d = new Dimension(); + d.width = (int) Math.ceil(grLen/bpPerPixel + 2*HORZ_BORDER); + d.height = (int) Math.ceil(ht + VERT_BORDER); + + super.setPreferredSize(d); + } + + private double buildGeneLayers(double y, double bpPerPixel) { + int [] layers = assignGeneLayers(bpPerPixel); + + double layerSize = GENE_HEIGHT + VERT_GENE_SPACE + getFontHeight(geneFont) + FONT_SPACE; + int max = -1; + + for (int i = 0; i < geneAlign.length; ++i) { + if (layers[i] > max) max = layers[i]; + + geneAlign[i].setBounds(startGr, endGr, HORZ_BORDER, bpPerPixel, layers[i] * layerSize + y); + } + return ((max + 1) * layerSize) + y; + } + + private int[] assignGeneLayers(double bpPerPixel) { + if (geneAlign == null || geneAlign.length == 0) return new int[0]; + + int[] layers = new int[geneAlign.length]; + double[] ends = new double[geneAlign.length]; + Arrays.fill(layers, -1); + Arrays.fill(ends, Double.NEGATIVE_INFINITY); + + for (int i = 0; i < geneAlign.length; ++i) { + double x = geneAlign[i].getX(startGr, 0, bpPerPixel); + for (int j = 0; j < ends.length; ++j) { + if (ends[j] <= x || ends[j] < 0) { + layers[i] = j; + break; + } + } + ends[layers[i]] = x + geneAlign[i].getWidth(bpPerPixel, startGr, endGr) + HORZ_GENE_SPACE; + } + return layers; + } + + private double buildHitLayers(double y, double bpPerPixel) { + final double layerHeight = HIT_HEIGHT + VERT_HIT_SPACE + getFontHeight(hitFont) + FONT_SPACE; + + int numLayers = assignHitLayers(); + + for (HitAlignment h : hitAlign) + h.setBounds(startGr, HORZ_BORDER, bpPerPixel, h.getLayer() * layerHeight + y); + + return ((numLayers + 1) * layerHeight) + y; + } + + // layer 1 is the lower layer, and layer 0 is upper; has to have 2 layers + private int assignHitLayers() { + if (hitAlign == null || hitAlign.length == 0) return 0; + + int layerNum=1, lastEnd=0, lastLayer=0, maxLayer=2; + + // sort on start + TreeMap hitOrd = new TreeMap (); + for (HitAlignment haObj : hitAlign) { + hitOrd.put(haObj.getSstart(), haObj); + } + for (int start : hitOrd.keySet()) { + HitAlignment haObj = hitOrd.get(start); + int end = haObj.getSend(); + end = start + haObj.getWidthAlign(); + + if (start>lastEnd) layerNum=1; + else { + if (lastLayer==1) layerNum=0; + else layerNum=1; + } + lastEnd = end+10; + lastLayer = layerNum; + + haObj.setLayer(layerNum); + } + return maxLayer; + } + + private HitAlignment getHitAlignment(Point p) { + if (hitAlign != null) { + for (HitAlignment h : hitAlign) + if (h.contains(p)) + return h; + } + return null; + } + private void notifyListenersOfClick(HitAlignment h) { + if (h != null) + for (int i = 0; i < listeners.size(); ++i) + ((CloseUpDialog) listeners.get(i)).hitClicked(h); + } + private double getFontHeight(Font font) { + return (double) getFontMetrics(font).getHeight() + FONT_SPACE; + } + + + protected void addCloseUpListener(CloseUpDialog cl) {if (!listeners.contains(cl))listeners.add(cl);} + + // start = min(start_exon, start_subhit), end=max(end_exon, end_subhit) + protected void setData(int startG, int endG, GeneAlignment[] ga, HitAlignment[] ha) { + this.startGr = startG; + this.endGr = endG; + this.geneAlign = ga; + this.hitAlign = ha; + + if (this.geneAlign != null) Arrays.sort(this.geneAlign); + if (this.hitAlign != null) Arrays.sort(this.hitAlign); + + setPreferredSize(getWidth()); + } + + protected int getNumberOfHits() { return (hitAlign == null ? 0 : hitAlign.length); } + + + /********************************************************************************/ + private static Color rulerFontColor= new Color(0,0,0); + private static Color hitFontColor = Color.black, geneFontColor=Color.black; + + private static Font rulerFont = new Font(""Courier"",0,14); + private static Font hitFont = new Font(""Arial"",0,12); + private static Font geneFont = new Font(""Arial"",0,12); + private static final double VERT_HIT_SPACE=2; + private static final double VERT_GENE_SPACE=5, HORZ_GENE_SPACE=8; + private static final int VERT_BORDER=12, HORZ_BORDER=15; + private static final double RULER_TICK_SPACE=60, RULER_LINE_THICKNESS=3, RULER_OFFSET=12; + private static final double FONT_SPACE = 3; + + // HitAlignment + public static final double LINE_HEIGHT=2; + public static final double MISS_HEIGHT=9, DELETE_HEIGHT=9; + public static final DoubleDimension INSERT_DIM = new DoubleDimension(6,6); + public static final double INSERT_OFFSET=5; + public static final DoubleDimension ARROW_DIM = new DoubleDimension(9,15); + public static final double HIT_HEIGHT = 15; + + // Gene Alignment + public static final DoubleDimension GARROW_DIM = new DoubleDimension(10,15); //w,h + public static final double EXON_HEIGHT=12, INTRON_HEIGHT=2; + private static final double GENE_HEIGHT = Math.max(EXON_HEIGHT, INTRON_HEIGHT); + + private static final Dimension2D RULER_ARROW_DIM = new Dimension(10,15); // w,h + private static final Dimension2D RULER_TICK_DIM = new Dimension(2,9); + + // Set by user in color wheel; defaults in closeup.properties + public static Color backgroundColor, rulerColor, hitColor; + public static Color missColor, deleteColor, insertColor; + public static Color intronColor, exonColorP, exonColorN; + + static { + PropertiesReader props = new PropertiesReader(SyMAP2d.class.getResource(""/properties/closeup.properties"")); + backgroundColor = props.getColor(""backgroundColor""); + rulerColor = props.getColor(""rulerColor""); + hitColor = props.getColor(""hitColor""); + missColor = props.getColor(""missColor""); + deleteColor = props.getColor(""deleteColor""); + insertColor = props.getColor(""insertColor""); + exonColorP = props.getColor(""exonColorP""); + exonColorN = props.getColor(""exonColorN""); + intronColor = props.getColor(""intronColor""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/SeqDataInfo.java",".java","15530","452","package symap.closeup; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Vector; + +import symap.Globals; +import symap.sequence.Annotation; +import util.ErrorReport; + +/******************************************************* + * Create sequence information associated with TextShowInfo + */ +public class SeqDataInfo { + + // format exon list (e.g. Exon #1:20:50,Exon #1:20:50) + static public String formatExon(String exonList) { + String exonTag = Globals.exonTag; + int rm = exonTag.length(); + String list=""""; + String [] exons = exonList.split("",""); + int dist=0, last=0; + + String exCol = Globals.exonTag.substring(0, Globals.exonTag.indexOf("" "")); + String [] fields = {""#"", exCol + "" Coords"",""Exon"", ""Intron""}; + int [] justify = {1, 0, 0, 0}; + int nRow = exons.length; + int nCol= fields.length; + String [][] rows = new String[nRow][nCol]; + int r=0, c=0; + + int x1, x2; + for (String x : exons) { + String [] y = x.split("":""); + if (y.length!=3) {System.err.println(""Parsing y: "" + exonList); return exonList;} + + if (!y[0].startsWith(exonTag)) System.err.println(exonList + ""\n"" + y[0]); + String n = y[0].substring(rm); + try { + x1 = Integer.parseInt(y[1]); + x2 = Integer.parseInt(y[2]); + } + catch (Exception e) {System.err.println(""Parsing int: "" + exonList); return exonList;} + + if (x1>x2) System.err.println(""ERROR start>end "" + x1 + "","" + x2); + + rows[r][c++] = n; + rows[r][c++] = String.format(""%,d - %,d"",x1, x2); + rows[r][c++] = String.format(""%,d"",(x2-x1+1)); + + if (last>0) { + dist = Math.abs(last-x1)+1; + rows[r][c] = String.format(""%,d"",dist); + } + else rows[r][c] = ""-""; + last = x2; + + r++; c=0; + } + list = util.Utilities.makeTable(nCol, nRow, fields, justify, rows); + return list; + } + /************************************************************* + * Methods for TextShowInfo for hits + */ + /* Format a clustered hit (e.g. 100:200,300:400); hitListStr is order stored in DB, which is by Q + * aObj - for ExonVec && if -ii gStart and gEnd + * title - merge, order, remove + * bSort - default&Merge yes, target only, sort by start; so # may be out-of-order + * Order&Remove no, keep ordered by #; so numbers may be out-of-order + * isInv - reverse hits; used with !bSort since not sorted and would be displayed wrong order + * always sorted ascending by Q, even if negative strand + */ + static protected int cntMergeNeg=0, cntDisorder; // TextShowInfo access this to determine whether to show Merge + + static protected String formatHit(int X, String name, Annotation aObj, + String hitListStr, String title, boolean bIsInv, boolean bSort) { + + if (hitListStr==null || hitListStr.equals("""")) return ""hitListStr Error""; + + boolean bMerge = title.startsWith(TextShowInfo.titleMerge); + boolean bOrder = title.startsWith(TextShowInfo.titleOrder); + + String colType; + if (bMerge) colType = ""Merged subhits""; + else if (bOrder && X==Globals.T) colType = ""Unsorted subhits""; + else colType = ""Sorted subhits""; + + cntMergeNeg=cntDisorder=0; + Vector exonVec = (aObj!=null) ? aObj.getExonVec() : null; + int s=0, e=0, nOrder=1; + + String [] tokc = hitListStr.split("",""); + ArrayList hitSort = new ArrayList (tokc.length); + + for (String coords : tokc) { + try { + String [] y = coords.split("":""); + s = Integer.parseInt(y[0]); + e = Integer.parseInt(y[1]); + } + catch (Exception err) {System.err.println(""Parsing int: "" + coords); return ""parse error"";} + + hitSort.add(new Hit(nOrder++, s, e)); + } + if (bSort) sortForFormat(hitSort); // target may be out of order; need ordered by start + else if (bIsInv) sortForOrder(hitSort, true); // for inverse order + + int sumTotLen=0, sumTotGap=0, lastE=0, lastS=0; + int lastO = (bIsInv) ? -1 : 1; + + String [] fields = {""#"", colType,""Length"", ""Gap"", """"}; + int [] justify = {1, 0, 0, 0, 1}; + int nRow = tokc.length; + if (bMerge) nRow++; + int nCol= fields.length; + String [][] rows = new String[nRow][nCol]; + + int r=0, c=0, o=0, len=0, gapCol=0; + + for (int i=0; i0) { // gap column + gapCol = Globals.pGap_nOlap(s,e,lastS,lastE); + + rows[r][c++] = String.format(""%,d"",gapCol); + if (gapCol<=0) cntMergeNeg++; + } + else rows[r][c++] = ""-""; + + /* last column */ + String star = "" "";// disorder sign + if (bOrder) { + if (lastS > s) { + star = TextShowInfo.disOrder+TextShowInfo.disOrder; + cntDisorder++; + } + else star = "" ""; + } + else { + int oo = (r>0) ? o-lastO : lastO; + if ((!bIsInv && oo != 1) || (bIsInv && oo != -1)) { + star = TextShowInfo.disOrder; + cntDisorder++; + } + } + + // exon - almost always Y for plants, not so for hsq-pan; Also extend pass gene + String ex = "" ""; + if (Globals.INFO) { + if (exonVec!=null) { + for (Annotation exon : exonVec) { + int olap = Globals.pGap_nOlap(s, e, exon.getStart(), exon.getEnd()); + if (olap<0) { + ex = "" E ""; + break; + } + } + } + // Extend: could have embedded hit, messing up true end, so check all + if (aObj!=null && aObj.getStart() > hitSort.get(i).start) { + ex += String.format("" s %,d"", (aObj.getStart()- hitSort.get(i).start)); + } + if (aObj!=null && aObj.getEnd() < hitSort.get(i).end) + ex += String.format("" e %,d"", ( hitSort.get(i).end - aObj.getEnd())); + } + rows[r][c++] = star + ex; + + r++; c=0; + + lastO = o; lastE = e; lastS = s; + if (bMerge) {sumTotLen+=len; sumTotGap += gapCol;} + } + if (bMerge && tokc.length>1) { + rows[r][c++] = ""--""; + rows[r][c++] = String.format(""%s %,d"",TextShowInfo.totalMerge, sumTotLen+sumTotGap); + rows[r][c++] = String.format(""%,d"",sumTotLen); + rows[r][c++] = String.format(""%,d"",sumTotGap); + rows[r][c++] = ""--""; + r++; + } + + String list = util.Utilities.makeTable(nCol, nRow, fields, justify, rows); + return name + ""\n"" + list; + } + + /************************************************************* + * Merge overlapping hits + * This method is in: + * mapper.HitData: for 2D display where it is not sorted first, which can leave gaps but does not hurt for display + * anchor2.HitPair: where the input is a vector of hits and the output is a merged vector + * This is yet another calculation because the input and output is a string, but the input must be sorted + * so the display does not show gaps so it uses many objects + */ + static protected String calcMergeHits(int X, String subHitStr, boolean isInv) { + try { + if (subHitStr == null || subHitStr.length() == 0) return """"; // uses start,end + + String[] subs = subHitStr.split("",""); + ArrayList subHits = new ArrayList (subs.length); + + int order=1; + for (String st : subs) { + String [] tok = st.split("":""); + int s = Integer.parseInt(tok[0]); + int e = Integer.parseInt(tok[1]); + + subHits.add(new Hit(order++, s,e)); + } + sortForMerge(subHits); // sort by start ascending, end descending + + ArrayList mergeHits = new ArrayList (); + for (Hit sh : subHits) { + boolean found=false; + + for (Hit mh : mergeHits) { + int olap = Globals.pGap_nOlap(sh.start, sh.end, mh.start, mh.end); + if (olap > 0) continue; + + found=true; + if (sh.end>mh.end) mh.end = sh.end; + if (sh.start tHitSort = new ArrayList (tHits.length); + + for (String coords : tHits) { // ordered by query; if isInv, then descending + String [] y = coords.split("":""); + x1 = Integer.parseInt(y[0]); + x2 = Integer.parseInt(y[1]); + + tHitSort.add(new Hit(0, x1, x2)); + } + + StringBuffer sb = new StringBuffer(); + for (int i=tHits.length-1; i>=0; i--) { + Hit ht = tHitSort.get(i); + if (sb.length()==0) sb.append(ht.start + "":"" + ht.end); + else sb.append("","" + ht.start + "":"" + ht.end); + } + return sb.toString(); + } + catch (Exception e) {e.printStackTrace(); return null;} + } + + static protected String [] calcRemoveDisorder(String queryHits, String targetHits, boolean isInv) { + try { + String [] retHits = new String [2]; + + int nOrder=1, x1=0, x2=0; + String [] qHits = queryHits.split("",""); + TreeMap qHitSort = new TreeMap (); + for (String coords : qHits) { // ordered by start + String [] y = coords.split("":""); + x1 = Integer.parseInt(y[0]); + x2 = Integer.parseInt(y[1]); + + qHitSort.put(nOrder, new Hit(nOrder++, x1, x2)); + } + + nOrder=1; + String [] tHits = targetHits.split("",""); + TreeMap tHitSort = new TreeMap (); + for (String coords : tHits) { // ordered by query; if isInv, then descending + String [] y = coords.split("":""); + x1 = Integer.parseInt(y[0]); + x2 = Integer.parseInt(y[1]); + + tHitSort.put(nOrder, new Hit(nOrder++, x1, x2)); + } + + Hit last=null; + for (int order : tHitSort.keySet()) { + Hit ht=tHitSort.get(order); + if (last!=null) { + if (isInv) { + if (last.startht.start) { + qHitSort.get(ht.order).order=0; + ht.order = 0; + } + } + } + last = ht; + } + StringBuffer sb = new StringBuffer(); + for (Hit ht : tHitSort.values()) { + if (ht.order>0) { + if (sb.length()==0) sb.append(ht.start + "":"" + ht.end); + else sb.append("","" + ht.start + "":"" + ht.end); + } + } + retHits[Globals.T] = sb.toString(); + + sb = new StringBuffer(); + for (Hit ht : qHitSort.values()) { + if (ht.order>0) { + if (sb.length()==0) sb.append(ht.start + "":"" + ht.end); + else sb.append("","" + ht.start + "":"" + ht.end); + } + } + retHits[Globals.Q] = sb.toString(); + + return retHits; + } + catch (Exception e) {ErrorReport.print(e, ""min hits""); return null;} + } + + protected static void sortForFormat(ArrayList hitList) { + Collections.sort(hitList, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (h1.start == h2.start) return h1.order - h2.order; // retain input order + return h1.start - h2.start; + } + }); + } + protected static void sortForOrder(ArrayList hitList, boolean isInv) { // calcOrderTarget + Collections.sort(hitList, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (isInv) return h2.order - h1.order; + else return h1.order - h2.order; + } + }); + } + protected static void sortForInv(ArrayList hitList) { + Collections.sort(hitList, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (h2.start == h1.start) return h2.order - h1.order; // retain input order + return h2.start - h1.start; + } + }); + } + protected static void sortForMerge(ArrayList hitList) { + Collections.sort(hitList, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (h1.start==h2.start) return h2.end-h1.end; + return h1.start - h2.start; + } + }); + } + /* Not used; Only called if target is disordered; not used, switched to not-sort; + * return new queryHits and targetHits ordered by target start; + */ + static protected String [] calcOrderTarget_NotUsed(String queryHits, String targetHits, boolean isInv) { + try { + String [] retHits = new String [2]; + + int nOrder=1, x1=0, x2=0; + String [] qHits = queryHits.split("",""); + ArrayList qHitSort = new ArrayList (qHits.length); + for (String coords : qHits) { // ordered by start + String [] y = coords.split("":""); + try {x1 = Integer.parseInt(y[0]); x2 = Integer.parseInt(y[1]);} + catch (Exception e) {System.err.println(""Parsing int: "" + coords); return retHits;} + + qHitSort.add(new Hit(nOrder++, x1, x2)); + } + + nOrder=1; + String [] tHits = targetHits.split("",""); + ArrayList tHitSort = new ArrayList (tHits.length); + for (String coords : tHits) { // ordered by query; if isInv, then descending + String [] y = coords.split("":""); + try {x1 = Integer.parseInt(y[0]); x2 = Integer.parseInt(y[1]);} + catch (Exception e) {System.err.println(""Parsing int: "" + coords); return retHits;} + + tHitSort.add(new Hit(nOrder++, x1, x2)); + } + if (isInv) sortForInv(tHitSort); + else sortForFormat(tHitSort); // target may be out of order; need ordered by start + + HashMap orderMap = new HashMap (nOrder); + nOrder=1; + for (Hit ht : tHitSort) orderMap.put(ht.order, nOrder++); + + for (Hit ht : tHitSort) ht.order = orderMap.get(ht.order); + for (Hit ht : qHitSort) ht.order = orderMap.get(ht.order); + + sortForOrder(tHitSort, false); + sortForOrder(qHitSort, false); + + StringBuffer sb = new StringBuffer(); + for (Hit ht : tHitSort) { + if (sb.length()==0) sb.append(ht.start + "":"" + ht.end); + else sb.append("","" + ht.start + "":"" + ht.end); + } + retHits[Globals.T] = sb.toString(); + + sb = new StringBuffer(); + for (Hit ht : qHitSort) { + if (sb.length()==0) sb.append(ht.start + "":"" + ht.end); + else sb.append("","" + ht.start + "":"" + ht.end); + } + retHits[Globals.Q] = sb.toString(); + + return retHits; + } + catch (Exception e) {ErrorReport.print(e, ""min hits""); return null;} + } + static private class Hit { + private int start, end, order; + + public Hit (int order, int start, int end) { + this.order=order; this.start=start; this.end=end; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/TextShowInfo.java",".java","15211","404","package symap.closeup; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.BorderLayout; +import java.awt.Color; +import java.util.Vector; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.WindowConstants; +import javax.swing.JCheckBox; + +import symap.Globals; +import symap.mapper.HitData; +import symap.sequence.Annotation; +import util.ErrorReport; +import util.Jcomp; + +/************************************************************************* + * Called from 2D SeqHits.PseudoHit, Sequence.Annotation, util.TextBox + * Show Info: When a hit-wire or gene is right-clicked, this is called to show its info. + * Show Align: For hit-wire, it also has an ""Align"" button + */ +public class TextShowInfo extends JDialog implements ActionListener { + private static final long serialVersionUID = 1L; + + // also used by SeqDataInfo + protected static final String disOrder = ""#""; + protected static final String titleMerge = ""Merged"", buttonMerge = ""Merge""; + protected static final String titleOrder = ""Order"", titleRemove = ""Remove"" + disOrder; // Remove is -ii only, doesn't work + protected static final String totalMerge = ""Total""; // Merge has total + + // For hit popup + private HitData hitDataObj=null; + private String title, theInfo, proj1, proj2, queryHits, targetHits; + private Annotation aObj1, aObj2; + private boolean isQuery; // isQuery for runAlign; + private boolean st1LTst2; // T query on left; F query on right + private boolean isInvHit; // !strands (but the block may be Inv) + + private AlignPool alignPool; + private HitAlignment[] hitAlignArr=null; + private JCheckBox ntCheckBox; + private JButton alignHitButton, orderButton, mergeButton, removeButton; + + // for Gene popup + private Annotation annoDataObj=null; + + private JButton closeButton; + + /*************************************************** + * 2D Gene info. Called by Annotation.java + */ + public TextShowInfo (Component parentFrame, String title, String theInfo, Annotation annoDataObj) { + super(); + setModal(false); + setTitle(title); + setResizable(true); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) {annoDataObj.setIsPopup(false);} + }); + this.annoDataObj = annoDataObj; + + JTextArea messageArea = new JTextArea(theInfo); + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.BOLD, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + closeButton = Jcomp.createButton(Jcomp.ok, ""Close window""); + closeButton.addActionListener(this); + + JPanel buttonPanel = new JPanel(); buttonPanel.setBackground(Color.white); + buttonPanel.add(closeButton); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(sPane,BorderLayout.CENTER); + getContentPane().add(buttonPanel,BorderLayout.SOUTH); + pack(); + + Dimension d = new Dimension (330, 200); + if (getWidth() >= d.width || getHeight() >= d.height) setSize(d); + setAlwaysOnTop(true); // doesn't work on Ubuntu + setLocationRelativeTo(null); + setVisible(true); + } + /*************************************************** + * 2D Hit info; + */ + public TextShowInfo (AlignPool alignPool, HitData hitDataObj, String title, String theInfo, String trailer, + boolean st1LTst2, String proj1, String proj2, Annotation aObj1, Annotation aObj2, String queryHits, String targetHits, + boolean isQuery, boolean isInv, boolean bSort) { + + super(); + setModal(false); + setTitle(title); + setResizable(true); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) {hitDataObj.setIsPopup(false);} + }); + + this.alignPool = alignPool; this.hitDataObj = hitDataObj; + this.title = title; this.theInfo = theInfo; + this.proj1 = proj1; this.proj2 = proj2; + this.aObj1 = aObj1; this.aObj2 = aObj2; + this.queryHits = queryHits; this.targetHits = targetHits; + this.isQuery = isQuery; this.st1LTst2 = st1LTst2; this.isInvHit = isInv; + + String gene1 = (aObj1!=null) ? "" #"" + aObj1.getFullGeneNum() : """"; + String gene2 = (aObj2!=null) ? "" #"" + aObj2.getFullGeneNum() : """"; + + boolean bMerge = title.startsWith(titleMerge); + boolean bOrder = title.startsWith(titleOrder); + boolean bRemove = title.startsWith(titleRemove); + + String name1 = String.format(""%-16s %s"", proj1, gene1); + String name2 = String.format(""%-16s %s"", proj2, gene2); + + /** Text - the tables and info **/ + String table1 = SeqDataInfo.formatHit(Globals.Q, name1, aObj1, queryHits, title, false, false); + int cntNegGap = SeqDataInfo.cntMergeNeg; + + String table2 = SeqDataInfo.formatHit(Globals.T, name2, aObj2, targetHits, title, isInv, bSort); + cntNegGap += SeqDataInfo.cntMergeNeg; + + // theInfo + theInfo += st1LTst2 ? (""\nL "" + table1+ ""\nR "" + table2) : (""\nL "" + table2+""\nR "" + table1); + theInfo += trailer; // if -ii, contains indices + + if (bMerge && (table1.contains(totalMerge) || table2.contains(totalMerge))) // no total in only 1 merged hit + theInfo += ""\nThe merged hits are not 1-to-1.""; + + boolean bDisorder = (SeqDataInfo.cntDisorder>0); + + if (bDisorder) { + if (bOrder) theInfo += ""\n"" + disOrder + disOrder + "" Disordered subhits""; + else theInfo += ""\n Disordered # column (same # subhits align)""; + } + /*****/ + + JTextArea messageArea = new JTextArea(theInfo); + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.BOLD, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + closeButton = Jcomp.createButton(Jcomp.ok, ""Close window""); + closeButton.addActionListener(this); + + // Hit only + alignHitButton = Jcomp.createButton(""Align"", ""Popup window of text alignment""); + alignHitButton.addActionListener(this); + ntCheckBox = new JCheckBox(""NT"", true); // not shown, was going to do AA align... + + orderButton = Jcomp.createButton(titleOrder, ""Order disordered hits(*)""); + orderButton.addActionListener(this); + + removeButton = Jcomp.createButton(titleRemove, ""Remove disordered hits(*)""); + removeButton.addActionListener(this); + + mergeButton = Jcomp.createButton(buttonMerge, ""Merge overlapping hits""); + mergeButton.addActionListener(this); + + JPanel buttonPanel = new JPanel(); buttonPanel.setBackground(Color.white); + if (!bMerge) { + if (cntNegGap>0 && bSort) buttonPanel.add(mergeButton); + if (bDisorder && !bOrder) buttonPanel.add(orderButton); + if (!bSort && !bRemove && Globals.INFO) buttonPanel.add(removeButton); + buttonPanel.add(alignHitButton); buttonPanel.add(Box.createHorizontalStrut(5)); + } + buttonPanel.add(closeButton); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(sPane,BorderLayout.CENTER); + getContentPane().add(buttonPanel,BorderLayout.SOUTH); + pack(); + + Dimension d = new Dimension (350, 200); // w,h + if (getWidth() >= d.width || getHeight() >= d.height) setSize(d); + setAlwaysOnTop(true); + setLocationRelativeTo(null); + setVisible(true); + } + public void actionPerformed(ActionEvent e) { + if (e.getSource() == closeButton) { + if (hitDataObj!=null) hitDataObj.setIsPopup(false); + else annoDataObj.setIsPopup(false); + setVisible(false); // close popup + } + else if (e.getSource() == alignHitButton) { + runAlign(true); // new align popup + } + else if (e.getSource() == orderButton) { + runOrder(); // two hit popups will be shown + } + else if (e.getSource() == mergeButton) { + runMerge(); // two hit popups will be shown + } + else if (e.getSource() == removeButton) { + runRemove(); // two hit popups will be shown + } + } + + /**************************************************************/ + private void addAlign(Vector lines, String aSeq1, String aSeqM, String aSeq2, int [] coords) { + try { + int nStart1=coords[0], nStart2=coords[2], nEnd=aSeq1.length(); + + int maxC = Math.max(coords[1], coords[3]); + int sz = (maxC+"""").length(); + String formatC = ""%"" + sz + ""d ""; + String formatM = ""%"" + sz + ""s ""; + + int inc = 60; // output in rows of 60 + int x; + StringBuffer sb = new StringBuffer (inc); + + for (int offset=0; offset= d.width || diag.getHeight() >= d.height) diag.setSize(d); + diag.setLocationRelativeTo(null); + //diag.setAlwaysOnTop(true); + diag.setVisible(true); + } + /****************************************************************/ + private void runAlign(boolean bTrim) { + try { + boolean isNT = ntCheckBox.isSelected(); + Vector hitList = new Vector (); + hitList.add(hitDataObj); + + // Run Align + hitAlignArr = alignPool.buildHitAlignments(hitList, isNT, isQuery, bTrim); + + String p1 = proj1.substring(0, proj1.indexOf("" "")); + String p2 = proj2.substring(0, proj2.indexOf("" "")); + + int cnt=0; + Vector lines = new Vector (); + for (HitAlignment hs : hitAlignArr) { + if (cnt>0) lines.add(""_______________________________________________________________________""); + String desc = (isNT) ? hs.toText(false, p1, p2) : hs.toTextAA(p1, p2); + String [] toks = desc.split(""\t""); + lines.add(toks[0]); // Block Hit# + lines.add(toks[1]); // %Id + + addAlign(lines, toks[2], toks[3], toks[4], hs.getCoords()); + + cnt++; + } + String msg=""""; + for (String l : lines) msg += l + ""\n""; + + String x = (bTrim) ? ""Align trim "" : ""Align""; + String title = x + hitDataObj.getName() + ""; "" + proj1 + "" to "" + proj2; + displayAlign(title, msg, bTrim); // true says put Reverse/Trim buttons on bottom + } + catch (Exception e) {ErrorReport.print(e, ""run align"");} + } + private void reverseAlign() { + hitAlignArr = alignPool.getHitReverse(hitAlignArr); + + int cnt=0; + String p1 = proj1.substring(0, proj1.indexOf("" "")); + String p2 = proj2.substring(0, proj2.indexOf("" "")); + + Vector lines = new Vector (); + for (HitAlignment hs : hitAlignArr) { + if (cnt>0) lines.add(""_______________________________________________________________________""); + String desc = hs.toText(false, p1, p2); + String [] toks = desc.split(""\t""); + lines.add(toks[0]); // Block Hit# + lines.add(toks[1]); // %Id + + addAlign(lines, toks[2], toks[3], toks[4], hs.getCoords()); + + cnt++; + } + String msg=""""; + for (String l : lines) msg += l + ""\n""; + + String title = ""Reverse Align "" + hitDataObj.getName() + ""; "" + proj1 + "" to "" + proj2; + displayAlign(title, msg, false); + } + + /************************************************************* + * toggle all hits and merged hits; + */ + private void runMerge() { + String queryShow = SeqDataInfo.calcMergeHits(Globals.Q, queryHits, false); + String targetShow = SeqDataInfo.calcMergeHits(Globals.T, targetHits, isInvHit); + + new TextShowInfo(alignPool, hitDataObj, titleMerge + "" "" + title, + theInfo, """", st1LTst2, proj1, proj2, aObj1, aObj2, + queryShow, targetShow, isQuery, isInvHit, true); + } + /************************************************************* + * retain target ordered by query - the '#' will be out-of-order; + */ + private void runOrder() { + new TextShowInfo(alignPool, hitDataObj, titleOrder + "" "" + title, + theInfo, """", st1LTst2, proj1, proj2, aObj1, aObj2, + queryHits, targetHits, isQuery, isInvHit, false /* keep order */); + } + /************************************************************* + * run after runOrder to remove disordered hits + */ + private void runRemove() { + String [] sort = SeqDataInfo.calcRemoveDisorder(queryHits, targetHits, isInvHit); + + new TextShowInfo(alignPool, hitDataObj, titleRemove + "" "" + title, + theInfo, """", st1LTst2, proj1, proj2, aObj1, aObj2, + sort[Globals.Q], sort[Globals.T], isQuery, isInvHit, false /* keep order */); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/CloseUp.java",".java","1269","46","package symap.closeup; + +import java.sql.SQLException; +import java.util.Vector; + +import symap.drawingpanel.DrawingPanel; +import symap.mapper.HitData; +import symap.sequence.Sequence; +import colordialog.ColorDialogHandler; +import util.ErrorReport; + +/******************************************************* + * created in symap.SyMAP at startup + */ +public class CloseUp { + private DrawingPanel dp; + private ColorDialogHandler cdh; + + public CloseUp(DrawingPanel dp, ColorDialogHandler cdh) { // frame.SyMAP2d + this.dp = dp; + this.cdh = cdh; + } + + /** + * Called by Sequence on mouse release; If no hits are found, then no dialog is shown. + */ + public int showCloseUp(Vector hitList, Sequence seqObj, int start, int end, + boolean isQuery, String otherChr, int numShow) { + try { + if (dp != null) dp.setFrameEnabled(false); + + CloseUpDialog cuDialog = new CloseUpDialog(this, hitList, seqObj,start,end, isQuery, otherChr, numShow); + + if (dp != null) dp.setFrameEnabled(true); + if (cuDialog != null && cdh != null) cdh.addListener(cuDialog); + + return cuDialog == null ? -1 : cuDialog.showIfHits(); + } + catch (SQLException e) {ErrorReport.print(e, ""Creating a CloseUpDialog""); return 0;} + } + + public DrawingPanel getDrawingPanel() { + return dp; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/DoubleDimension.java",".java","652","28","package symap.closeup; + +import java.awt.geom.Dimension2D; + +/*************************************************** + * Used in CloseUp methods + */ +public class DoubleDimension extends Dimension2D { + protected double width; + protected double height; + + protected DoubleDimension() { + width = 0; + height = 0; + } + protected DoubleDimension(double width, double height) { + this.width = width; + this.height = height; + } + public void setSize(double width, double height) { + this.width = width; + this.height = height; + } + public double getWidth() {return width;} + public double getHeight() {return height;} +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/MsaRun.java",".java","18682","554","package symap.closeup; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.MalformedURLException; +import java.util.Collections; +import java.util.Iterator; +import java.util.Vector; +import java.util.HashMap; +import javax.swing.JTextField; + +import symap.Globals; +import symap.Ext; + +import util.ErrorReport; +import util.Utilities; +import util.FileDir; + +/*********************************** + * SyMAP Query MSA - align selected set using muscle or mafft + * + * Called from MsaMainPanel, which adds all sequences and their names, then calls alignMafft or alignMuscle + * Write fasta, run align, read result + * + * This was written for NT or AA, but only used for NT + */ +public class MsaRun { + private final static String TARGET_DIR = Globals.alignDir; + private final static String SOURCE_FILE = Globals.alignDir + ""/Source.fa""; // put in directory and do not delete + private final static String TARGET_FILE = Globals.alignDir + ""/Align.fa""; + + private final static int SEQ_LINE_LEN = 80; + protected final static char gapIn='-', gapOut='.', unk='n'; + + // input/output + private String fileName = null, pgmStr=""""; // input + private JTextField progressField; + private Vector seqNames = null; // input/output + private Vector seqSeqs = null; // input/output + protected String finalStats= "" ""; // Used in MsaMainPanel + private int maxSeq=0; + private MsaMainPanel msaMain=null; // to checked Stopped + + protected MsaRun(MsaMainPanel msaMain, String name, JTextField progressField) { + this.msaMain = msaMain; + seqNames = new Vector (); + seqSeqs = new Vector (); + fileName = name; + this.progressField = progressField; + + FileDir.deleteFile(TARGET_FILE); // previous file; if error, could read old one if not removed + } + protected boolean hasFilename() { return fileName != null; } + + // Add input + protected void addSequence(String name, String seq) { + seqNames.add(name); + seqSeqs.add(seq); + } + // Get results + protected int getNumSeqs() {return seqSeqs.size();} + protected String [] getNames() {return seqNames.toArray(new String[seqSeqs.size()]);} + protected String [] getSeqs() {return seqSeqs.toArray(new String[seqSeqs.size()]);} + protected int getMaxSeqLen() {return maxSeq;} + + /************************************************************************ + * MAFFT + * String cmd = ./ext/mafft/mac/mafft.bat Source.fa >Align.fa; // command line from /queryMSA + * cmd = cmd + "" --auto --reorder --thread "" + cpus + "" "" + SOURCE_FILE; // used by TCW + **********************************************************************/ + protected boolean alignMafft(String status, boolean bTrim, boolean bAuto, int cpu) { + pgmStr = ""MAFFT""; + + String cmd = Ext.getMafftCmd(); + + if (bAuto) cmd += "" --auto""; + if (cpu>1) cmd += "" --thread "" + cpu; + + String trace = cmd + "" "" + SOURCE_FILE + "" >"" + TARGET_FILE; + if (Globals.INFO) Globals.prt(trace); + + try { + long time = Utilities.getNanoTime(); + + progressField.setText(""Writing sequences to file""); + FileDir.checkCreateDir(TARGET_DIR, true); + writeFASTA(SOURCE_FILE); + + progressField.setText(status); + + String traceFile = Globals.alignDir + ""/maffta.log""; + + int rc = runStdOut(cmd + "" "" + SOURCE_FILE, TARGET_FILE, traceFile); + if (rc!=0) { + if (msaMain.bStopped) return false; + + Globals.eprt(""MAFFT failed with rc="" + rc); + if (rc==1) Globals.prt(""rc=1 may indicate not enought memory""); + Globals.prt(trace); + return false; + } + + progressField.setText(""Reading results""); + if (!readFASTA(TARGET_FILE)) { + if (msaMain.bStopped) return false; + + Globals.eprt(""MAFFT failed reading "" + TARGET_FILE); + Globals.prt(trace); + return false; + }; + + trimEnds(bTrim); + if (Globals.INFO) finalStats += "" Time: "" + Utilities.getNanoTimeStr(time); + progressField.setText(""Displaying results""); + return true; + } + catch(Exception e) { + if (!msaMain.bStopped) { + ErrorReport.print(e, ""Exception occurred when running MAFTA""); + Globals.prt(trace); + } + return false; + } + } + private int runStdOut(String cmd, String outFile, String errFile) { + int exitVal=0; + try { + String[] args = cmd.split(""\\s+""); + ProcessBuilder pb = new ProcessBuilder(args); + pb.redirectOutput(new File(outFile)); + pb.redirectError(new File(errFile)); + + Process p = pb.start(); + exitVal = p.waitFor(); + + return exitVal; + } + catch (MalformedURLException e) { + if (!msaMain.bStopped) ErrorReport.print(e, ""MalformedURLException""); + exitVal=-3; + } + catch (IOException e) { + if (!msaMain.bStopped) ErrorReport.print(e, ""IOException - check permissions""); + exitVal=-2; + } + catch (Exception e) { + if (!msaMain.bStopped) ErrorReport.print(e, ""Command failed""); + exitVal=-1; + } + return exitVal; + } + /***************************************************************** + * MUSCLE + * String cmd = path + "" -in "" + SOURCE_FILE + "" -out "" + TARGET_FILE; + ***************************************************************/ + protected boolean alignMuscle(String status, boolean bTrim) {// set status in calling symapQuery.TableShow + pgmStr = ""MUSCLE""; + String cmd = Ext.getMuscleCmd(); + + String trace = cmd + "" -in "" + SOURCE_FILE + "" -out "" + TARGET_FILE; + if (Globals.INFO) Globals.prt(trace); + try { + long time = Utilities.getNanoTime(); + + progressField.setText(""Writing sequences to file""); + FileDir.checkCreateDir(TARGET_DIR, true); + writeFASTA(SOURCE_FILE); + + progressField.setText(status); + + String [] x = {cmd, ""-in"", SOURCE_FILE, ""-out"", TARGET_FILE}; + Process pr = Runtime.getRuntime().exec(x); + pr.waitFor(); + + if (pr.exitValue()!=0) { + if (msaMain.bStopped) return false; + + Globals.eprt(""MUSCLE failed with rc="" + pr.exitValue()); + Globals.prt(trace); + return false; + } + progressField.setText(""Reading results""); + if (!readFASTA(TARGET_FILE)) { + if (msaMain.bStopped) return false; + + Globals.eprt(""MUSCLE failed reading "" + TARGET_FILE); + Globals.prt(trace); + return false; + }; + + trimEnds(bTrim); + if (Globals.INFO) finalStats += "" Time: "" + Utilities.getNanoTimeStr(time); + progressField.setText(""Displaying results""); + return true; + } + catch(Exception e) { + if (!msaMain.bStopped) { + ErrorReport.print(e, ""Align sequences with muscle""); + Globals.prt(trace); + } + return false; + } + } + /***************************************************************/ + private void trimEnds(boolean bTrim) {// called if Trim checkbox + if (!bTrim) return; + try { + String consen = seqSeqs.get(0); + int len0=consen.length()-1; + if (consen.charAt(0)!=gapOut && consen.charAt(len0)!=gapOut) { + finalStats += "" Trim 0""; + return; + } + + int s=0; + while (consen.charAt(s)==gapOut && s<=len0) s++; + if (s!=0) { + Vector tSeqs = new Vector (); + for (String seq : seqSeqs) tSeqs.add(seq.substring(s)); + seqSeqs.clear(); + seqSeqs = tSeqs; + consen = seqSeqs.get(0); // get modified one + len0 = consen.length()-1; + } + int e=len0; + while (consen.charAt(e)==gapOut && e>=0) e--; + if (e!=len0) { + Vector tSeqs = new Vector (); + for (String seq : seqSeqs) tSeqs.add(seq.substring(0,e)); + seqSeqs.clear(); + seqSeqs = tSeqs; + } + finalStats += String.format("" Trim %,d"", (s+(len0-e))); + } + catch(Exception e) {ErrorReport.print(e, ""Align trim sequences""); } + } + + /******************************************************/ + protected void exportConsensus(String filename) { + String targetDirectory = TARGET_DIR + ""/""; + File targetDir = new File(targetDirectory); + if (!targetDir.exists()) targetDir.mkdir(); + + writeFASTA(targetDirectory + filename); // Consensus is 1st sequence, followed by the rest + } + /******************************************************/ + private void writeFASTA(String fname) { + try { + PrintWriter out = new PrintWriter(new FileWriter(fname)); + + Iterator nameIter = seqNames.iterator(); + Iterator seqIter = seqSeqs.iterator(); + + while(nameIter.hasNext()) { + int pos = 0; + String theSeq = seqIter.next(); + maxSeq = Math.max(theSeq.length(), maxSeq); + out.println("">"" + nameIter.next()); + + for(;(pos + SEQ_LINE_LEN) < theSeq.length(); pos += SEQ_LINE_LEN) { + out.println(theSeq.substring(pos, pos+SEQ_LINE_LEN)); + } + out.println(theSeq.substring(pos)); + } + out.close(); + } + catch(Exception e) {ErrorReport.print(e, ""Write FASTA file "" + fname);} + } + /******************************************************/ + private boolean readFASTA(String fname) { + try { + if (!FileDir.fileExists(fname)) { + util.Popup.showErrorMessage(""No output files were created. Make sure "" + pgmStr + "" exists""); + return false; + } + // The sequences in the alignment file are not in original order; save order to put back + int nSeqs = seqNames.size(); + HashMap seqPosMap = new HashMap (nSeqs); + for (int i=0; i"")) { + if (theName.length() > 0 && theSeq.length() > 0) { // last sequence + if (seqPosMap.containsKey(theName)) { + int i = seqPosMap.get(theName); + names[i] = theName; + seq[i] = theSeq.replace(gapIn, gapOut); + } + else Globals.eprt(""Cannot read from input file: "" + theName); + } + theName = line.substring(1); + theSeq = """"; + } else { + theSeq += line; + } + } + if (theName.length() > 0 && theSeq.length() > 0) { // last one + int i = seqPosMap.get(theName); + names[i] = theName; + seq[i] = theSeq.replace(gapIn, gapOut); + } + in.close(); + + // Enter them in original order + int cntGood=0; + int len = seq[0].length(); + for (int i=0; i counts = new HashMap(); + + for(int base=0; base bCntVec = new Vector (); + for (Character c : counts.keySet()) { + int cnt = counts.get(c); + bCntVec.add(new SymbolCount(c, cnt)); + if (c!=gapOut) totalCount += cnt; + } + counts.clear(); + Collections.sort(bCntVec); + + //Test if the there is one symbol most frequent + if (totalCount==1) { // single value for column; rest are gaps + theConsensus += gapOut; + cntGap++; + } + else if (bCntVec.size()==1) { // all syms the same; can't all be gap + theConsensus += bCntVec.get(0).sym; + cntMatch++; + } + else if (bCntVec.size()==2 && (bCntVec.get(0).sym==gapOut || bCntVec.get(1).sym==gapOut)) { // more than one match, rest gaps + char c = (bCntVec.get(0).sym==gapOut) ? bCntVec.get(1).sym : bCntVec.get(0).sym; + theConsensus += c; + cntMatch++; + } + else { + char cc = unk; // if no best base + for (int i=0; i1) { + cc = Character.toLowerCase(sc.sym); + theConsensus += cc; + cntMis++; + break; + } + } + if (cc==unk) { + theConsensus += cc; + cntMis++; + } + } + } + seqNames.insertElementAt(""Consensus"", 0); + seqSeqs.insertElementAt(theConsensus, 0); + + double score = ((double) cntMatch/(double) nSeqLen)*100.0; + finalStats = String.format("" %sID %.1f Len %,d Match %,d Mismatch %,d Gap %,d"", + ""%"", score, nSeqLen, cntMatch, cntMis, cntGap); + } + catch(Exception e) {ErrorReport.print(e, ""Error building consensus ""); return;} + } + private static int getTotalCount(Vector theCounts) { + int retVal = 0; + Iterator iter = theCounts.iterator(); + while(iter.hasNext()) { + SymbolCount temp = iter.next(); + if(temp.sym != gapOut) retVal += temp.cnt; + } + return retVal; + } + //Data structure for sorting/retrieving counts + private class SymbolCount implements Comparable { + private SymbolCount(char symbol, int count) { + sym = symbol; + cnt = count; + } + public int compareTo(SymbolCount a) { + return a.cnt - cnt; + } + private char sym; + private int cnt; + } + /********************************************************** + * The below is currently not used because no AA + ********************************************************/ + private static Character getMostCommonRelated(Vector theSymbols) { + //Special case: need at least 2 non-gap values to have consensus + if (getTotalCount(theSymbols) == 1) return gapOut; + + int [] relateCounts = new int[theSymbols.size()]; + for (int x=0; x (relateCounts[maxPos]) ) + maxPos = x; + } + return theSymbols.get(maxPos).sym; + } + // Called by MsaPanel - but never really since not aligning AA + // Return true anytime the BLOSUM62 matrix value is >= 1. This seems to + // be how blast places '+' for a likely substitution in it's alignment. + static protected boolean isCommonAcidSub(char chAcid1, char chAcid2) { + if (chAcid1 == chAcid2) return true; + + switch (chAcid1) { + case AMINO_Glx: + return (chAcid2 == AMINO_Asp || chAcid2 == AMINO_Gln + || chAcid2 == AMINO_Glu || chAcid2 == AMINO_Lys || chAcid2 == AMINO_Asx); + case AMINO_Asx: + return (chAcid2 == AMINO_Asn || chAcid2 == AMINO_Asp + || chAcid2 == AMINO_Glu || chAcid2 == AMINO_Glx); + case AMINO_Ala: + return (chAcid2 == AMINO_Ser); + case AMINO_Arg: + return (chAcid2 == AMINO_Gln || chAcid2 == AMINO_Lys); + case AMINO_Asn: + return chAcid2 == AMINO_Asp || chAcid2 == AMINO_His + || chAcid2 == AMINO_Ser || chAcid2 == AMINO_Asx; + case AMINO_Asp: + return chAcid2 == AMINO_Asn || chAcid2 == AMINO_Glu + || chAcid2 == AMINO_Asx || chAcid2 == AMINO_Glx; + case AMINO_Gln: + return chAcid2 == AMINO_Arg || chAcid2 == AMINO_Glu + || chAcid2 == AMINO_Lys || chAcid2 == AMINO_Glx; + case AMINO_Glu: + return chAcid2 == AMINO_Asp || chAcid2 == AMINO_Gln + || chAcid2 == AMINO_Lys || chAcid2 == AMINO_Asx || chAcid2 == AMINO_Glx; + case AMINO_His: + return chAcid2 == AMINO_Asn || chAcid2 == AMINO_Tyr; + case AMINO_Ile: + return chAcid2 == AMINO_Leu || chAcid2 == AMINO_Met || chAcid2 == AMINO_Val; + case AMINO_Leu: + return chAcid2 == AMINO_Ile || chAcid2 == AMINO_Met || chAcid2 == AMINO_Val; + case AMINO_Lys: + return chAcid2 == AMINO_Arg || chAcid2 == AMINO_Gln + || chAcid2 == AMINO_Glu || chAcid2 == AMINO_Glx; + case AMINO_Met: + return chAcid2 == AMINO_Ile || chAcid2 == AMINO_Leu || chAcid2 == AMINO_Val; + case AMINO_Phe: + return chAcid2 == AMINO_Trp || chAcid2 == AMINO_Tyr; + case AMINO_Ser: + return chAcid2 == AMINO_Ala || chAcid2 == AMINO_Asn || chAcid2 == AMINO_Thr; + case AMINO_Thr: + return chAcid2 == AMINO_Ser; + case AMINO_Trp: + return chAcid2 == AMINO_Phe || chAcid2 == AMINO_Tyr; + case AMINO_Tyr: + return chAcid2 == AMINO_His || chAcid2 == AMINO_Phe || chAcid2 == AMINO_Trp; + case AMINO_Val: + return chAcid2 == AMINO_Ile || chAcid2 == AMINO_Leu || chAcid2 == AMINO_Met; + default: + return false; + } + } + static private final char AMINO_Phe = 'F'; + static private final char AMINO_Ile = 'I'; + static private final char AMINO_Met = 'M'; + static private final char AMINO_Leu = 'L'; + static private final char AMINO_Val = 'V'; +// static private final char AMINO_Pro = 'P'; + static private final char AMINO_Ser = 'S'; + static private final char AMINO_Thr = 'T'; + static private final char AMINO_Ala = 'A'; + static private final char AMINO_Tyr = 'Y'; +// static private final char AMINO_Stop = '*'; + static private final char AMINO_Gln = 'Q'; + static private final char AMINO_Lys = 'K'; + static private final char AMINO_Glu = 'E'; + static private final char AMINO_Trp = 'W'; +// static private final char AMINO_Gly = 'G'; + static private final char AMINO_His = 'H'; + static private final char AMINO_Asn = 'N'; + static private final char AMINO_Asp = 'D'; +// static private final char AMINO_Cys = 'C'; + static private final char AMINO_Arg = 'R'; + static public final char AMINO_Glx = 'Z'; + static public final char AMINO_Asx = 'B'; + static public final char AMINO_Amiguous = 'X'; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/ArrowLine.java",".java","5510","137","package symap.closeup; + +import java.awt.Polygon; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.Dimension2D; +import java.awt.geom.PathIterator; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +/**************************************************************** + * Hit line and Ruler; + */ +public class ArrowLine implements Shape { + protected static final int NO_ARROW = 0, LEFT_ARROW = 1, RIGHT_ARROW = 2, BOTH_ARROWS = 3; + private DoublePolygon poly; + private double lineY, arrowLineWidth; + + protected ArrowLine() {poly = new DoublePolygon();} + + protected void setBounds(Rectangle2D bounds, double lineThickness, Dimension2D arrowDimension, int arrow) { + if (arrow == NO_ARROW) setBounds(bounds,lineThickness,null,null); + else setBounds(bounds,lineThickness, + arrow == RIGHT_ARROW ? null : arrowDimension, + arrow == LEFT_ARROW ? null : arrowDimension); + } + protected void setBounds(Rectangle2D bounds, double lineThickness, Dimension2D lArrowDim, Dimension2D rArrowDim) { + poly.reset(); + if (bounds.getWidth() <= 0) return ; + + int arrow = NO_ARROW; + if (lArrowDim != null) arrow += LEFT_ARROW; + if (rArrowDim != null) arrow += RIGHT_ARROW; + + double halfY = bounds.getY() + bounds.getHeight()/2.0; + + lineY = halfY - lineThickness/2.0; + arrowLineWidth = 0; + + if (arrow == NO_ARROW) { + poly.addPoint(bounds.getX(),lineY); + poly.addPoint(bounds.getX()+bounds.getWidth(),lineY); + poly.addPoint(bounds.getX()+bounds.getWidth(),lineY+lineThickness); + poly.addPoint(bounds.getX(),lineY+lineThickness); + return ; + } + + double lineRX, lineLX, arrowXR, arrowXL, arrowYL, arrowYR; + + if (rArrowDim == null) rArrowDim = new DoubleDimension(0,lineThickness); + else rArrowDim = new DoubleDimension(rArrowDim.getWidth(),rArrowDim.getHeight()); + if (lArrowDim == null) lArrowDim = new DoubleDimension(0,lineThickness); + else lArrowDim = new DoubleDimension(lArrowDim.getWidth(),lArrowDim.getHeight()); + + if (rArrowDim.getWidth() + lArrowDim.getWidth() > bounds.getWidth()) { + rArrowDim.setSize(bounds.getWidth()/2.0,rArrowDim.getHeight()); + lArrowDim.setSize(rArrowDim.getWidth(), lArrowDim.getHeight()); + } + + final double LA_OFFSET = lArrowDim.getHeight() bounds.getWidth()) lineLX = bounds.getX(); + + arrowXL = bounds.getX() + lArrowDim.getWidth(); + if (lArrowDim.getWidth() > bounds.getWidth()) arrowXL = bounds.getX() + bounds.getWidth(); + + if (arrow == RIGHT_ARROW) + arrowLineWidth = bounds.getX()+bounds.getWidth() - arrowXR; + else + arrowLineWidth = arrowXL - bounds.getX(); + arrowLineWidth = arrowLineWidth-1; + + if (arrow == RIGHT_ARROW) { + poly.addPoint(bounds.getX(),lineY); + poly.addPoint(bounds.getX(),lineY+lineThickness); + poly.addPoint(lineRX,lineY+lineThickness); + poly.addPoint(arrowXR,arrowYR+rArrowDim.getHeight()); + poly.addPoint(bounds.getX()+bounds.getWidth(),halfY); + poly.addPoint(arrowXR,arrowYR); + poly.addPoint(lineRX,lineY); + } + else if (arrow == LEFT_ARROW) { + poly.addPoint(bounds.getX()+bounds.getWidth(),lineY); + poly.addPoint(bounds.getX()+bounds.getWidth(),lineY+lineThickness); + poly.addPoint(lineLX,lineY+lineThickness); + poly.addPoint(arrowXL,arrowYL+lArrowDim.getHeight()); + poly.addPoint(bounds.getX(),halfY); + poly.addPoint(arrowXL,arrowYL); + poly.addPoint(lineLX,lineY); + } + else if (arrow == BOTH_ARROWS) { + poly.addPoint(lineLX,lineY); + poly.addPoint(lineRX,lineY); + poly.addPoint(arrowXR,arrowYR); + poly.addPoint(bounds.getX()+bounds.getWidth(),halfY); + poly.addPoint(arrowXR,arrowYR+rArrowDim.getHeight()); + poly.addPoint(lineRX,lineY+lineThickness); + poly.addPoint(lineLX,lineY+lineThickness); + poly.addPoint(arrowXL,arrowYL+lArrowDim.getHeight()); + poly.addPoint(bounds.getX(),halfY); + poly.addPoint(arrowXL,arrowYL); + } + } + + public boolean contains(double x, double y) {return poly.contains(x,y);} + public boolean contains(double x, double y, double w, double h) {return poly.contains(x,y,w,h);} + public boolean contains(Point2D p) {return poly.contains(p);} + public boolean contains(Rectangle2D r) {return poly.contains(r);} + public Rectangle getBounds() {return poly.getBounds();} + public Rectangle2D getBounds2D() {return poly.getBounds2D();} + public PathIterator getPathIterator(AffineTransform at) {return poly.getPathIterator(at);} + public PathIterator getPathIterator(AffineTransform at, double flatness) {return poly.getPathIterator(at,flatness);} + public boolean intersects(double x, double y, double w, double h) {return poly.intersects(x,y,w,h);} + + public boolean intersects(Rectangle2D r) {return poly.intersects(r);} + + private class DoublePolygon extends Polygon { + public DoublePolygon() {super();} + public void addPoint(double x, double y) { + super.addPoint((int)Math.round(x),(int)Math.round(y)); + } + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/TextShowSeq.java",".java","13221","392","package symap.closeup; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Vector; + +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JSeparator; +import javax.swing.JTextArea; +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import symap.drawingpanel.DrawingPanel; +import symap.mapper.HitData; +import symap.sequence.Annotation; +import symap.sequence.Sequence; +import util.ErrorReport; +import util.Jcomp; + +/***************************************************** + * 2D Show Seq Options pull-down; called when sequence is selected + * Uses specialized displayInfoMonoSpace for display + */ +public class TextShowSeq extends JDialog implements ActionListener { + private static final long serialVersionUID = 1L; + private final int INC=80; + private final boolean bGene=false; // wait until next release - needs some work + + private AlignPool alignPool; + private DrawingPanel drawPanel; + private Sequence seqObj; + private String projectName; + private int rStart, rEnd; + private int grpID; + private boolean isQuery; + private String type=""""; + + private Vector hitList; + private Vector geneList; + + private JButton okButton, cancelButton; + private JRadioButton exonButton, transExonButton, geneButton; + private JRadioButton hitButton, revHitButton, transHitButton, fullHitButton, regionButton; + + public TextShowSeq (DrawingPanel dp, Sequence sequence, String project, + int grpID, int start, int end, boolean isQuery) + { + super(); + setModal(false); + setResizable(true); + + alignPool = new AlignPool(dp.getDBC()); + drawPanel = dp; + this.seqObj = sequence; + this.projectName = project; + this.rStart = start; + this.rEnd = end; + this.grpID = grpID; + this.isQuery = isQuery; + + hitButton = Jcomp.createRadio(""Subhits"", ""Show separate subhits""); // CAS576 add tip; change label + revHitButton = Jcomp.createRadio(""Reverse"", ""Show reversed subhits""); + fullHitButton = Jcomp.createRadio(""Full Hit"", ""Show from start to end of the clustered hit""); + regionButton = Jcomp.createRadio(""Region"", ""Show the selected sequence""); + // these are not working... + transHitButton = new JRadioButton(""Translated Hit""); transHitButton.setBackground(Color.white); + geneButton = new JRadioButton(""Gene""); geneButton.setBackground(Color.white); + exonButton = new JRadioButton(""Exon""); exonButton.setBackground(Color.white); + transExonButton = new JRadioButton(""Translated Exon""); transExonButton.setBackground(Color.white); + + ButtonGroup group = new ButtonGroup(); + group.add(hitButton); group.add(transHitButton); + group.add(revHitButton); group.add(fullHitButton); + group.add(regionButton); group.add(geneButton); + group.add(exonButton); group.add(transExonButton); + + JPanel buttonPanel = new JPanel(); + okButton = Jcomp.createButton(""Show"", ""Show Sequence""); + okButton.addActionListener(this); + cancelButton = Jcomp.createButton(Jcomp.cancel, ""Cancel action""); + cancelButton.addActionListener(this); + buttonPanel.add(okButton); buttonPanel.add(cancelButton); + + Container cp = getContentPane(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + cp.setLayout(gbl); + gbc.fill = 2; + gbc.gridheight = 1; + gbc.ipadx = 5; + gbc.ipady = 8; + + int n = GridBagConstraints.REMAINDER; + addToGrid(cp,gbl,gbc,hitButton, 1); + addToGrid(cp,gbl,gbc,revHitButton, n); + addToGrid(cp,gbl,gbc,fullHitButton, 1); + addToGrid(cp,gbl,gbc,regionButton, n); + + if (bGene) { + //addToGrid(cp,gbl,gbc,transHitButton, 2); + addToGrid(cp,gbl,gbc,exonButton, 1); + addToGrid(cp,gbl,gbc,transExonButton, n); + addToGrid(cp,gbl,gbc,geneButton, n); + } + addToGrid(cp,gbl,gbc,new JSeparator(),n); + addToGrid(cp,gbl,gbc,buttonPanel,n); + hitButton.setSelected(true); + + init(); + + pack(); + + Dimension d = new Dimension (330, 200); + if (getWidth() >= d.width || getHeight() >= d.height) setSize(d); + setVisible(true); + setAlwaysOnTop(true); + setLocationRelativeTo(null); + setTitle(""Show Sequence Options""); + } + // if no genes in region, disable gene/exon. If no hits in region, disable hit/full hit. + private void init() { + hitList = drawPanel.getHitsInRange(seqObj,rStart,rEnd); + geneList = seqObj.getAnnoGene(rStart, rEnd); // EXON_INT if select Exon + if (hitList.size()==0) { + hitButton.setEnabled(false); revHitButton.setEnabled(false); + transHitButton.setEnabled(false); fullHitButton.setEnabled(false); + regionButton.setSelected(true); + } + + if (geneList.size()==0) { + geneButton.setEnabled(false); exonButton.setEnabled(false); transExonButton.setEnabled(false); + } + } + private void addToGrid(Container c, GridBagLayout gbl, GridBagConstraints gbc, Component comp, int i) { + gbc.gridwidth = i; + gbl.setConstraints(comp,gbc); + c.add(comp); + } + /****************************************************************/ + public void actionPerformed(ActionEvent e) { + if (e.getSource() == okButton) { + showSeq(); + setVisible(false); + } + else if (e.getSource() == cancelButton) { + setVisible(false); + } + } + // Each show will return Vector to be shown as FASTA + private void showSeq() { + Vector seqs=null; + + if (hitButton.isSelected()) seqs = showHits(false); + else if (revHitButton.isSelected()) seqs = showHits(true); + else if (fullHitButton.isSelected()) seqs = showFullHits(); + else if (regionButton.isSelected()) seqs = showRegion(); + + else if (transHitButton.isSelected()) seqs = showTransHits(); + else if (geneButton.isSelected()) seqs = showGenes(); + else if (exonButton.isSelected()) seqs = showSepExons(); + else if (transExonButton.isSelected()) seqs = showExons(true); + if (seqs==null) return; + + // Create formated line + StringBuffer bfLines = new StringBuffer (); + + for (SeqData sd : seqs) { + bfLines.append(String.format(""> %s"", sd.getHeader()) + ""\n""); + String seq = sd.getSeq(); + + int len = seq.length(), x=0; + while ((x+INC) showRegion() { + try { + type=""Region""; + String coords = rStart + "":"" + rEnd; + String title = ""Region "" + SeqData.coordsStr(rStart, rEnd); + + String seq = alignPool.loadPseudoSeq(coords, grpID); + + SeqData sd = new SeqData(seq, ' ', title); + Vector seqs = new Vector (1); + seqs.add(sd); + + return seqs; + } catch (Exception e) {ErrorReport.print(e, ""show gene""); return null;} + } + // all subhits + private Vector showHits(boolean bRev) { + try { + type = (hitList.size()>1) ? "" Hits"" : ""Hit""; + if (bRev) type = "" Reverse "" + type; + if (hitList.size()>1) type = hitList.size() + type; + return alignPool.getHitSequence(hitList, grpID, isQuery, bRev); + + } catch (Exception e) {ErrorReport.print(e, ""show gene""); return null;} + } + // merged + private Vector showFullHits() { + try { + type= ""Clustered hit region ""; + type = type + hitList.size(); + int s, e; + + Vector seqs = new Vector (hitList.size()); + for (HitData hd : hitList) { + s = (isQuery) ? hd.getStart1() : hd.getStart2(); + e = (isQuery) ? hd.getEnd1() : hd.getEnd2(); + + String seq = alignPool.loadPseudoSeq(s + "":"" + e, grpID); + + String title = hd.getName() + "" "" + SeqData.coordsStr(s, e); + SeqData sd = new SeqData(seq, ' ', title); + seqs.add(sd); + } + return seqs; + + } catch (Exception e) {ErrorReport.print(e, ""show full hit region""); return null;} + } + //Translated hits (best frame? or all frames?) + private Vector showTransHits() { + try { + type=""Translated hits""; + + return alignPool.getHitSequence(hitList, grpID, isQuery, false); // TODO translated + + } catch (Exception e) {ErrorReport.print(e, ""show gene""); return null;} + } + // Full gene sequence + private Vector showGenes() { + try { + type = ""Gene""; + Vector seqs = new Vector (); + int s,e; + for (Annotation ad : geneList) { + s = ad.getStart(); + e = ad.getEnd(); + + String seq = alignPool.loadPseudoSeq(s + "":"" + e, grpID); + + String title = ad.getTag() + "" "" + SeqData.coordsStr(s, e); + SeqData sd = new SeqData(seq, ' ', title); + seqs.add(sd); + } + + return seqs; + } catch (Exception e) {ErrorReport.print(e, ""show gene""); return null;} + } + + // concatenated exons + private Vector showExons(boolean bTrans) { + try { + type = ""Exons""; + int geneIdx = seqObj.getAnnoGene(rStart, rEnd).get(0).getAnnoIdx(); + Vector exonList = seqObj.getAnnoExon(geneIdx); + Annotation [] annoArr = new Annotation [exonList.size()]; + for (int i=0; i comp = Annotation.getExonStartComparator(); + Arrays.sort(annoArr, comp); + + Vector seqs = new Vector (exonList.size()); + int last_gene_idx = -1, s, e, farS=Integer.MAX_VALUE, farE=0; + boolean isPos=true; + String concatExon="""", geneTag=""""; + + for (Annotation ad : annoArr) { + if (last_gene_idx!=ad.getGeneIdx()) { + if (last_gene_idx != -1) { + String title = geneTag + "" "" + SeqData.coordsStr(farS, farE); + if (bTrans) concatExon = SeqData.translate(concatExon); + SeqData sd = new SeqData(concatExon, ' ', title); + seqs.add(sd); + + farS=Integer.MAX_VALUE; farE=0; + concatExon=""""; + } + + last_gene_idx = ad.getGeneIdx(); + for (Annotation gd : geneList) { + if (last_gene_idx==gd.getAnnoIdx()) { + geneTag = gd.getTag(); + isPos = gd.isStrandPos(); + } + } + } + s = ad.getStart(); e = ad.getEnd(); + String exon = alignPool.loadPseudoSeq(s + "":"" + e, grpID); + if (!isPos) exon = SeqData.revComplement(exon); + concatExon += exon; + + farS = Math.min(farS, s); farE = Math.max(farE, e); + } + // process last one + String title = geneTag + "" "" + SeqData.coordsStr(farS, farE); + if (bTrans) concatExon = SeqData.translate(concatExon); + SeqData sd = new SeqData(concatExon, ' ', title); + seqs.add(sd); + + return seqs; + } catch (Exception e) {ErrorReport.print(e, ""show exon""); return null;} + } + // separate exons + private Vector showSepExons() { + try { + type = ""Exons""; + int geneIdx = seqObj.getAnnoGene(rStart, rEnd).get(0).getAnnoIdx(); + Vector exonList = seqObj.getAnnoExon(geneIdx); + Annotation [] annoArr = new Annotation [exonList.size()]; + for (int i=0; i comp = Annotation.getExonStartComparator(); + Arrays.sort(annoArr, comp); + + Vector seqs = new Vector (exonList.size()); + int last_gene_idx = -1, s, e; + boolean isPos=true; + String geneTag="""", exon=""""; + int cnt=1; + + for (Annotation ad : annoArr) { + if (last_gene_idx!=ad.getGeneIdx()) { + last_gene_idx = ad.getGeneIdx(); + for (Annotation gd : geneList) { + if (last_gene_idx==gd.getAnnoIdx()) { + geneTag = gd.getTag(); + isPos = gd.isStrandPos(); + } + } + } + s = ad.getStart(); e = ad.getEnd(); + exon = alignPool.loadPseudoSeq(s + "":"" + e, grpID); + if (isPos) exon = SeqData.revComplement(exon); + SeqData sd = new SeqData(exon, ' ', geneTag + "" "" + cnt); + seqs.add(sd); + cnt++; + } + + return seqs; + } catch (Exception e) {ErrorReport.print(e, ""show exon""); return null;} + } + /****************************************************** + * Copied from util.Utilities.displayInfoMonoSpace to specialize + * Puts ok button in lower right + */ + public static void displayInfoMonoSpace(Component parentFrame, String title, String theSeq, boolean isModal) { + JOptionPane pane = new JOptionPane(); + + JTextArea messageArea = new JTextArea(theSeq); + + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.BOLD, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + pane.setMessage(sPane); + pane.setMessageType(JOptionPane.PLAIN_MESSAGE); + + JDialog diag = pane.createDialog(parentFrame, title); + int h = Math.min(450, sPane.getHeight()); + Dimension d = new Dimension (620, h+200); // width, height + if (sPane.getWidth() >= d.width || sPane.getHeight() >= d.height) diag.setSize(d); + + diag.setModal(isModal); + diag.setResizable(true); + diag.setVisible(true); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/AlignData.java",".java","6148","205","package symap.closeup; + +import util.ErrorReport; + +/******************************************** + * Input 2 seqs and a type (NT, AA, AAframe) + * Called from AlignPool to align subhits for closeup graphics and text align + * The caller may call: getAlignSeq1, getAlignSeq2, matchSeq + */ +public class AlignData { + private static boolean TRACE=false; + protected static final int NT=0; + protected static final int AA=1; + private static final int AAframe=2; + + protected static final char gapCh = '-'; + protected static final char stopCh = '*'; + private static final String AA_POS = ""+""; // aa pos sub + private static final String AA_NEG = "" ""; // aa neg sub + + private String alignSeq1="""", alignSeq2="""", matchSeq=""""; + private int nEndAlign=0, cntMatch=0, startOffset=0, cntGap=0, cntMis=0, cntTrimS=0, cntTrimE=0; + private boolean isNT=true; + private int alignType=0; + private String traceMsg="""", trimMsg=null; + + protected AlignData() {} + + protected boolean align(int type, String seq1, String seq2, boolean bTrim, String traceMsg) { + alignType=type; + isNT = (alignType==NT); + this.traceMsg = traceMsg; + + AlignPair ap = new AlignPair(); + if (alignType==AAframe) {} + else { + ap.DPalign(seq1, seq2, isNT); + alignSeq1 = ap.getAlignResult1(); + alignSeq2 = ap.getAlignResult2(); + + if (bTrim) trimEnds(); + + if (isNT) computeMatchNT(); + else computeMatchAA(); + } + + return true; + } + protected String getAlignSeq1() { return alignSeq1;} + protected String getAlignSeq2() { return alignSeq2;} + protected String getAlignMatch() { return matchSeq;} + + protected String getScore() { + double sim = ((double) cntMatch/(double) alignSeq1.length())*100.0; + String s = String.format(""%s %.1f"", "" DP %Id"", sim); + String m = String.format(""Match %,d"", cntMatch); + String mm = String.format(""Mismatch %,d"", cntMis); + String g = String.format(""Gap %,d"", cntGap); + String len = String.format(""Len %,d"", alignSeq1.length()); + + String t = (cntTrimS>0 || cntTrimE>0) ? ""Trim "" + cntTrimS + "","" + cntTrimE : """"; + return String.format(""%s %s %s %s %s %s"", s, len, m, mm, g, t); + } + protected int getStartOffset() {return startOffset;} + + // Trim non-match off ends + private void trimEnds() { + try { + String s1 = alignSeq1.toUpperCase(); + String s2 = alignSeq2.toUpperCase(); + + int len=alignSeq1.length()-1; + + int start=0, end=len, gapS1=0, gapE1=0, gapS2=0, gapE2=0; + + for (int i=0; i<=len; i++) { + if (s1.charAt(i)!=s2.charAt(i)) { + start++; cntTrimS++; + if (s1.charAt(i)==gapCh) gapS1++; + if (s2.charAt(i)==gapCh) gapS2++; + } + else break; + } + for (int i=len; i>=0; i--) { + if (s1.charAt(i)!=s2.charAt(i)) { + end--; cntTrimE++; + if (s1.charAt(i)==gapCh) gapE1++; + if (s2.charAt(i)==gapCh) gapE2++; + } + else break; + } + startOffset=start; + + if (start>0 || end0; i--) { + if (doSeq1 && alignSeq2.charAt(i)==gapCh) e1--; + else if (doSeq2 && alignSeq1.charAt(i)==gapCh) e2--; + else {nEndAlign=i+1; break;} + } + if (doSeq1) e1++; + if (doSeq2) e2++; + + // find first non-gap match from beginning + doSeq1=doSeq2=false; + if (alignSeq1.startsWith(gapStr)) doSeq2=true; + if (alignSeq2.startsWith(gapStr)) doSeq1=true; + if (doSeq1 && doSeq2) System.err.println(""Can't happen: "" + alignSeq1.substring(0,5) + "" "" + alignSeq2.substring(0,5)); + + int open=-10, extend=-1; + + for (int i=0; i0) return AA_POS; + else return AA_NEG; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/CloseUpDialog.java",".java","6912","201","package symap.closeup; + +import java.awt.Container; +import java.awt.Font; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.event.MouseEvent; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JDialog; +import java.sql.SQLException; +import java.util.Vector; + +import colordialog.ColorListener; +import symap.sequence.Sequence; +import symap.sequence.Annotation; +import symap.mapper.HitData; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import util.ErrorReport; + +/************************************************* + * The panel for displaying the alignment, with CloseupComponent on top and TextComponent on bottom; + * called from CloseUp, which is called by SyMAP2d + * Gets hits and genes in region, and builds the HitAlignment and GeneAlignment for display + */ +public class CloseUpDialog extends JDialog implements ColorListener, HelpListener { + private static final long serialVersionUID = 1L; + private AlignPool alignPool; + private CloseUpComponent viewComp; + private JScrollPane blastScroll, viewScroll; + private TextComponent textComp; + private HitAlignment selectedHa; + private HelpBar helpBar; + private final int MAX_WIDTH=1500; + private String projS, projO; // selected and other + + // hitList will have at least ONE hit + protected CloseUpDialog(CloseUp closeup, Vector hitList, Sequence seqObj, + int selStart, int selEnd, boolean isProj1, String otherChr, int numShow) throws SQLException { + alignPool = new AlignPool(closeup.getDrawingPanel().getDBC()); + projS = seqObj.getProjectDisplayName(); + projO = seqObj.getOtherProjectName(); + initView(); + + setView(seqObj, hitList, selStart, selEnd, isProj1); + + String d = SeqData.coordsStr(selStart, selEnd); + String other = projO + "" "" + otherChr; + String x = String.format(""Selected Region: %s %s %s to %s"", projS, seqObj.getChrName(), d, other); + setTitle(x); + + util.Jcomp.setFullSize(this,viewComp, MAX_WIDTH); + if (numShow==1) setLocationRelativeTo(null); + } + + protected int showIfHits() { + if (viewComp==null) return -1; + + int h = viewComp.getNumberOfHits(); + + if (h > 0) setVisible(true); + return h; + } + private void initView() { + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + viewComp = new CloseUpComponent(); + textComp = new TextComponent(projS, projO); + + helpBar = new HelpBar(-1, 17); + helpBar.addHelpListener(viewComp,this); + helpBar.addHelpListener(textComp,this); + + viewComp.addCloseUpListener(this); + + viewScroll = new JScrollPane(viewComp,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + blastScroll = new JScrollPane(textComp,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + viewScroll.getViewport().setBackground(viewComp.getBackground()); + blastScroll.getViewport().setBackground(textComp.getBackground()); + + Container cp = getContentPane(); + cp.setLayout(new BorderLayout()); + cp.add(viewScroll,BorderLayout.NORTH); + cp.add(blastScroll,BorderLayout.CENTER); + cp.add(helpBar, BorderLayout.SOUTH); + } + + // the subhits and exons are only shown if they are within or overlap the selected boundary + protected void setView(Sequence src, Vector hitList, int sstart, int send, boolean isProj1) throws SQLException + { + try { + HitAlignment[] hitAlignArr = alignPool.buildHitAlignments(hitList, isProj1, projS, projO, sstart, send); + + GeneAlignment[] geneAlignArr = buildGeneAlignments(src, sstart, send); + + // compute the start and end of graphics; all hits within sstart/send + int sHit = Integer.MAX_VALUE; + int eHit = Integer.MIN_VALUE; + for (HitAlignment h : hitAlignArr) { + sHit = Math.min(sHit, h.getSstart()); + eHit = Math.max(eHit, h.getAend()); // start+width + } + + int sEx = Integer.MAX_VALUE; + int eEx = Integer.MIN_VALUE; + for (GeneAlignment gn : geneAlignArr) { + if (gn.getGmax() < sHit || gn.getGmin()>eHit) { + gn.setNoShow(); + continue; + } + + gn.setDisplayExons(sstart, send); // set exons within selected + + sEx = Math.min(sEx, gn.getEmin()); + eEx = Math.max(eEx, gn.getEmax()); + } + int startGr = Math.min(sHit, sEx) - 10; // a little padding + int endGr = Math.max(eHit, eEx) + 10; + + viewComp.setData(startGr, endGr, geneAlignArr, hitAlignArr); + + selectedHa = hitAlignArr[0]; + hitAlignArr[0].setSelected(true); + hitClicked(hitAlignArr[0]); + } + catch (Exception e) {ErrorReport.print(e, ""Closeup: determining hits and exons to show"");} + } + + private GeneAlignment[] buildGeneAlignments(Sequence seq, int sstart, int send) { + Vector annoVec = seq.getAnnoGene(sstart, send); + + Vector alignments = new Vector(); + for (Annotation a : annoVec) { + Vector exons = seq.getAnnoExon(a.getAnnoIdx()); // get specific exons + + GeneAlignment ga = new GeneAlignment( + a.getCloseUpDesc(), a.getStart(), a.getEnd(), a.isStrandPos(), exons); + + if (!alignments.contains(ga)) // in case database has redundant entries (as with Rice) + alignments.add(ga); + } + + return alignments.toArray(new GeneAlignment[0]); + } + public void resetColors() { + textComp.setBackground(TextComponent.backgroundColor); + blastScroll.getViewport().setBackground(TextComponent.backgroundColor); + textComp.repaint(); + viewComp.setBackground(CloseUpComponent.backgroundColor); + viewScroll.getViewport().setBackground(CloseUpComponent.backgroundColor); + viewComp.repaint(); + } + + // modified to handle color change + protected void hitClicked(HitAlignment ha) { + if (ha != null) { + if (selectedHa != null) selectedHa.setSelected(false); + ha.setSelected(true); + selectedHa = ha; + viewComp.repaint(); // Repaint to show color change + textComp.setAlignment(ha); + getContentPane().validate(); + } + } + + public String getHelpText(MouseEvent e) { + if (e.getSource() == viewComp) return ""Click on a hit to select it and view the base alignment.""; + else if (e.getSource() == textComp) return ""Highlight text and press CTRL-C to copy.""; + else return null; + } + /*************************************************** + * Draws the text area at bottom of display with alignment + * CAS575 cleanup; was its own file + */ + private class TextComponent extends JTextArea { + private static final long serialVersionUID = 1L; + private static final Color backgroundColor = Color.white; + private static Font sequenceFont = null; + + private HitAlignment alignment; + + private TextComponent(String proj1, String proj2) { + super(); + setEditable(false); + if (sequenceFont == null) sequenceFont = new Font(Font.MONOSPACED,0,16); + + setFont(sequenceFont); + setBackground(backgroundColor); + this.alignment = null; + } + private void setAlignment(HitAlignment ha) { + alignment = ha; + setVisible(false); + selectAll(); + replaceRange(alignment.toString(), getSelectionStart(), getSelectionEnd()); + setVisible(true); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/AlignPool.java",".java","20160","548","package symap.closeup; + +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Vector; + +import database.DBconn2; +import symap.Globals; +import symap.mapper.HitData; +import util.ErrorReport; +import util.Utilities; + +/****************************************** + * 2D: CloseUp, Hit-Info AlignHit, Show Sequence, and symapQuery MSA + * AlignData/AlignPair does the dynamic programming (DP) alignment. + * This file loads the data from the database and sets it all up + * + * HitAlignment DP align for Closeup + * TextShowAlign DP align Hit for Hit Info + * TextShowSeq get sequence for Show Sequence + * Query MSA get full hit sequence or concatenated subhit for MSA align + * + * 1. Query and target are used in the pseudo_hits table + * 2. Select and Other are from the user selected sequence + * 3. isQuery determines whether the Select=Query or Select=Target + */ +public class AlignPool { + private static final boolean TRACE = false; + private static final boolean toUpper = false; + private static final boolean bTrim=Globals.bTrim; // only used for Closeup; Text align has it passed in + + private final int CHUNK_SZ = backend.Constants.CHUNK_SIZE; + private HitAlignResults curHit; // hqr for the whole current hit + + private DBconn2 dbc2; + + /************************************************************** + * Symap query MSA + */ + public AlignPool(DBconn2 dbc2){ // For SyMAPQueryFrame to use loadPseudoSeq + this.dbc2 = dbc2; + } + public String loadSeq(int pos, String indices, int grpIdx, String gapLess) { + try { + if (gapLess.equals("""")) return loadPseudoSeq(indices, grpIdx); // pseudo_seq2 is index by grpIdx only + + // process subhits + String subhitstr = loadSubHitStr(pos, gapLess); // reads pseudo_hits - + if (subhitstr==null) return loadPseudoSeq(indices, grpIdx); // shouldn't happen + + // Merge overlapping subhits + String [] subhits = subhitstr.split("",""); + int [] start = new int [subhits.length]; + int [] end = new int [subhits.length]; + for (int i=0; i0) end[i-1] = coords[1]; // merge; start[i] remains -1 + else { + start[i] = coords[0]; + end[i] = coords[1]; + } + s2 = coords[0]; e2 = coords[1]; + } + + // load sequence + String mgSeq=""""; + for (int i=0; i hitList, + boolean isQuery, String projS, String projO, int selStart, int selEnd) + { + return computeHitAlign(hitList, isQuery, projS, projO, true, selStart, selEnd, bTrim); // use -a trim + } + // Called from TextPopup + protected synchronized HitAlignment[] buildHitAlignments(Vector hitList, boolean isNT, boolean isQuery, boolean isTrim) + { + return computeHitAlign(hitList, isQuery, """", """", isNT, -1, -1, isTrim); + } + // Called from TextPopup + protected synchronized HitAlignment[] getHitReverse(HitAlignment [] halign) + { + return computeHitReverse(halign); + } + // Called from TextShowSeq + protected Vector getHitSequence (Vector hitList, int grpID, boolean isQuery, boolean bRev) + { + return createHitSequence(hitList, grpID, isQuery, bRev); + } + + /************************************************************************ + * Computations for CloseUp and TextPopup + */ + private HitAlignment[] computeHitAlign(Vector hitList, + boolean isSwap, String projS, String projO, boolean isNT, int sStart, int sEnd, boolean isTrim) { + try { + // make sorted hitArr from hitList + HitData[] hitArr = new HitData [hitList.size()]; + for (int i=0; i comp = HitData.sortByStart2(); + Arrays.sort(hitArr, comp); + + // for each hit from selected region + Vector hitAlign = new Vector (); + + for (HitData hitObj : hitArr) { + curHit = loadHitForAlign(hitObj, isSwap); + + if (curHit==null) return null; + + // for each subhit; + int num=curHit.selectIndices.length; + for (int i = 0; i < num; i++) { + int subStart = extractStart(curHit.selectIndices[i]); + int subEnd = extractEnd(curHit.selectIndices[i]); + if (sStart!=-1 && sEnd != -1) { + if (!Utilities.isOverlap(sStart, sEnd, subStart, subEnd)) continue; + } + // Do Alignment + HitAlignResults subHit = alignSubHit(i, isNT, subStart, subEnd, isTrim); + + HitAlignment ha = new HitAlignment(hitObj, projS, projO, + new SeqData(subHit.selectSeq, subHit.selectAlign, curHit.strand.charAt(0)), + new SeqData(subHit.otherSeq, subHit.otherAlign, curHit.strand.charAt(2)), + new SeqData(subHit.matchAlign, ' '), + subHit.selectStart, subHit.selectEnd, + subHit.otherStart, subHit.otherEnd, + subHit.alignLength, subHit.offset, + subHit.scoreStr, (i+1)+""/""+num); + + hitAlign.add(ha); + } + } + return (HitAlignment[]) hitAlign.toArray(new HitAlignment[0]); + } catch (Exception e) {ErrorReport.print(e, ""getHitAlignments""); return null; } + } + /******************************************************************************/ + private synchronized HitAlignment[] computeHitReverse(HitAlignment [] halign) { + Vector alignments = new Vector (); + + for (int i=0; i createHitSequence (Vector hitList, + int grpID, boolean isQuery, boolean bRev) { + try { + Vector hitVec = new Vector (); + + // make sorted hitArr from hitList + HitData[] hitArr = new HitData [hitList.size()]; + for (int i=0; i comp = HitData.sortByStart2(); + Arrays.sort(hitArr, comp); + + // for each hit from selected region + for (HitData hitObj : hitArr) { + curHit = loadHitForSeq(hitObj, grpID, isQuery); + + // for each subhit, extract subsequence + int num=curHit.selectIndices.length; + for (int i = 0; i < num; i++) { + // make query sub-sequence + int qStart = extractStart(curHit.selectIndices[i]); // [0] s1:e1 [1] s2:e2, etc; get i[0] + int qEnd = extractEnd(curHit.selectIndices[i]); + + int startOfs = qStart - curHit.selectStart; // relative to beginning + int endOfs = qEnd - curHit.selectStart; + String strQuery = curHit.selectSeq.substring(startOfs, endOfs+1); + if (toUpper) strQuery = strQuery.toUpperCase(); + char strand = curHit.strand.charAt(0); + String rc=""""; + if (strand == '-') { + if (!bRev) { + strQuery = SeqData.revComplement(strQuery); + rc="" RC""; + } + } + else if (bRev) { + strQuery = SeqData.revComplement(strQuery); + rc="" RC""; + } + + String coords = SeqData.coordsStr(strand, qStart, qEnd); + String header = hitObj.getName() + ""."" + (i+1)+""/""+num + "" "" + coords + rc; + SeqData sd = new SeqData(strQuery, qStart, strand, header); + hitVec.add(sd); + } + } + Collections.sort(hitVec); + return hitVec; + } catch (Exception e) {ErrorReport.print(e, ""align hit""); return null;} + } + /************************************************************************ + * Database calls + */ + /*************************************************************************** + * Load the hit info and subhit target/query sequence + * Coords for subhits are relative to forward strand + */ + private HitAlignResults loadHitForAlign(HitData hitData, boolean isQuery) { + ResultSet rs = null; + curHit = new HitAlignResults(); + + // Note that target_seq and query_seq refer to indices of sequence segments not the sequences themselves. + String query = ""SELECT h.strand, h.query_seq, h.target_seq, h.grp1_idx, h.grp2_idx, h.hitnum "" + + ""FROM pseudo_hits AS h WHERE h.idx="" + hitData.getID(); + try { + rs = dbc2.executeQuery(query); + if (!rs.next()) { + System.err.println(""Major SyMAP error reading database""); + return null; + } + curHit.strand = rs.getString(1); + if (curHit.strand == null || curHit.strand.length() < 3) { + System.err.println(""Invalid strand value '"" + curHit.strand + ""' for hit idx="" + hitData.getID()); + curHit.strand = ""+/+""; + } + + String query_seq = rs.getString(2); // string list of sub-block start/end values + String target_seq = rs.getString(3); // string list of sub-block start/end values + int grp1_idx = rs.getInt(4); + int grp2_idx = rs.getInt(5); + curHit.hitnum = rs.getInt(6); + + int start1 = (isQuery) ? hitData.getStart1() : hitData.getStart2(); + int end1 = (isQuery) ? hitData.getEnd1() : hitData.getEnd2(); + int start2 = (isQuery) ? hitData.getStart2() : hitData.getStart1(); + int end2 = (isQuery) ? hitData.getEnd2() : hitData.getEnd1(); + + if (!isQuery) { + String strTemp = query_seq; + query_seq = target_seq; + target_seq = strTemp; + + int nTemp = grp1_idx; + grp1_idx = grp2_idx; + grp2_idx = nTemp; + + curHit.strand = reverseStrand(curHit.strand); // swap x/y + } + + // No indices if one hit, so create indices for whole hit + if (query_seq == null || query_seq.length() == 0 || target_seq == null || target_seq.length() == 0){ + query_seq = start1 + "":"" + end1; + target_seq = start2 + "":"" + end2; + } + + // Get sequences of select and other covering merged hits + curHit.isSelNeg = (curHit.strand.charAt(0) == '-'); // -/? + curHit.selectIndices = query_seq.split("",""); + curHit.selectStart = start1; + curHit.selectSeq = loadPseudoSeq(start1 + "":"" + end1, grp1_idx); + + curHit.isOthNeg = (curHit.strand.charAt(2) == '-'); // ?/- + curHit.otherIndices = target_seq.split("",""); + curHit.otherStart = start2; + curHit.otherSeq = loadPseudoSeq(start2 + "":"" + end2, grp2_idx); + } + catch (Exception e) {ErrorReport.print(e, ""Acquiring alignment""); } + return curHit; + } + /********************************* + * indices is start:end; also called directly from TextShowSeq + */ + protected String loadPseudoSeq(String indices, int grpIdx) { + ResultSet rs = null; + String pseudoSeq = """"; + + try { + // Java and MUMmer are zero based but mysql is 1 based, add one + int start = extractStart(indices) + 1; + int end = extractEnd(indices) + 1; + if (start == -1 || end == -1) return """"; + + if (start > end) { + int temp = start; + start = end; + end = temp; + } + + String query2=""""; + long count = end - start + 1; + long chunk = start / CHUNK_SZ; + String seq; + start = start % CHUNK_SZ; + if (start>0) start--; // -1 =translate like MUMmer show_align AA output (it seems to do 6-frame and pick best) + end = end % CHUNK_SZ; + + while (count > 0) { + query2 = ""SELECT SUBSTRING(seq FROM "" + start + "" FOR "" + count + "") "" + + ""FROM pseudo_seq2 AS s WHERE s.grp_idx="" + grpIdx + "" AND s.chunk="" + chunk; + + rs = dbc2.executeQuery(query2); + if (rs.next()) { + seq = rs.getString(1); + pseudoSeq += seq; + count -= seq.length(); // account for start offset + end -= seq.length(); + start = 1; + chunk++; + } + else break; + } + if (pseudoSeq.equals("""")) { + String msg=""Could not read sequence for "" + indices + "" may be wrong alignment files loaded.""; + ErrorReport.print(msg); + return """"; + } + return pseudoSeq; + } + catch (Exception e) {ErrorReport.print(e, ""Getting sequence data""); return """";} + } + /******************************************************* + * For getSeq Get subhit query only and get isSwap from grpID + * HitData is from Mapper + */ + private HitAlignResults loadHitForSeq(HitData hitData, int grpID, boolean isQuery) { + ResultSet rs = null; + curHit = new HitAlignResults(); + + // Note that target_seq and query_seq refer to indices of sequence segments not the sequences themselves. + String query = ""SELECT h.strand, h.query_seq, h.target_seq, h.grp1_idx, h.grp2_idx "" + + ""FROM pseudo_hits AS h WHERE h.idx="" + hitData.getID(); + + try { + rs = dbc2.executeQuery(query); + if (!rs.next()) { + System.err.println(""Major SyMAP error reading database""); + return null; + } + curHit.strand = rs.getString(1); + if (curHit.strand == null || curHit.strand.length() < 3) { + System.err.println(""Invalid strand value '"" + curHit.strand + ""' for hit idx="" + hitData.getID()); + curHit.strand = ""+/+""; + } + + String query_seq = rs.getString(2); // string list of sub-block start/end values + String target_seq = rs.getString(3); // string list of sub-block start/end values + + int start1 = (isQuery) ? hitData.getStart1() : hitData.getStart2(); + int end1 = (isQuery) ? hitData.getEnd1() : hitData.getEnd2(); + + if (!isQuery) { + query_seq = target_seq; + curHit.strand = reverseStrand(curHit.strand); + } + // No indices if one hit, so create indices for whole hit + if (query_seq == null || query_seq.length() == 0 || target_seq == null || target_seq.length() == 0){ + query_seq = start1 + "":"" + end1; + } + + // Get sequence covering to merged hits + curHit.selectIndices = query_seq.split("",""); + curHit.selectStart = start1; + curHit.selectSeq = loadPseudoSeq(start1 + "":"" + end1, grpID); + } + catch (Exception e) {ErrorReport.print(e, ""Acquiring alignment""); } + + return curHit; + } + // Query MSA + private String loadSubHitStr(int pos, String gapLess) { + try { + String [] tok = gapLess.split("";""); // pseudo_hits needs all of these to be unique since no hitIdx + String where = "" FROM pseudo_hits where hitNum="" + tok[0] + "" and grp1_idx="" + tok[1] + "" and proj1_idx="" + tok[2] + + "" and grp2_idx="" + tok[3] + "" and proj2_idx="" + tok[4]; + if (pos==0) { + ResultSet rs = dbc2.executeQuery(""SELECT query_seq "" + where); + if (rs.next()) return rs.getString(1); + } + else { + ResultSet rs = dbc2.executeQuery( ""SELECT target_seq "" + where); + if (rs.next()) return rs.getString(1); + } + Globals.eprt(""Load indices: "" + where); + return null; + } + catch (Exception e) {ErrorReport.print(e, ""Subhit string""); return """";} + } + /******************************************************************/ + private String reverseStrand(String s) { // used to reverse +/- or -/+ + return new StringBuffer(s).reverse().toString(); + } + private int extractStart(String range) {return extractInt(range)[0];} + private int extractEnd(String range) {return extractInt(range)[1];} + + private int[] extractInt(String range) { + String tokens[] = range.split("":""); + if (tokens.length != 2) return null; + + int[] out = new int[2]; + out[0] = Integer.parseInt(tokens[0]); + out[1] = Integer.parseInt(tokens[1]); + return out; + } + + /******************************************************** + * One hqr for current hit, and one for each subhit for alignment, transferred to HitAlignment class + */ + static class HitAlignResults { + private boolean isSelNeg, isOthNeg; + private String strand; + + private int selectStart, selectEnd; + private int otherStart, otherEnd; + private int alignLength, offset; + + private String selectSeq, otherSeq; + private String selectAlign=null, otherAlign=null, matchAlign; + + private String[] selectIndices, otherIndices; + private String scoreStr; + private int hitnum; // for tracing + + protected HitAlignResults() {} + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/SeqData.java",".java","10185","308","package symap.closeup; + +import java.util.Arrays; +import java.util.Vector; + +import util.ErrorReport; + +/*************************************************************** + * This is a minor class for displaying aligned text data, manipulating data and formatting text + */ +public class SeqData implements Comparable { + private static final byte DASH = AlignData.gapCh; + + private byte[] alignSeq; + private int realLength; + private char strand; + + private String seqHeader; + private String seqStr; // not aligned + private int start=0; + + // graphic and text align + protected SeqData(String seq, String alignSeq, char strand) { + this.alignSeq = (alignSeq == null) ? new byte[0] : alignSeq.getBytes(); + this.seqStr = seq; + this.strand = strand; + realLength = getRL(this.alignSeq,0,this.alignSeq.length); + } + // reverse align + protected SeqData(String seq, char strand) { + this.alignSeq = (seq == null) ? new byte[0] : seq.getBytes(); + this.strand = strand; + realLength = getRL(this.alignSeq,0,this.alignSeq.length); + } + + // show seq + protected SeqData (String seq, int start, char strand, String header) { + this.seqStr = seq; + this.start = start; + this.strand = strand; + this.seqHeader = header; + } + protected SeqData (String seq, char strand, String header) { + this.seqStr = seq; + this.strand = strand; + this.seqHeader = header; + } + protected char getStrand() {return strand;} + protected String getHeader() {return seqHeader;} + protected String getSeq() {return seqStr;} + + public boolean equals(Object obj) { + return obj instanceof SeqData && Arrays.equals(alignSeq,((SeqData)obj).alignSeq); + } + public int compareTo(SeqData a){ + return start - a.start; + } + public String toString() {return new String(alignSeq);} + + /************************************************ + * Static calls + */ + private static int getRL(byte[] seq, int i, int len) {// real length + int r; + for (r = 0; i < len; ++i) + if (seq[i] != DASH) ++r; + return r; + } + // these two are used by all methods that display coords + protected static String coordsStr(int start, int end) { + return String.format(""%,d - %,d (%,dbp)"", start, end, (end-start+1)) ; + } + protected static String coordsStr(char o, int start, int end) { + return String.format(""%c(%,d - %,d) %,dbp"", o, start, end, (end-start+1)) ; + } + public static String coordsStr(boolean isStrandPos, int start, int end) { + String o = (isStrandPos) ? ""+"" : ""-""; + return String.format(""%s(%,d - %,d) %,dbp"", o, start, end, (end-start+1)) ; + } + public static String coordsStrKb(boolean isStrandPos, int start, int end) { + String o = (isStrandPos) ? ""+"" : ""-""; + double s = (start<1000000) ? start : Math.round(start/1000); + String xs = (start<1000000) ? """" : ""KB""; + int len = (end-start+1); + double l = (len<1000) ? len : Math.round(len/1000); + String xl = (len<1000) ? ""bp"" : ""KB""; + + return String.format(""%s%,d%s for %,d%s"", o, (int) s, xs, (int)l, xl) ; + } + + /********************************************************** + // these 3 methods are used to closeup.HitAlignment + **********************************************************/ + protected static double[] getQueryMisses(SeqData qs, SeqData ts) { + try { + Vector miss = new Vector(); + double size = (double)ts.realLength; + int pos = 0, prev = -1, i; + + for (i = 0; i < qs.alignSeq.length; ++i) { + byte b1 = toUpperCase(qs.alignSeq[i]); + byte b2 = toUpperCase(ts.alignSeq[i]); + if (b1 != b2 && qs.alignSeq[i] != DASH && ts.alignSeq[i] != DASH) { + if (pos != prev) { + miss.add((double)pos/(double)size); + prev = pos; + } + } + if (ts.alignSeq[i] != DASH) ++pos; + } + double[] ret = new double[miss.size()]; + for (i = 0; i < ret.length; ++i) ret[i] = miss.get(i); + + return ret; + } + catch (Exception e) { + ErrorReport.die(e, ""getQueryMisses ""+ qs.alignSeq.toString() + ""\n"" + ts.alignSeq.toString()); + return null; + } + } + + private static final byte UPPER_CASE_OFFSET = 'A' - 'a'; + private static byte toUpperCase(byte b) { + if (b < 'a' || b > 'z') return b; + return (byte) (b + UPPER_CASE_OFFSET); + } + + protected static double[] getQueryInserts(SeqData qs, SeqData ts) { + try { + Vector ins = new Vector (); + double size = (double)ts.realLength; + int pos = 0, prev = -1, i; + + for (i = 0; i < qs.alignSeq.length; ++i) { + if (ts.alignSeq[i] == DASH) { + if (pos != prev) { + ins.add((double)pos/(double)size); + prev = pos; + } + } + else ++pos; + } + double[] ret = new double[ins.size()]; + for (i = 0; i < ret.length; ++i) ret[i] = ins.get(i); + return ret; + } + catch (Exception e) { + ErrorReport.die(e, ""getQueryInserts\n"" + qs.alignSeq.toString() + ""\n"" + ts.alignSeq.toString()); + return null; + } + } + + protected static double[] getQueryDeletes(SeqData qs, SeqData ts) { + try { + Vector dels = new Vector(); + double size = (double)ts.realLength; + int pos = 0, prev = -1, i; + + for (i = 0; i < qs.alignSeq.length; ++i) { + if (qs.alignSeq[i] == DASH) { + if (pos != prev) { + dels.add((double)pos/(double)size); + prev = pos; + } + } + if (ts.alignSeq[i] != DASH) ++pos; + } + double[] ret = new double[dels.size()]; + for (i = 0; i < ret.length; ++i) ret[i] = dels.get(i); + + return ret; + } + catch (Exception e) { + ErrorReport.die(e, ""getQueryDeletes\n"" + qs.alignSeq.toString() + ""\n"" + ts.alignSeq.toString()); + return null; + } + } + /***************************************************** + * XXX DNA string + */ + // handle reverse complement of sequences for database changes + public static String revComplement(String seq) { + if (seq == null) return null; + + StringBuffer retStr = new StringBuffer(seq.length()); + int i; + for (i = 0; i < seq.length(); i++) { + char c = seq.charAt(i); + switch (c) { + case 'A': retStr.append(""T""); break; + case 'a': retStr.append(""t""); break; + case 'T': retStr.append(""A""); break; + case 't': retStr.append(""a""); break; + case 'G': retStr.append(""C""); break; + case 'g': retStr.append(""c""); break; + case 'C': retStr.append(""G""); break; + case 'c': retStr.append(""g""); break; + default: retStr.append(""N""); // anything nonstandard gets an N + } + } + retStr = retStr.reverse(); + return retStr.toString(); + } + + /****************************************************************/ + protected static String translate(String seq) { + try { + String aaSeq=""""; + for (int i=0; i=0 && seqSeqs[x].charAt(seqStops[x])==gap; + seqStops[x]--); + + dSeqStartf = Math.max(dSeqStartf, getTextWidth(seqNames[x])); + nMaxIndexf = Math.max(nMaxIndexf, seqSeqs[x].length()); + seqSelected[x] = false; + } + columnSelected = new boolean[nMaxIndexf]; + for(int x=0; x= 0 && xPos < columnSelected.length) { + highlightChanged = true; + if (!e.isControlDown() && !e.isShiftDown()) selectNoColumns(); + columnSelected[xPos] = !columnSelected[xPos]; + } + } + // Determine the row for the click. + if (topSelect[0] <= pt.y && pt.y <= bottomSelect[bottomSelect.length-1]){ + highlightChanged = true; + if (!e.isControlDown() && !e.isShiftDown()) selectNoRows(); + + for(int x=0; x dXMin) + drawVerticalText(g2, String.valueOf(i), dX, dY); + } + } + private void drawText(Graphics2D g2, String str, double dXLeft, double dYTop, Color theColor){ + if (str.length()==0) return; + + g2.setColor(theColor); + + TextLayout layout = new TextLayout(str, theFont, g2.getFontRenderContext()); + float fBaseline = (float)(dYTop + dFontAscent); + layout.draw(g2, (float)dXLeft, fBaseline); + } + + private void drawText(Graphics2D g2, String str, double dX, double dY){ + drawText(g2, str, dX, dY, Color.BLACK); + } + // Positioned by the center of the left side + private void drawVerticalText(Graphics2D g2, String str, double dX, double dY){ + if (str.length() == 0) return; + + TextLayout layout = new TextLayout(str, theFont, g2.getFontRenderContext()); + g2.rotate(- Math.PI / 2.0); + g2.setColor(Color.BLACK); + float fHalf = (float)(layout.getBounds().getHeight() / 2.0f); + layout.draw(g2, (float)-dY, (float)dX + fHalf); + g2.rotate(Math.PI / 2.0); + } + /**************************************************************************** + * Draw/write sequences + */ + private void drawSequence(Graphics2D g2, String label, String sequence, double dYTop, double dYBottom){ + if (nDrawMode == GRAPHICMODE) + drawSeqLine(g2, label, sequence, dYTop, dYBottom); + else + writeSeqLetters(g2, label, sequence, dYTop, dYBottom); + } + private void writeSeqLetters(Graphics2D g2,String label,String seq, double dYTop, double dYBottom) { + double dWriteBaseline = (dYBottom - dYTop) / 2 - dFontMinHeight / 2 + dYTop + dFontAscent; + + g2.setColor(Color.black); + + // Draw the columns of bases that are currently visible + int nStart = 0; + int nEnd = seq.length(); + + for(int i = nStart; i < nEnd; i++){ + double dX = calcWriteX(i); + + Color baseColor = Color.black; + if (isDNA) { + if (getIsNAt(seq, i)) baseColor = unkPurple; + else if (getIsGapAt(seq, i)) baseColor = darkGreen; + else if (getIsLowQuality(seq, i)) baseColor = lowQuality; + else if (getIsMismatchAt(seq, i)) baseColor = mismatchRed; + } + else { + if (getIsStop(seq, i)) baseColor = Color.gray; + else if (getIsNAt(seq, i)) baseColor = mediumGray; + else if (getIsSubAt(seq, i)) baseColor = purple; + else if (getIsGapAt(seq, i)) baseColor = darkGreen; + else if (getIsMismatchAt(seq, i)) baseColor = mismatchRed; + } + drawCenteredBase(g2, seq.charAt(i), baseColor, dX, dWriteBaseline); + } + } + private void drawSeqLine(Graphics2D g2,String label,String seq,double dYTop, double dYBottom){ + //Find the locations of the start and stop + int startGapEnd = 0; + int endGapStart = seq.length(); + while (startGapEnd0 && seq.charAt(endGapStart-1) == gap) endGapStart--; + + // Determine the position of the sequence line, but don't draw until after the hashes + double dXPosStart = calcDrawX(startGapEnd); + double dXPosEnd = calcDrawX(endGapStart); + + double dHeight = dYBottom - dYTop; + double dYCenter = dHeight / 2.0 + dYTop; + + int RED_HASH = (int)(dHeight/2) - 2; + int GREEN_HASH = RED_HASH - 1; + int GRAY_HASH = GREEN_HASH - 2; + int BLUE_HASH = GREEN_HASH - 2; + + // Draw column at at time + for(int i = startGapEnd; i < endGapStart;){ + double dHashXPos = calcDrawX(i); + + boolean bGreenHash=false, bRedHash=false, bGreyHash=false; + boolean bBlueStopHash=false, bBlueHash=false, bPurpleHash=false; + + // multiple bases are represented together; if any true, then it gets the hash + for (int j=0; iseqStops[0]) return true; + return false; + } + + private boolean getIsSubAt(String seq, int nPos) { // sub both strands + return !isDNA && seqSeqs[0].charAt(nPos) != seq.charAt(nPos) + && MsaRun.isCommonAcidSub(seqSeqs[0].charAt(nPos), seq.charAt(nPos)); + } + /*--- For letters ------------*/ + private void drawCenteredBase(Graphics2D g2, char chBase, Color theColor, double dCellLeft, double dBaseline){ + g2.setColor(theColor); + + String str = """" + chBase; + TextLayout layout = new TextLayout(str, theFont, g2.getFontRenderContext()); + Rectangle2D bounds = layout.getBounds(); + float fCharWidth = (float)bounds.getWidth(); + + // Adjust x draw position to center the character in its rectangle + float fX = (float)dCellLeft + (float)(dFontCellWidth - 1.0f) / 2.0f - fCharWidth / 2.0f; + + layout.draw(g2, fX, (float)dBaseline); + + g2.setColor(Color.black); + } + private void drawArrowHead(Graphics2D g2, double dArrowPntX, double dArrowPntY, double dHeight, boolean bRight){ + final double ARROW_WIDTH = dHeight - 1; + + double dYStartTop = dArrowPntY - dHeight; + double dYStartBottom = dArrowPntY + dHeight; + double dXStart = dArrowPntX; + + if (bRight) dXStart -= ARROW_WIDTH; + else dXStart += ARROW_WIDTH; + + g2.draw(new Line2D.Double(dXStart, dYStartTop, dArrowPntX, dArrowPntY)); + g2.draw(new Line2D.Double(dXStart - 1, dYStartTop, dArrowPntX - 1, dArrowPntY)); + g2.draw(new Line2D.Double(dXStart, dYStartBottom, dArrowPntX, dArrowPntY)); + g2.draw(new Line2D.Double(dXStart - 1, dYStartBottom, dArrowPntX - 1, dArrowPntY)); + } + /********************************************************************/ + private double getFrameWidth(){ + double dWidth = dSeqStartf + getSequenceWidth() + nInsetGap; + return Math.max(700, dWidth); + } + private double getFrameRight() { + return nLeftGap + getFrameWidth(); + } + private void selectAllRows() { + for(int x=0; x { + private static final double EXON_HEIGHT = CloseUpComponent.EXON_HEIGHT; // 12 + private static final double INTRON_HEIGHT = CloseUpComponent.INTRON_HEIGHT;// 2; + + private String desc; + private int gStart, gEnd; // gene start and end + private boolean isReverse, isForward, bShow=true; + + private int eStart, eEnd; // only show exons in selected/hit area + private Exon[] exons; + + private int startGr = Integer.MIN_VALUE, endGr = Integer.MAX_VALUE; // start and end of graphics + private Rectangle2D.Double bounds = new Rectangle2D.Double(); + private ArrowLine geneLine; + + protected GeneAlignment(String name, int start, int end, boolean forward, Vector e) { + if (name != null) + name = name.replaceAll(""=http://\\S+;"", "" "").replaceAll("";"", "" ""); + + this.desc = name; + this.gStart = start; + this.gEnd = end; + this.isReverse = (start>end); // in DB, startee) arrow = ArrowLine.BOTH_ARROWS; + else if (sgee) arrow = ArrowLine.RIGHT_ARROW; + + geneLine = new ArrowLine(); + geneLine.setBounds(gbounds, CloseUpComponent.INTRON_HEIGHT, CloseUpComponent.GARROW_DIM, arrow); + } + + protected void paint(Graphics2D g2, FontMetrics fm, Color fontColor, double vertFontSpace) { + if (!bShow) return; + + if (!paintGene(g2, fm, fontColor, vertFontSpace)) return; + + // paint name + if (desc == null || desc.length() == 0) return; + + String s = desc; + if (desc.length() > 100) s = desc.substring(0,100) + ""...""; + + double x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2.0; + double y = bounds.y - vertFontSpace; + g2.setPaint(fontColor); + g2.setFont(fm.getFont()); + g2.drawString(s, (float)x, (float)y); + } + + private boolean paintGene(Graphics2D g2, FontMetrics fm, Color fontColor, double vertFontSpace) { + g2.setPaint(CloseUpComponent.intronColor); + g2.draw(geneLine); + g2.fill(geneLine); + + double bpPerPixel = getExonLength(startGr,endGr)/bounds.width; + int startBP = getStartExon(startGr); + int endBP = getEndExon(endGr); + double endX = bounds.x + bounds.width; + + if (gEnd < startBP) return false; + + ExonBox exon = new ExonBox(); + Rectangle2D.Double exonBounds = new Rectangle2D.Double(); + + exonBounds.x = bounds.x; + exonBounds.width = bounds.width; + exonBounds.y = bounds.y + (bounds.height - INTRON_HEIGHT) / 2.0; + exonBounds.height = INTRON_HEIGHT; + + if (exons.length > 0) { + if (exons[0].start <= startBP) { + exonBounds.x = bounds.x + exons[0].getEnd(startBP,endBP,bpPerPixel); + exonBounds.width = endX - exonBounds.x; + } + if (exons[exons.length-1].end >= endBP) { + exonBounds.width = bounds.x+exons[exons.length-1].getStart(startBP,bpPerPixel) - exonBounds.x; + } + } + if (exonBounds.x < bounds.x) { + exonBounds.width = exonBounds.width - (bounds.x - exonBounds.x); + exonBounds.x = bounds.x; + } + if (exonBounds.x + exonBounds.width > endX) { + exonBounds.width = endX - exonBounds.x; + } + + // draw all exons over black line + Color c = (isForward) ? CloseUpComponent.exonColorP : CloseUpComponent.exonColorN; + g2.setPaint(c); + exonBounds.y = bounds.y + (bounds.height - EXON_HEIGHT) / 2.0; + exonBounds.height = EXON_HEIGHT; + + for (int i = 0; i < exons.length; ++i) { + exonBounds.x = bounds.x + exons[i].getStart(startBP, bpPerPixel); + exonBounds.width = exons[i].getWidth(startBP, endBP, bpPerPixel); + + if (exonBounds.width > 0) { + exon.setBounds(exonBounds); + g2.draw(exon); + g2.fill(exon); + } + } + // add exon tag + g2.setPaint(fontColor); + g2.setFont(fm.getFont()); + double y = bounds.y + EXON_HEIGHT*2; + + for (int i = 0; i < exons.length; ++i) { + if (!exons[i].bShow) continue; + + double width = exons[i].getWidth(startBP, endBP, bpPerPixel); + if (width>0) { + String tag = exons[i].tag; + double x = bounds.x + exons[i].getStart(startBP, bpPerPixel); + x += (width - fm.stringWidth(tag)) / 2.0; + + g2.drawString(tag, (float)x, (float)y); + } + } + + return true; + } + + protected double getWidth(double bpPerPixel, int minStartBP, int maxEndBP) { + return getExonLength(minStartBP,maxEndBP) / bpPerPixel; + } + + protected double getX(int startG, double pixelStart, double bpPerPixel) { + return (getStartExon(startG)-startG)/bpPerPixel + pixelStart; + } + + private double getgX(int startGr, double pixelStart, double bpPerPixel) { + int start = Math.max(!isReverse ? gStart : gEnd, startGr); + return (start-startGr)/bpPerPixel + pixelStart; + } + private int getGeneLength(int paintStart, int paintEnd) { + int end = Math.min(!isReverse ? gEnd : gStart, paintEnd); + int start = Math.max(!isReverse ? gStart : gEnd, paintStart); + return Math.max(end-start, 0); + } + + protected int getGmin() { return isReverse ? gEnd : gStart; } + protected int getGmax() { return isReverse ? gStart : gEnd; } + protected int getEmin() { return isReverse ? eEnd : eStart; } + protected int getEmax() { return isReverse ? eStart : eEnd; } + + private int getStartExon(int paintStart) { + return Math.max(!isReverse ? eStart : eEnd, paintStart); + } + private int getEndExon(int paintEnd) { + return Math.min(!isReverse ? eEnd : eStart, paintEnd); + } + private int getExonLength(int paintStart, int paintEnd) { + return Math.max(getEndExon(paintEnd) - getStartExon(paintStart),0); + } + private int getFirstExon() { return !isReverse ? eStart : eEnd; } + + public int compareTo(GeneAlignment ga) { + return getFirstExon() - ga.getFirstExon(); + } + public boolean equals(Object obj) { + if (obj instanceof GeneAlignment) { + GeneAlignment g = (GeneAlignment)obj; + return (desc == null || desc.equals(g.desc)) && gStart == g.gStart && gEnd == g.gEnd; + } + return false; + } + public String toString() { return ""Gene ""+desc+"" ""+gStart+""-""+gEnd; } + + /******************************************************************* + * Holds the exon coordinates for the gene drawn in GeneAlignment + */ + protected class Exon implements Comparable { + private int start; + private int end; + private String tag; + private boolean bShow=true; + + protected Exon(int start, int end, String tag) { + if (start > end) { + int temp = start; + start = end; + end = temp; + } + this.start = start; + this.end = end; + this.tag = tag; + } + private double getStart(int startBP, double bpPerPixel) { + if (start <= startBP) return 0; + return (start - startBP)/bpPerPixel; + } + private double getWidth(int startBP, int endBP, double bpPerPixel) { + int x = (end > endBP) ? endBP : end; + int y = (start < startBP) ? startBP : start; + return Math.max((x-y)/bpPerPixel, 0); + } + private double getEnd(int startBP, int endBP, double bpPerPixel) { + if (end < startBP) return 0; + int x = (end > endBP) ? endBP : end; + return (x - startBP)/bpPerPixel; + } + private Exon translate(int s, int e) { + if (s <= e) return this; + start = s-end+e; + end = s-start+e; + return this; + } + public boolean equals(Object obj) { + if (obj instanceof Exon) { + Exon e = (Exon)obj; + return e.start == start && e.end == end; + } + return false; + } + public String toString() {return tag + "" "" +start+""-""+end;} + public int compareTo(Exon e) {return start - e.start;} + } + /**************************************************************************** + * ExonBox; + */ + protected class ExonBox implements Shape { + private DoublePolygon poly; + + private ExonBox() {poly = new DoublePolygon();} + + public void setBounds(Rectangle2D bounds) { + poly.reset(); + poly.addPoint(bounds.getX(),bounds.getY()); + poly.addPoint(bounds.getX(),bounds.getY() + bounds.getHeight()); + poly.addPoint(bounds.getX()+bounds.getWidth(), bounds.getY() + bounds.getHeight()); + poly.addPoint(bounds.getX()+bounds.getWidth(), bounds.getY()); + } + + public boolean contains(double x, double y) {return poly.contains(x,y);} + public boolean contains(double x, double y, double w, double h) {return poly.contains(x,y,w,h);} + public boolean contains(Point2D p) {return poly.contains(p);} + public boolean contains(Rectangle2D r) {return poly.contains(r);} + public Rectangle getBounds() {return poly.getBounds();} + public Rectangle2D getBounds2D() {return poly.getBounds2D();} + public PathIterator getPathIterator(AffineTransform at) {return poly.getPathIterator(at);} + public PathIterator getPathIterator(AffineTransform at, double flatness) {return poly.getPathIterator(at,flatness);} + public boolean intersects(double x, double y, double w, double h) {return poly.intersects(x,y,w,h);} + public boolean intersects(Rectangle2D r) {return poly.intersects(r);} + + private class DoublePolygon extends Polygon { + public DoublePolygon() {super();} + public void addPoint(double x, double y) { + super.addPoint((int)Math.round(x),(int)Math.round(y)); + } + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/AlignPair.java",".java","19898","515","package symap.closeup; + +/** + * The DPalign method perform dynamic programming; called by AlignPair + * The methods getHorzResult and getVertResult build and scored the aligned sequences + */ +public class AlignPair +{ + private final char stopCh = AlignData.stopCh; + private final char gapCh = AlignData.gapCh; + private float matchScore = 1.8f; + private float mismatchScore = -1.0f; + private float gapOpen = 7.0f; // 4.0f; // 3.0f changed to negative in code + private float gapExtend = 0.7f; // 0.5f; // 0.7f + private boolean bFreeEndGaps = true; // semi-global; don't penalize gaps at ends + private boolean bUseAffineGap = true; + + protected boolean DPalign ( String strHorz, String strVert, boolean dna ) { + strGapHorz=strGapVert=null; + isDNA = dna; + + if (bUseAffineGap) return matchAffine( strHorz, strVert ); + else return matchNonAffine( strHorz, strVert ); + } + protected String getAlignResult1 ( ) { + if (strGapHorz==null) buildOutput ( gapCh ); + return strGapHorz; + } + protected String getAlignResult2 () { + if (strGapVert==null) buildOutput ( gapCh ); + return strGapVert; + } + + // Build strGapHorz and strGapVert which have inserted gaps + private void buildOutput ( char chGap ) { + if ( bUseAffineGap ) buildAffineOutput ( chGap ); + else buildNonAffineOutput ( chGap ); + + score(chGap); + } + /** + * Shared Routines for affine and non-affine dynamic programming + */ + private float cmp(char x, char y) { + if (isDNA) { + if (Character.toUpperCase(x)==Character.toUpperCase(y)) return matchScore; + else return mismatchScore; + } + return (float) getBlosum(x,y); + } + + /************************************************************* + * NonAffine + */ + private boolean matchNonAffine (String strHorz, String strVert ) + { + nRows = strVert.length() + 1; + nCols = strHorz.length() + 1; + nCells = nCols * nRows; + strInHorz = strHorz; + strInVert = strVert; + + if (!checkAllocation ( )) return false; + + // Initialize top row + for ( int i = 1; i < nCols; ++i ){ + if ( bFreeEndGaps ) matchRow[i] = 0; + else matchRow[i] = - ( gapOpen * i ); + matchDir[i] = DIRECTION_LEFT; + } + + // Initalize left column for direction arrays + for ( int k = 1, i = nCols; k < nRows; ++k, i += nCols ){ + matchDir[i] = DIRECTION_UP; + } + matchRow[0] = 0; + + // Fill in all matricies simultaneously, row-by-row + for ( int v = 1; v < nRows; ++v ){ + float fMatch, fUp, fDiag, fLeft; + int i = ( v * nCols ) + 1; + + // Only saves two rows, the last one and current one. + float [] temp = matchLastRow; + matchLastRow = matchRow; + matchRow = temp; + temp = gapHorzLastRow; + gapHorzLastRow = gapHorzRow; + gapHorzRow = temp; + temp = gapVertLastRow; + gapVertLastRow = gapVertRow; + gapVertRow = temp; + + // Initialize column 0 for the current row + if ( bFreeEndGaps ) matchRow[0] = 0; + else matchRow[0] = - ( gapOpen * v ); + + for ( int h = 1; h < nCols; ++h, ++i ){ + fMatch = cmp(strVert.charAt(v-1), strHorz.charAt(h-1)); + + fUp = matchLastRow[h]; + if (!bFreeEndGaps || h != nCols - 1) fUp -= gapOpen; + + fDiag = matchLastRow[h-1] + fMatch; + + fLeft = matchRow[h-1]; + if (!bFreeEndGaps || v != nRows - 1) fLeft -= gapOpen; + + matchRow[h] = fUp; + matchDir[i] = DIRECTION_UP; + + if ( fDiag > matchRow[h] ){ + matchRow[h] = fDiag; + matchDir[i] = DIRECTION_DIAGONAL; + } + if ( fLeft > matchRow[h] ){ + matchRow[h] = fLeft; + matchDir[i] = DIRECTION_LEFT; + } + } + } + return true; + } + private void buildNonAffineOutput ( char chGap ){ + strGapHorz = """"; + strGapVert = """"; + + int i = nCells - 1; + int v = strInVert.length() - 1; + int h = strInHorz.length() - 1; + + while ( i > 0 ){ + switch ( matchDir[i] ){ + case DIRECTION_UP: + strGapHorz = chGap + strGapHorz; + strGapVert = strInVert.charAt(v) + strGapVert; + --v; + i -= nCols; + break; + case DIRECTION_LEFT: + strGapHorz = strInHorz.charAt(h) + strGapHorz; + strGapVert = chGap + strGapVert; + --h; + --i; + break; + case DIRECTION_DIAGONAL: + strGapHorz = strInHorz.charAt(h) + strGapHorz; + strGapVert = strInVert.charAt(v) + strGapVert; + --h; + --v; + i -= (nCols + 1); + break; + default: + throw new RuntimeException ( ""Invalid direction..."" ); + } + } + } + /******************************************************** + * XXX Affine + */ + private boolean matchAffine (String strHorz, String strVert ){ + nRows = strVert.length() + 1; + nCols = strHorz.length() + 1; + nCells = nCols * nRows; + strInHorz = strHorz; + strInVert = strVert; + + float fTotalGapOpen = - ( gapOpen + gapExtend ); + + if (!checkAllocation ( )) return false; + + // Initialize top row + for ( int i = 1; i < nCols; ++i ){ + matchRow[i] = -Float.MAX_VALUE; + matchDir[i] = DIRECTION_DIAGONAL; + gapHorzRow[i] = -Float.MAX_VALUE; + gapHorzDir[i] = DIRECTION_UP; + if ( bFreeEndGaps ) gapVertRow[i] = 0; + else gapVertRow[i] = -( gapOpen + (i-1) * gapExtend ); + gapVertDir[i] = DIRECTION_LEFT; + } + + // Initalize left column for direction arrays + for ( int k = 1, i = nCols; k < nRows; ++k, i += nCols ){ + matchDir[i] = DIRECTION_DIAGONAL; + gapHorzDir[i] = DIRECTION_UP; + gapVertDir[i] = DIRECTION_LEFT; + } + matchRow[0] = 0; + + // Fill in all matricies simultaneously, row-by-row + for ( int v = 1; v < nRows; ++v ){ + int i = ( v * nCols ) + 1; + + // ""Rotate"" the score arrays. The current row is now uninitialized, + // but the last row is completely filled in. + float [] temp = matchLastRow; + matchLastRow = matchRow; + matchRow = temp; + temp = gapHorzLastRow; + gapHorzLastRow = gapHorzRow; + gapHorzRow = temp; + temp = gapVertLastRow; + gapVertLastRow = gapVertRow; + gapVertRow = temp; + + // Initialize column 0 for the current row of all ""rotating"" arrays + matchRow[0] = -Float.MAX_VALUE; + if ( bFreeEndGaps ) gapHorzRow[0] = 0; + else gapHorzRow[0] = - ( gapOpen + (v - 1) * gapExtend ); + gapVertRow[0] = -Float.MAX_VALUE; + + for ( int h = 1; h < nCols; ++h, ++i){ + float fMatch = cmp(strVert.charAt(v-1), strHorz.charAt(h-1)); + + // Match matrix. Compare with the value one cell up and one to the left. + testBest ( h - 1, false, fMatch, fMatch, fMatch ); + matchRow [h] = fLastBest; + matchDir [i] = chLastBest; + + // Horizonal gap matrix. Compare with the value one cell up. + if ( bFreeEndGaps && ( h == nCols - 1 ) ) + testBest ( h, false, 0, 0, 0 ); + else + testBest ( h, false, -gapExtend, fTotalGapOpen, fTotalGapOpen ); + gapHorzRow [h] = fLastBest; + gapHorzDir [i] = chLastBest; + + // Vertical gap matrix. Compare with the value one cell to the left. + if ( bFreeEndGaps && ( v == (nRows - 1) ) ) + testBest ( h-1, true, 0, 0, 0 ); + else + testBest ( h-1, true, fTotalGapOpen, fTotalGapOpen, -gapExtend ); + gapVertRow [h] = fLastBest; + gapVertDir [i] = chLastBest; + } + } + // Set the starting ""pointer"" for building the output strings + testBest ( nCols - 1, true, 0, 0, 0 ); + startDir = chLastBest; + return true; + } + private void buildAffineOutput ( char chGap ){ + strGapHorz = """"; + strGapVert = """"; + + int i = nCells - 1; + int v = strInVert.length() - 1; + int h = strInHorz.length() - 1; + + char chNextHop = startDir; + + while ( i > 0 ){ + switch ( chNextHop ){ + case DIRECTION_UP: + chNextHop = gapHorzDir [i]; + strGapHorz = chGap + strGapHorz; + strGapVert = strInVert.charAt(v) + strGapVert; + --v; + i -= nCols; + break; + case DIRECTION_LEFT: + chNextHop = gapVertDir [i]; + strGapHorz = strInHorz.charAt(h) + strGapHorz; + strGapVert = chGap + strGapVert; + --h; + --i; + break; + case DIRECTION_DIAGONAL: + chNextHop = matchDir[i]; + strGapHorz = strInHorz.charAt(h) + strGapHorz; + strGapVert = strInVert.charAt(v) + strGapVert; + --h; + --v; + i -= (nCols + 1); + break; + default: + System.err.println( ""Error aligning sequences, may have run out of memory..."" ); + } + } + } + + /***************************************************** + * Used by affine method + */ + private void testBest ( int i, boolean bCurRow, float fDUp, float fDDiag, float fDLeft ){ + // Choose the best choice with the arbitrary tie break of up, diagonal, left + // Note: the inversion between the direction in the matrix and the gap is correct + float fUp, fDiag, fLeft; + + if ( bCurRow ){ + fUp = fDUp + gapHorzRow [i]; + fDiag = fDDiag + matchRow [i]; + fLeft = fDLeft + gapVertRow [i]; + } + else{ + fUp = fDUp + gapHorzLastRow [i]; + fDiag = fDDiag + matchLastRow [i]; + fLeft = fDLeft + gapVertLastRow [i]; + } + + fLastBest = fUp; + chLastBest = DIRECTION_UP; + if ( fDiag > fLastBest ){ + fLastBest = fDiag; + chLastBest = DIRECTION_DIAGONAL; + } + if ( fLeft > fLastBest ){ + fLastBest = fLeft; + chLastBest = DIRECTION_LEFT; + } + } + /***********************************************************/ + // For doHomology, the arrays get reused. + private boolean checkAllocation ( ){ + if (nCells > maxCells) { + System.err.println(""Not enough memory to align sequences - need "" + nCells + ""kb""); + isGood=false; + return false; + } + fLastBest = -Float.MAX_VALUE; + chLastBest = DIRECTION_DIAGONAL; + + try { + if ( matchDir == null || matchDir.length < nCells ){ + matchDir = new char [nCells]; + if ( bUseAffineGap ){ + gapHorzDir = new char [nCells]; + gapVertDir = new char [nCells]; + } + } + else { + for (int i=0; i< matchDir.length; i++) matchDir[i] = ' '; + if ( bUseAffineGap ) + for (int i=0; i< matchDir.length; i++) + gapHorzDir[i] = gapVertDir[i] = ' '; + } + int max = (nRows > nCols ) ? nRows : nCols; + + if ( matchRow == null || matchRow.length < max ){ + matchRow = new float [max]; + matchLastRow = new float [max]; + if ( bUseAffineGap ){ + gapHorzRow = new float [max]; + gapHorzLastRow = new float [max]; + gapVertRow = new float [max]; + gapVertLastRow = new float [max]; + } + } + else { + for (int i=0; i< matchRow.length; i++) matchRow[i] = 0.0f; + if ( bUseAffineGap ) + for (int i=0; i< matchRow.length; i++) + gapHorzRow[i] = gapVertRow[i] = + gapHorzLastRow[i] = gapVertLastRow[i] = 0.0f; + } + } + catch (OutOfMemoryError E) { + matchDir = null; + maxCells = nCells; + System.err.println(""Not enough memory to align sequences""); + System.err.println(""Increase in executable script (e.g. execAnno, viewSingleTCW""); + isGood=false; + return false; + } + return true; + } + + protected void clear() { + matchLastRow = null; + matchRow = null; + matchDir = null; + gapHorzRow = null; + gapHorzLastRow = null; + gapHorzDir = null; + gapVertRow = null; + gapVertLastRow = null; + gapVertDir = null; + + strInHorz = null; + strInVert = null; + strGapHorz = null; + strGapVert = null; + } + + //Score the alignment; sets all values that can later be obtained with gets + private void score(char chGap) { + OLPmatch = OLPlen = OLPstops = OLPscore = OLPgap = 0; + int i, j; + int allS = 0, allE = 0; // start and stop of complete overlap + boolean isOpen=false; + + int lenStr = strGapHorz.length(); // lengths of two strings the same + + // find start of overlap + for (i = 0; i< lenStr; i++) { + if (strGapHorz.charAt(i) != chGap && strGapVert.charAt(i) != chGap) { + allS = i; + break; + } + } + // find end of overlap + for (j = lenStr-1; j> 0; j--) { + if (strGapHorz.charAt(j) != chGap && strGapVert.charAt(j) != chGap) { + allE = j; + break; + } + } + OLPlen = allE - allS + 1; + if (allE>=strGapHorz.length() || allE>=strGapVert.length()) return; + + for (i = allS; i <= allE; i++) { + if (strGapHorz.charAt(i) == chGap || strGapVert.charAt(i) == chGap) { + OLPgap++; + if (isOpen && bUseAffineGap) OLPscore -= gapExtend; + else OLPscore -= gapOpen; + isOpen = true; + if (strGapHorz.charAt(i) == stopCh || strGapVert.charAt(i) == stopCh) OLPstops++; + } + else { + isOpen = false; + if (strGapHorz.charAt(i) == stopCh || strGapVert.charAt(i) == stopCh) { + OLPstops++; + OLPscore -= 4; + } + else { + double s = cmp(strGapHorz.charAt(i), strGapVert.charAt(i)); + if (s>0) OLPmatch++; + OLPscore += s; + } + } + } + if (OLPmatch>OLPlen) OLPmatch=OLPlen; // just to make sure + } + + /*******************************************************/ + private String strInHorz = null; + private String strInVert = null; + private String strGapHorz = null, strGapVert = null; // final results + + private static final char DIRECTION_UP = '^'; + private static final char DIRECTION_LEFT = '<'; + private static final char DIRECTION_DIAGONAL = '\\'; + + private int nCells, nRows, nCols = Integer.MIN_VALUE; + private float [] matchLastRow = null; + private float [] matchRow = null; + private char [] matchDir = null; + // used for affine. + private float [] gapHorzRow = null; + private float [] gapHorzLastRow = null; + private char [] gapHorzDir = null; + private float [] gapVertRow = null; + private float [] gapVertLastRow = null; + private char [] gapVertDir = null; + + private char startDir; + private float fLastBest = -Float.MAX_VALUE; + private char chLastBest = DIRECTION_DIAGONAL; + + private long maxCells = Long.MAX_VALUE; + + // returning values for score to compare alignments from different frames + // maybe should have just gotten a dp score. + private int OLPmatch = 0; + private int OLPlen = 0; + private int OLPstops = 0, OLPscore = 0, OLPgap = 0; + private boolean isDNA = true; + private boolean isGood=true; + + protected void prtInfo() {System.out.format(""Stops %d Score %d Gap %d Good %b"", OLPstops, OLPscore, OLPgap, isGood);} + + // BLOSUM62 7/17/19 from ftp://ftp.ncbi.nlm.nih.gov/blast/matrices/BLOSUM62 + // Called in cmp above. + // Also called by util.align.AlignData + // by moving the array to this file sped it up about 10-fold!! + static protected int getBlosum(char a1, char a2) { + String residues = ""ARNDCQEGHILKMFPSTWYVBZX*""; + int idx1 = residues.indexOf(a1); + int idx2 = residues.indexOf(a2); + if (idx1==-1 || idx2==-1) { + if (idx1==-1) System.err.println(""AA not recognized a1 '"" + a1 + ""' ""); + if (idx2==-1) System.err.println(""AA not recognized a2 '"" + a2 + ""' ""); + return -10; + } + return (blosum[idx1][idx2]); + } + private static final int blosum[][] = new int [][] { + { 4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0, -2, -1, 0, -4}, + {-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3, -1, 0, -1, -4}, + {-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3, 3, 0, -1, -4}, + {-2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3, 4, 1, -1, -4}, + { 0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1, -3, -3, -2, -4}, + {-1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2, 0, 3, -1, -4}, + {-1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1, -4}, + { 0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3, -1, -2, -1, -4}, + {-2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3, 0, 0, -1, -4}, + {-1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3, -3, -3, -1, -4}, + {-1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1, -4, -3, -1, -4}, + {-1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2, 0, 1, -1, -4}, + {-1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1, -3, -1, -1, -4}, + {-2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1, -3, -3, -1, -4}, + {-1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2, -2, -1, -2, -4}, + { 1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2, 0, 0, 0, -4}, + { 0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0, -1, -1, 0, -4}, + {-3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3, -4, -3, -2, -4}, + {-2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1, -3, -2, -1, -4}, + { 0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4, -3, -2, -1, -4}, + {-2, -1, 3, 4, -3, 0, 1, -1, 0, -3, -4, 0, -3, -3, -2, 0, -1, -4, -3, -3, 4, 1, -1, -4}, + {-1, 0, 0, 1, -3, 3, 4, -2, 0, -3, -3, 1, -1, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1, -4}, + { 0, -1, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, 0, 0, -2, -1, -1, -1, -1, -1, -4}, + {-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, 1} + }; + +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/closeup/MsaMainPanel.java",".java","12998","405","package symap.closeup; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFileChooser; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextField; + +import symap.Globals; +import symapQuery.QueryFrame; +import symapQuery.TableMainPanel; +import util.ErrorReport; +import util.Jcomp; +/************************************** + * For Symap Query: align selected set using muscle or mafft + * Called from SyMAPQueryFrame; calls methods to build alignments and displays + * MsaPanel is the actual align panel and MsaRun runs the alignment + */ +public class MsaMainPanel extends JPanel { + private static final long serialVersionUID = -2090028995232770402L; + private String [] tableLines; + private String sumLines=""""; // created in AlignRun + private String tabName, tabAdd, resultSum; + + public MsaMainPanel(TableMainPanel tablePanel, QueryFrame parentFrame, String [] names, String [] seqs, String [] tabLines, + String progress, String msaSum, String tabName, String tabAdd, String resultSum, + boolean bTrim, boolean bAuto, int cpu){ + + this.tablePanel = tablePanel; + this.queryFrame = parentFrame; + this.tableLines = tabLines; + this.tabName = tabName; + this.tabAdd = tabAdd; + this.resultSum = resultSum; + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBackground(Color.WHITE); + + buildAlignThread(names, seqs, progress, msaSum, bTrim, bAuto, cpu); + } + + private void buildAlignThread(String [] names, String [] seqs, String progress, String msaSum, + boolean bTrim, boolean bAuto, int cpu) { + + if (theThread == null){ + theThread = new Thread(new Runnable() { + public void run() { + try { + createProgress(); + + bDone=false; + + boolean rc = runAlign(names, seqs, progress, msaSum, bTrim, bAuto, cpu); + if (!rc) return; // Tab will still occur, but with progress error shown + if (bStopped) return; + + bDone=true; + + createButtonPanel(); + createSplitPane(); + + add(buttonPanel); + add(splitPane); + + showProgress(false); + updateExportButton(); + buildFinish(); + + if (isVisible()) { //Makes the table appear + setVisible(false); + setVisible(true); + } + } + catch (Exception e) {ErrorReport.print(e, ""Build Alignment"");} + } + }); + theThread.setPriority(Thread.MIN_PRIORITY); + theThread.start(); + } + } + /* replace tab: add to result table; Has to be done from thread, but not in thread */ + private void buildFinish() { + if (bStopped) return; // if it does not on result table after stop, cannot remove + + String oldTab = tabName+"":""; // same as QueryFrame.makeTabMSA + String newTab = tabName + "" "" + tabAdd; + + String [] resultVal = new String[2]; + resultVal[0] = newTab; // left of result table panel + resultVal[1] = resultSum; // right of result table panel with query filters + + queryFrame.updateTabText(oldTab,newTab, resultVal); + + tablePanel.setMsaButton(true); + } + /*****************************************************/ + private boolean runAlign(String [] names, String [] sequences, + String status, String msaSum, boolean bTrim, boolean bAuto, int cpu) { + + String fileName = ""temp""; + msaData = new MsaRun(this, fileName, progressField); + for(int x=0; x (); + cmbRatio.addItem(""Zoom 1:1""); + cmbRatio.addItem(""Zoom 1:2""); + cmbRatio.addItem(""Zoom 1:3""); + cmbRatio.addItem(""Zoom 1:4""); + cmbRatio.addItem(""Zoom 1:5""); + cmbRatio.addItem(""Zoom 1:6""); + cmbRatio.addItem(""Zoom 1:7""); + cmbRatio.addItem(""Zoom 1:8""); + cmbRatio.addItem(""Zoom 1:9""); + cmbRatio.addItem(""Zoom 1:10""); + cmbRatio.setBackground(Color.WHITE); + cmbRatio.setSelectedIndex(0); + cmbRatio.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + refreshAlign(); + } + }); + theRow.add(cmbRatio); theRow.add(Box.createHorizontalStrut(10)); + + btnShowType = Jcomp.createButton(""Show Sequences"", ""Change graphics from graphic to sequence""); + btnShowType.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + if(btnShowType.getText().equals(""Show Graphic"")) { + btnShowType.setText(""Show Sequences""); + cmbRatio.setEnabled(true); + } + else { + btnShowType.setText(""Show Graphic""); + cmbRatio.setEnabled(false); + } + refreshAlign(); + } + }); + theRow.add(btnShowType); theRow.add(Box.createHorizontalStrut(10)); + + btnExport = Jcomp.createButton(""Export"", ""Export consensus and aligned sequences""); + btnExport.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + if (msaPanel == null) return; + + String fname = ""consensus.fa""; + String saveDir = Globals.alignDir; + + JFileChooser chooser = new JFileChooser(saveDir); + chooser.setSelectedFile(new File(fname)); + if (chooser.showSaveDialog(queryFrame) != JFileChooser.APPROVE_OPTION) return; + if (chooser.getSelectedFile() == null) return; + + fname = chooser.getSelectedFile().getName(); + if(fname != null && fname.length() > 0) { + if(!fname.endsWith("".fa"")) fname += "".fa""; + msaData.exportConsensus(fname); + } + } + }); + theRow.add(btnExport); + theRow.setMaximumSize(theRow.getPreferredSize()); + + buttonPanel.add(theRow); + } + + private void handleClickAlign(MouseEvent e) { + if(msaPanel == null) return; + + // Convert to view relative coordinates + int viewX = (int) (e.getX() + msaScroll.getViewport().getViewPosition().getX()); + int viewY = (int) (e.getY() + msaScroll.getViewport().getViewPosition().getY()); + + // Convert to panel relative coordinates + int nPanelX = viewX - msaPanel.getX(); + int nPanelY = viewY - msaPanel.getY(); + + if (msaPanel.contains(nPanelX, nPanelY)) {// Click is in current panel, let the object handle it + msaPanel.handleClick(e, new Point(nPanelX, nPanelY)); + } + else if (!e.isShiftDown() && !e.isControlDown()) { + msaPanel.selectNoRows(); + msaPanel.selectNoColumns(); + } + } + /*************************************************/ + private void updateExportButton() { + if(msaData != null && msaData.hasFilename()) + btnExport.setEnabled(true); + else + btnExport.setEnabled(false); + } + /************************************************* + * Status at top of page while alignment is running + */ + private void createProgress() { + progressField = new JTextField(130); + progressField.setEditable(false); + progressField.setMaximumSize(progressField.getPreferredSize()); + progressField.setBackground(Color.WHITE); + progressField.setBorder(BorderFactory.createEmptyBorder()); + + btnCancel = new JButton(""Stop""); + btnCancel.setBackground(Color.WHITE); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + stopThread(); + } + }); + + add(progressField); + add(Box.createVerticalStrut(10)); + add(btnCancel); + } + private void showProgress(boolean show) { + btnCancel.setVisible(show); + progressField.setVisible(show); + } + private void updateProgress(String status) { + progressField.setText(status); + repaint(); + } + private void stopThread() { + if (theThread==null) return; + + if (bDone) { + if (!util.Popup.showConfirm2(""Stop MSA"", ""MSA complete. Stop displaying results?"")) return; + } + + tablePanel.setMsaButton(true); // unfreeze button + + queryFrame.removeResult(this); // remove from left side + + util.Popup.showInfoMessage(""Stop MSA"", // writes to terminal + ""You must stop MAFFT (distbfast) or MUSCLE (muscle) manually; "" + + ""\n see the online documentation for help. ""); + + bStopped=true; + try { + theThread.interrupt(); + } + catch (Exception e) {}; + } + + /*********************************************** + * Draws the table of hit information beneath alignment; + */ + private class TablePanel extends JPanel { + private static final long serialVersionUID = -5292053168212278988L; + private static Font font = new Font(""Courier"", Font.PLAIN, 12); + private String [] tabPlus; + + private TablePanel () { + // Add sumLines to keyLines + int ex=2, nlines = tableLines.length; + tabPlus = new String[nlines+ex]; + for (int i=0; i cmbRatio = null; + private JButton btnShowType = null, btnExport = null; + + private JTextField progressField = null; + private JButton btnCancel = null; + + private Thread theThread = null; //Thread used for building the sequence data + private boolean bDone=false; // If they Stop, but it just finished, this will be true + protected boolean bStopped=false; + + private MsaRun msaData = null; + private MsaPanel msaPanel = null; + private JScrollPane msaScroll = null, lowerScroll = null; + private TablePanel lowerPanel = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/TrackLayout.java",".java","4310","131","package symap.sequence; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.LayoutManager; +import java.awt.Point; + +import javax.swing.JButton; +import javax.swing.JPanel; + +import symap.drawingpanel.DrawingPanel; +import symap.mapper.Mapper; + +/*************************************************** + * Lays out tracks; called in DrawingPanels + */ +public class TrackLayout implements LayoutManager { + private DrawingPanel dp; + private TrackHolder[] trackHolders; // N sequence + private Mapper[] mappers; // N-1 hits joining 2 sequence + private JPanel buttonPanel; // to contain Filter buttons + + private final int MAX_SPACE = 180; // maximum space for a track with added ruler and anno + + public TrackLayout(DrawingPanel dp, TrackHolder[] trackHolders, Mapper[] mappers, JPanel buttonPanel) { + buttonPanel.setLayout(null); + this.dp = dp; + this.buttonPanel = buttonPanel; + this.mappers = mappers; + this.trackHolders = trackHolders; + } + + public void layoutContainer(Container target) { + if (!trackHolders[0].isVisible()) return; + if (!mappers[0].isVisible()) return; + + if (buttonPanel == null) { + symap.Globals.eprt(""Null button panel in Track Layout""); + return; + } + buttonPanel.removeAll(); + + int nTracks = trackHolders.length; + int accWid = 5; // accumulated width + Dimension filterDim = new Dimension(0,0); // filter buttons dimension + + // Set track dimensions and location and calculate button panel size + for (int i = 0; i < nTracks; i++) { + Dimension dimTrack = trackHolders[i].getPreferredSize(); + trackHolders[i].setSize(dimTrack.width, dimTrack.height); + + if (i > 0) accWid += dp.trackDistance; + trackHolders[i].setLocation(accWid, 0); + + // set button dims + JButton ithButton = trackHolders[i].getFilterButton(); + buttonPanel.add(ithButton); + + Dimension dimButton = ithButton.getPreferredSize(); + ithButton.setSize(dimButton); + + int mid = (int) Math.round(trackHolders[i].getTrack().getMidX() + accWid - (dimButton.width/2.0)); + ithButton.setLocation(mid,1); + + // update dims + if (i>0 && nTracks>2) accWid += Math.min(dimTrack.width, MAX_SPACE); + else accWid += dimTrack.width; + + filterDim.height = Math.max(filterDim.height, ithButton.getHeight()); + filterDim.width = accWid; + + accWid += dp.trackDistance; + } + buttonPanel.setSize(filterDim.width, buttonPanel.getHeight()); + + // Set mappers dims and Hit Filter dims and loc + Point pt1, pt2 = trackHolders[0].getLocation(); + Dimension dim1, dim2 = trackHolders[0].getSize(); + + for (int i = 0; i < mappers.length; i++) { + pt1 = pt2; + dim1 = dim2; + pt2 = trackHolders[i+1].getLocation(); + dim2 = trackHolders[i+1].getSize(); + + Dimension dim = new Dimension(Math.max(dim1.width + pt1.x, dim2.width + pt2.x), + Math.max(dim1.height + pt1.y, dim2.height + pt2.y)); + mappers[i].setSize(dim); + + // Set Hit Filter dimensions and locations + JButton ithButton = mappers[i].getFilterButton(); + buttonPanel.add(ithButton); + + Dimension bDim = ithButton.getPreferredSize(); + ithButton.setSize(bDim); + + JButton b1 = trackHolders[i].getFilterButton(), b2 = trackHolders[i+1].getFilterButton(); + int mid = (int) Math.round((b1.getX() + b1.getWidth() + b2.getX() - bDim.width) / 2.0); + ithButton.setLocation(mid, 1); + + filterDim.height = Math.max(filterDim.height,ithButton.getHeight()); + } + + // Finish buttonPanel + filterDim.height += 2; + if (filterDim.width > 0) { + buttonPanel.setPreferredSize(filterDim); + buttonPanel.setSize(filterDim); + } + } + public Dimension preferredLayoutSize(Container target) { // necessary for scroll bar + if (!trackHolders[0].isVisible()) return target.getSize(); + + Dimension dim = new Dimension(0,0); + + for (int i = 0; i < trackHolders.length; i++) { + if (i > 0) dim.width += dp.trackDistance; + Dimension d = trackHolders[i].getPreferredSize(); + dim.height = Math.max(dim.height,d.height); + dim.width += d.width; + if (i > 0) dim.width += dp.trackDistance; + } + return dim; + } + + public Dimension minimumLayoutSize(Container target) {return preferredLayoutSize(target);} + public void addLayoutComponent(String name, Component comp) { } + public void removeLayoutComponent(Component comp) { } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/TextBox.java",".java","5720","188","package symap.sequence; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.BasicStroke; +import java.util.Vector; +import javax.swing.JComponent; +import javax.swing.JLabel; + +import util.LinkLabel; + +/****************************************************** + * Draws the gray annotation description box + * They stay the same width regular of expand/shrink, instead turns on scroll bar + */ +public class TextBox extends JComponent { + private static final long serialVersionUID = 1L; + private Color borderColor = Color.black; + private final Color bgColor = new Color(240,240,240); + private float stroke = 3f; + private final int INSET = 5; + private final int startWidth = 600; + private final int wrapLen=40, wrapMaxLen=50, wrapShortLen=10, maxLines=3; + + private int width=0, tx = INSET, ty = INSET; + private Font theFont; + + // Specific for gray box called from Sequence; greedy placement algorithm + protected TextBox(Vector lines, Font font, int x, int y, Color bgColor) { + if (lines.size()!=3) return; + + theFont=font; + this.borderColor = bgColor; + + setLabel(lines.get(0)); + if (lines.get(1).length()>1) setLabel(lines.get(1)); + String desc=lines.get(2); + + if (desc.length() <= wrapLen) { + if (desc.length()>1) setLabel(desc); + } + else { + int curLen=0, totLines=0; + String[] words = desc.split(""\\s+""); + + StringBuffer curLine = new StringBuffer(); + + for (int i = 0; i < words.length; i++) { + curLen += words[i].length()+1; + + if (curLen>wrapLen) { + boolean bNoWrap = curLine.length()< wrapShortLen && curLen=maxLines) { + setLabel(curLine.toString() + ""...""); + break; + } + setLabel(curLine.toString()); + curLen = words[i].length()+1; + curLine = new StringBuffer(); + } + } + if (curLine.length()>0) curLine.append("" ""); + curLine.append(words[i]); + if (i==words.length-1) setLabel(curLine.toString()); + } + } + setSize(width, ty + INSET); + setLocation(x, y); + } + private void setLabel(String line) { + if (line.length()>wrapLen) line = line.substring(0,wrapLen)+""...""; + JLabel label = new JLabel(line); + + label.setLocation(tx, ty); + label.setFont(theFont); + label.setSize(label.getMinimumSize()); + add(label); + + ty += label.getHeight(); + width = Math.max(width, label.getWidth() + INSET*2); + if (width > startWidth) width = startWidth; + } + protected double getLowY() { return getHeight() + getY();} + + /// a URL-savvy graphical text box Previous; not used + private int trueWidth=0; + public TextBox(Vector text, Font font, int x, int y, int wrapLen, int truncLen) { + this(text.toArray(new String[0]), font, x, y, wrapLen, truncLen); + } + + private TextBox(String[] text, Font font, int x, int y,int wrapLen, int truncLen) { + int width = 0; + int tx = INSET; + int ty = INSET; + + for (String line : text) { + int urlIndex = line.indexOf(""=http://""); + if (urlIndex > -1) { // this line contains a URL + String tag = line.substring(0, urlIndex); + String url = line.substring(urlIndex+1); + JLabel label = new LinkLabel(tag, Color.black, Color.red, url); + label.setLocation(tx, ty); + label.setFont(font); + label.setSize(label.getMinimumSize()); + add(label); + + ty += label.getHeight(); + width = Math.max(width, label.getWidth() + INSET*2); + trueWidth = Math.max(trueWidth, label.getWidth() + INSET*2); + if (width > startWidth) width = startWidth; + } + else { + if (line.length() <= wrapLen) { + JLabel label = new JLabel(line); + + label.setLocation(tx, ty); + label.setFont(font); + label.setSize(label.getMinimumSize()); + add(label); + + ty += label.getHeight(); + width = Math.max(width, label.getWidth() + INSET*2); + trueWidth = Math.max(trueWidth, label.getWidth() + INSET*2); + if (width > startWidth) width = startWidth; + } + else { + String[] words = line.split(""\\s+""); + StringBuffer curLine = new StringBuffer(); + int totalLen = 0; + for (int i = 0; i < words.length; i++) { + curLine.append(words[i]+"" ""); + + totalLen += words[i].length()+1; + int curLen = curLine.length(); + + if (curLen >= wrapLen || i == words.length - 1) { + + if (i < words.length - 1 && totalLen >= truncLen) {// done with this line, but add ""..."" if being truncated + curLine.append(""...""); + } + if (curLine.length() > 1.25*wrapLen) { + curLine.delete((int)(1.25*wrapLen),curLine.length()); + curLine.append(""...""); + } + JLabel label = new JLabel(curLine.toString()); + + label.setLocation(tx, ty); + label.setFont(font); + label.setSize(label.getMinimumSize()); + add(label); + + ty += label.getHeight(); + width = Math.max(width, label.getWidth() + INSET*2); + trueWidth = Math.max(trueWidth, label.getWidth() + INSET*2); + if (width > startWidth) width = startWidth; + if (totalLen >= truncLen) break; // note, don't truncate until filling a line + curLine = new StringBuffer(); + } + } + } + } + } + setSize(width, ty + INSET); + setLocation(x, y); + } + + public void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D)g; + int width = getWidth()-1; + int height = getHeight()-1; + + // Draw rectangle + g2.setColor(bgColor); + g2.fillRect(0, 0, width, height); + BasicStroke s = new BasicStroke(stroke); + g2.setStroke(s); + g2.setColor(borderColor); + g2.drawRect(0, 0, width, height); + + paintComponents(g); // draw text + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/TrackHolder.java",".java","2566","83","package symap.sequence; + +/************************************************************* + * Holds a sequence track + */ +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.MouseEvent; + +import javax.swing.JButton; +import javax.swing.JComponent; + +import symap.drawingpanel.DrawingPanel; +import symap.drawingpanel.FilterHandler; +import symap.frame.HelpBar; + +public class TrackHolder extends JComponent { + private static final long serialVersionUID = 1L; + private HelpBar hb; + private int orientation; // left-right + private Sequence track=null;// track->sequence + private FilterHandler fh; + private int trackNum; // for Sequence track + + private void dprt(String msg) {symap.Globals.dprt(""TH "" + msg);} + + public TrackHolder(DrawingPanel dp, HelpBar hb, int trackNum, int side) { // Called by DrawingPanel; created on startup + super(); + this.hb = hb; + this.trackNum = trackNum; + this.orientation = side; + + fh = new FilterHandler(dp); + track = null; + + setOpaque(false); + setVisible(false); + } + + public Sequence getTrack() {return track;}// Called by DrawingPanel, Mapper + + public int getTrackNum() {return trackNum;} + + public void setTrack(Sequence t) { // Called by DrawingPanel.setSequenceTrack + if (t == track && t!=null) dprt(""Has track "" + track.toString()); + if (t == null) dprt(""null seq track ""); + + track = t; + fh.setSfilter(track); + addMouseListener(track); + addMouseMotionListener(track); + addMouseWheelListener(track); + addKeyListener(track); + if (hb != null) hb.addHelpListener(this,track); + track.setOrientation(orientation); + } + public void setTrackData(TrackData td) { // called by DrawingPanel.setMaps for History + track.setup(td); + } + public TrackData getTrackData() { return track.getData();} // called by DrawingPanelData for History; + + protected void showPopupFilter(MouseEvent e) { fh.showPopup(e);} // Sequence.mousePressed + + protected JButton getFilterButton() { return fh.getFilterButton(); }// TrackLayout + + public void closeFilter() { fh.closeFilter();}// DrawingPanel + + public Dimension getPreferredSize() {return track.getDimension();} + + public void setVisible(boolean visible) { + if (fh.getFilterButton() != null) fh.getFilterButton().setEnabled(visible); + super.setVisible(visible); + } + protected void paintComponent(Graphics g) { + super.paintComponent(g); + track.paintComponent(g); + } + public String toString() { + String seq = (track==null) ? ""null"" : track.toString(); + return String.format(""TrackHolder side=%2d #%d %s"", orientation, trackNum, seq); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/Annotation.java",".java","20097","549","package symap.sequence; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Component; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Stroke; +import java.awt.geom.Rectangle2D; +import java.util.Vector; + +import props.PropertiesReader; + +import java.util.Comparator; +import java.util.TreeMap; + +import symap.Globals; +import symap.mapper.Mapper; +import symap.closeup.TextShowInfo; +import symap.closeup.SeqDataInfo; +import symap.closeup.SeqData; +import util.ErrorReport; +import util.Utilities; + +/** + * Annotation is used for storing and painting an annotation graphics to the screen. + * An annotation can be a Gene, Exon, Gap, Centromere + * Drawing the annotation requires calling setRectangle() first. + */ +public class Annotation { + private Sequence seqObj; + private int itype; + private int start, end; + private String description; + private String strGeneNum, tag, fullTag; + private boolean bStrandPos; + private int gene_idx=0; // If this is an exon, it is the gene_idx (pseudo_annot.idx) that it belongs to + private int annot_idx=0; // pseudo_annot.idx + private int genenum=0; + + private Rectangle2D.Double rect; // Gene rectangle + private Rectangle2D.Double hoverGeneRect; // so hover cover for gene covers full width of exon + private Rectangle2D.Double lastR=null; // if Last gene starts at same Y, then stagger Gene# + + private Vector exonVec = null; // determine during SeqPool load + private String exonList=null; // build first time of popup + private String hitListStr1=null; // add to popup; computed in sequence.setForGenePopup using coords + private String hitListStr2=null; // add HitList for other side to popup + private int [] hitIdxArr1=null, hitIdxArr2=null; // set value when hitListStr is set + private boolean bHasHits=false; // On creation, T if any hits; on display GeneNum, changed to T if hit for this pair + + private boolean bGeneLineOpt=false; // Show line on all genes + private boolean bHighPopup=false; // Highlight gene if popup + private boolean bShowGeneNum=false; // Show text genenum + private boolean bShowGeneNumHit=false; // Show text genenum + private boolean isPopup=false; // Gene has popup - highlight if bHighPopup + private boolean isHitPopup=false; // Hit Popup highlights gene too, though gene Popup has precedence + + private boolean isSelectedGene=false; // Gene is filtered + private boolean isG2xN=false; // Highlight exons of G2xN genes + + /** + * Creates a new Annotation instance setting the description values, color, and draw method based on type. + * SeqPool.setSequence + */ + protected Annotation(Sequence seqObj, String desc, int itype, int start, int end, String strand, + String dbtag, int gene_idx, int idx, int genenum, int numhits) { + this.seqObj = seqObj; + this.itype = itype; + this.start = start; + this.end = end; + this.bStrandPos = (strand == null || !strand.equals(""-"")); + this.description = desc; + this.gene_idx = gene_idx; + this.annot_idx = idx; + this.genenum = genenum; + bHasHits = (numhits>0); // this could be from any synteny pair + + // see backend.AnnotLoadPost.computeTags for formatting + if (genenum==0) { + if (!dbtag.startsWith(""Exon"")) this.fullTag = this.tag = Globals.exonTag + dbtag; // new + else this.fullTag = this.tag = dbtag; // old start with Exon + } + else { + tag = Utilities.convertTag(dbtag); // coverts old to new DB: geneNum (n exon-len) + strGeneNum = Utilities.getGenenumFromDBtag(tag); // extracts geneNum.suffix only + fullTag = Utilities.createFullTagFromDBtag(tag); // create: 'Gene' geneTag ('#Exons' n exon-len) + exonVec = new Vector (); + } + + rect = new Rectangle2D.Double(); + hoverGeneRect = new Rectangle2D.Double(); + } + protected void addExon(Annotation aObj) {exonVec.add(aObj);} // determined during SeqPool load of data + + public Vector getExonVec() { return exonVec;} // for closeup.SeqDataInfo hit popup + /** + * DRAW sets up the rectangle; called in Sequence.buildGraphics(); + */ + protected void setRectangle( + Rectangle2D boundry, // center of chromosome rectangle (rect.x+1,rect.y,rect.width-2,rect.height) + int startBP, int endBP, // display start and end of chromosome + double bpPerPixel, double dwidth, double hoverWidth, boolean flip, int offset, + boolean bHighPopup, boolean bGeneLineOpt, boolean bShowGeneNum, boolean bShowGeneNumHit, int nG2xN) + { + this.bGeneLineOpt=bGeneLineOpt; // used these 3 in paintComponent + this.bHighPopup=bHighPopup; + this.bShowGeneNum=bShowGeneNum; this.bShowGeneNumHit=bShowGeneNumHit; + if (bShowGeneNum && nG2xN!=0 && !isG2xN) this.bShowGeneNum=false; + + double x, y, height; + double chrX=boundry.getX(), upChrY=boundry.getY(), chrHeight=boundry.getHeight(), chrWidth=boundry.getWidth(); + double lowChrY = upChrY + chrHeight; // lowest chromosome edge + + int ts, te; + if (start > end) { + ts = end; + te = start; + } else { + ts = start; + te = end; + } + if (ts < startBP) ts = startBP; + if (te > endBP) te = endBP; + + if (!flip) y = (ts - startBP) / bpPerPixel + upChrY; + else y = (endBP - ts) / bpPerPixel + upChrY; + + height = (te - ts) / bpPerPixel; + if (flip) y -= height; + + x = chrX + (chrWidth - dwidth)/2; // set x before modify width + if (offset!=0) x = x-offset; // for overlapping genes, 0 for not + + if (chrWidth < dwidth) dwidth = chrWidth; + + double lowY = y + height; + if (y < upChrY) y = upChrY; + if (lowY > lowChrY) height = lowChrY - y; + + if (lowY >= upChrY && y <= lowChrY) rect.setRect(x, y, dwidth, height); + else rect.setRect(0, 0, 0, 0); + + if (hoverWidth!=0) { // gene + double xx = chrX + (chrWidth-hoverWidth)/2; // set x before modify width + if (offset!=0) xx= xx-offset; // for overlapping genes + + if (chrWidth < hoverWidth) hoverWidth = chrWidth; + + if (lowY >= upChrY && y <= lowChrY) hoverGeneRect.setRect(xx, y, hoverWidth, height); + else hoverGeneRect.setRect(0, 0, 0, 0); + } + } + + public void paintComponent(Graphics2D g2) { // called from Sequence.paintComponent + if (itype >= numTypes) return; + + g2.setPaint(getColor()); + + if (itype == CENTROMERE_INT) { + Stroke oldstroke = g2.getStroke(); + g2.setStroke(new BasicStroke(crossWidth)/*crossStroke*/); + + g2.drawLine((int)rect.x, (int)rect.y, (int)rect.x + (int)rect.width, (int)rect.y + (int)rect.height); + g2.drawLine((int)rect.x, (int)rect.y + (int)rect.height, (int)rect.x + (int)rect.width, (int)rect.y); + + g2.setStroke(oldstroke); + } + else { // (1) Gene, Exon, Gap (2) TICK or RECT + if (rect.height >= 2) { // Only draw full rectangle if it is large enough to see. + g2.fillRect((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height); + + if (itype==GENE_INT) {// Gene Delimiter + if (bGeneLineOpt || isPopup || isSelectedGene) { + Stroke oldstroke = g2.getStroke(); + g2.setStroke(new BasicStroke(2)); + g2.drawLine((int)rect.x-10, (int)rect.y, ((int)rect.x + 13), (int)rect.y); + g2.setStroke(oldstroke); + } + } + } + else // Else draw as line + g2.drawLine((int)rect.x, (int)rect.y, (int)rect.x + (int)rect.width, (int)rect.y); + + // XXX Gene# LastR is Rect, not text (Gray box drawn in Sequence.buildGraphics) + boolean doGeneNum = (bShowGeneNum && itype==GENE_INT) || (bShowGeneNumHit && showGeneHasHit()); + if (doGeneNum) { + g2.setPaint(Color.black); + g2.setFont(Globals.textFont); + + int x, w=0; + if (seqObj.isRef()) { // right side + if (lastR!=null && lastR.x>rect.x && lastR.y+lastR.height>rect.y) + x = (int)lastR.x + (int) Sequence.EXON_WIDTH-2; + else x = (int)rect.x + (int) Sequence.EXON_WIDTH-2; // paint on right + } + else { // left side + FontMetrics metrics = g2.getFontMetrics(Globals.textFont); + w = metrics.stringWidth(strGeneNum) + 6; // tested stringWidth of 'a' is 7 + x = (int) rect.x-w; + } + int y = (int)rect.y + (Globals.textHeight/2); + if (lastR!=null && Math.abs(lastR.y-rect.y) 0 && rect.getHeight() > 0; + } + + protected void setOffset(double x, double y) { // Offset the whole Annotation if it's visible. + if (isVisible()) { + rect.x -= x; + rect.y -= y; + + if (hoverGeneRect.getX()!=0 && hoverGeneRect.getY() !=0) { + hoverGeneRect.x -= x; + hoverGeneRect.y -= y; + } + } + } + + public int getStart() {return start;} + public int getEnd() {return end;} + public int getGeneIdx() { return gene_idx;} // For Sequence to know if overlap exon + public int getAnnoIdx() { return annot_idx;} // ditto + public String getTag() {return tag;} // For HelpBox; called for Exons + public boolean isStrandPos() {return bStrandPos;} // for seq-seq closeup + protected Color getBorderColor() { return (bStrandPos) ? exonColorP : exonColorN;} // for Annotation Boxes + + protected int getType() {return itype;} + protected boolean isGene() { return itype == GENE_INT; } + protected boolean isExon() { return itype == EXON_INT; } + protected boolean isGap() { return itype == GAP_INT; } + protected boolean isCentromere() { return itype == CENTROMERE_INT; } + + protected int getGeneLen() { return Math.abs(end-start)+1;} // ditto + protected int getGeneNum() { return genenum;} // for sorting in SeqPool + public String getFullGeneNum() {return strGeneNum;} // has suffix + + /******************************************* + * XXX hover and box and closeup info + */ + protected boolean hasDesc() { // Sequence.build() + return description != null && description.length() > 0; + } + public String getCloseUpDesc() {// For CloseUpDialog - shown over the gene graphic; use DescOnly + return ""Gene #"" + strGeneNum + "" "" + getIdOnly() + "" "" + getDescOnly(); + } + protected Vector getGeneBoxDesc() { // Shown when the Annotation option is on; + Vector out = new Vector(); + out.add(String.format(""Gene #%s "",strGeneNum) + SeqData.coordsStrKb(bStrandPos, start, end)); + out.add(getIdOnly()); + out.add(getDescOnly()); // TextBox expect 3 entries + return out; + } + private String getIdOnly() { + for (String keyVal : description.split("";"")) { + if (keyVal.contains(""="")) { + String [] tok = keyVal.split(""=""); + String key = tok[0].toLowerCase(); + if (key.startsWith(""id"")) { + if (tok.length==2) return tok[1]; + else return """"; + } + } + } + return """"; + } + private String getDescOnly() { + for (String keyVal : description.split("";"")) { // NCBI or Ensembl + if (keyVal.contains(""="")) { + String [] tok = keyVal.split(""=""); + String key = tok[0].toLowerCase(); + if (key.startsWith(""product"") || key.startsWith(""desc"")) { + if (tok.length==2) return tok[1]; + else return """"; + } + } + } + for (String keyVal : description.split("";"")) { // unknown, take a guess + if (keyVal.contains(""="")) { + String [] tok = keyVal.split(""=""); + String key = tok[0].toLowerCase(); + if (!key.startsWith(""id"") && !key.startsWith(""name"") && !key.startsWith(""protein"")) { + if (tok.length==2) return tok[1]; + else return """"; + } + } + } + return description; + } + + private Vector getPopUpDesc() { // Shown when click on anno; show full descr + Vector out = new Vector(); + out.add(fullTag); + out.add(getLocLong()); + for (String token : description.split("";"")) { + out.add( token.trim() ); + } + return out; + } + protected String getHoverDesc() {// Shown in info text box when mouse over object; show full desc + String longDes; + + if (itype == GENE_INT) { + String xDesc = description.replaceAll("";"", ""\n""); + longDes = fullTag + ""\n"" + getLocLong() + ""\n"" + xDesc; + } + else if (itype == EXON_INT) longDes = tag + "" "" +getLocLong(); + else if (itype == GAP_INT) longDes = ""Gap\n"" + getLocLong(); + else if (itype == CENTROMERE_INT) longDes = ""Centromere\n"" + getLocLong(); + else longDes = ""Name "" + description; + + return longDes; + } + private String getLocLong() { // used in above two + return SeqData.coordsStr(bStrandPos, start, end); + } + + protected boolean hasHitList() {return hitListStr1!=null; } // means it has been set, but may not have hits + protected boolean hasHits() {return hitIdxArr1!=null;} // set and has hits + protected void setHitList(String hList, TreeMap scoreMap) { // Calls 1st time popup or show GeneNum + hitListStr1=hList; + if (scoreMap.size() > 0) { + hitIdxArr1 = new int [scoreMap.size()]; + int i=0; + for (int idx : scoreMap.keySet()) hitIdxArr1[i++] = idx; + } + } + protected boolean hasHitList2() {return hitListStr2!=null; } // hits on other side if tracks on both sides + protected void setHitList2(String hList, TreeMap scoreMap){ + hitListStr2=hList; + if (scoreMap.size() > 0) { + hitIdxArr2 = new int [scoreMap.size()]; + int i=0; + for (int idx : scoreMap.keySet()) hitIdxArr2[i++] = idx; + } + } + + // for popup + protected void setExonList() { + if (exonList!=null) return; + try { + String list=null; + + TreeMap stMap = new TreeMap (); // to sort on start + for (Annotation ex : exonVec) { + String x = ex.tag + "":"" + ex.start+ "":"" + ex.end; ; // accessing exon annotation object + stMap.put(ex.start, x); + } + for (String val : stMap.values()) { + if (list==null) list = val; + else list += "","" + val; + } + exonList = list; + } + catch (Exception e) {ErrorReport.print(e, ""Get exon list for "" + gene_idx);} + } + + // determines if the rectangle of this annotation contains the point p. + protected boolean contains(Point p) { + if (itype == GENE_INT) { + return hoverGeneRect.contains(p.getX(), p.getY()); + } + return rect.contains(p.getX(), p.getY()); + } + /* + * popup from clicking gene; use Utilities for tag + * called from Sequence.popupDesc, + * if hitListStr and exonList, not set, they are now and reused + * calls SeqPool to get list of hits for the gene/chr and scores + * calls HitData to format hit + */ + protected void popupDesc(Component parentFrame, String name, String chr) { + try { + if (!tag.contains(""("")) return; + setIsPopup(true); + + String [] tok = Utilities.getGeneExonFromTag(tag); // tok[0] Gene #X tok[1] #Exon=n nnnnbp + + String msg = null; + for (String x : getPopUpDesc()) { + if (msg==null) msg = tok[0] + "" "" + chr + ""\n""; + else msg += x + ""\n""; + } + msg += ""\n""; + + if (hitListStr1!=null && hitListStr1.length()>1) { + String [] hitWires = hitListStr1.split("";""); // Computed in SeqPool.getGeneHits + for (String h : hitWires) msg += h + ""\n""; // boundaries only + } + if (hitListStr2!=null && hitListStr2.length()>1) { + String [] hitWires = hitListStr2.split("";""); + for (String h : hitWires) msg += h + ""\n""; + } + + if (exonList!=null) { + msg += tok[1] + ""\n"" + SeqDataInfo.formatExon(exonList); + } + + if (Globals.INFO) msg += ""\nIdx="" + annot_idx + ""\n""; + + String title = name + ""; "" + tok[0]; + + new TextShowInfo(parentFrame, title, msg, this); + } + catch (Exception e) {ErrorReport.print(e, ""Creating genepopup"");} + } + + public String toString() { + String x = String.format(""%-12s "", seqObj.getFullName()); + x += String.format(""%-8s [Rect %.2f,%.2f,%.2f,%.2f] [Seq: %d,%d]"", fullTag, + rect.x,rect.y,rect.width, rect.height, start, end); + if (itype==GENE_INT) + x += String.format("" [HRect %.2f,%.2f,%.2f,%.2f]"", + hoverGeneRect.x,hoverGeneRect.y,hoverGeneRect.width, hoverGeneRect.height); + return x; + } + + /****************************************************************** + * XXX settings + */ + protected int isMatchGeneN(String gene) {// for Sequence Filter Gene# search + if (!strGeneNum.equals(gene)) return -1; + return start + ((end-start)/2); + } + + public void setIsPopup(boolean b) { // Called for gene only on popup; Annotation=true; TextShowInfo=false + isPopup=b; + if (exonVec!=null) + for (Annotation ad : exonVec) ad.isPopup=b; + } + protected void setIsHitPopup(boolean b) { // Called for gene when searched on (not turned off) + isHitPopup=b; + if (exonVec!=null) + for (Annotation ad : exonVec) ad.isHitPopup=b; + } + protected void setIsSelectedGene(boolean b) { // Called for filtered gene (never turned off) + isSelectedGene=b; + if (exonVec!=null) + for (Annotation ad : exonVec) ad.isSelectedGene=b; + } + + /* g2xN methods */ + protected boolean isHighG2xN() {return isG2xN;} // hit and gene highlighted + + protected void setIsG2xN(boolean b) { // Sequence.setAnnoG2xN + isG2xN = b; // sets for Gene object + if (exonVec!=null) + for (Annotation ad : exonVec) ad.isG2xN = b; // sets exons object + } + + //////////////////////////////////////////////////////// + // for TextShowSeq to sort exons + public static Comparator getExonStartComparator() { + return new Comparator() { + public int compare(Annotation a1, Annotation a2) { + return a2.start - a1.start; + } + }; + } + /*********************************************************************** + * Values used in the database to represent annotation types. + */ + private static final float crossWidth= (float) 2.0; // the width of the line in the cross + + protected static final int GENE_INT = 0; + protected static final int EXON_INT = 1; + protected static final int GAP_INT = 2; + protected static final int CENTROMERE_INT = 3; + protected static final int numTypes = 4; + + // accessed and changed by ColorDialog - do not change + public static Color geneColor; + public static Color gapColor; + public static Color centromereColor; + public static Color exonColorP; + public static Color exonColorN; + public static Color geneHighColor; + + static { + PropertiesReader props = new PropertiesReader(Globals.class.getResource(""/properties/annotation.properties"")); + geneColor = props.getColor(""geneColor""); + gapColor = props.getColor(""gapColor""); + centromereColor = props.getColor(""centromereColor""); + exonColorP = props.getColor(""exonColorP""); + exonColorN = props.getColor(""exonColorN""); + geneHighColor = props.getColor(""geneHighColor""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/SeqPool.java",".java","14571","423","package symap.sequence; + +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Vector; +import java.util.HashMap; +import java.util.TreeMap; + +import database.DBconn2; +import symap.Globals; +import symap.mapper.HitData; +import symap.mapper.SeqHits; +import util.ErrorReport; + +/** + * Load data for Sequence Track + * Gene overlap placement algorithm + * Conserved genes (g2xN for Sfilter) + */ +public class SeqPool { + private DBconn2 dbc2; + + protected SeqPool(DBconn2 dbc2) { this.dbc2 = dbc2;} // called from Sequence when it is created + + /** XXX database methods ***/ + protected int loadChrSize(Sequence seqObj) { + try { + int grpIdx = seqObj.getGroup(); + String size_query = + ""SELECT (SELECT length FROM pseudos WHERE grp_idx="" + grpIdx + "") as size, ""+ + "" (SELECT name FROM xgroups WHERE idx="" + grpIdx + "") as name; ""; + + int size = dbc2.executeInteger(size_query); + return size; + } + catch (Exception e) {ErrorReport.print(e, ""Cannot get genome size""); return 0;} + } + /** + * Called by Sequence object in init + * Annotation Vector = enter annotation objects + */ + protected synchronized String loadSeqData(Sequence seqObj, Vector annoVec) { + int grpIdx = seqObj.getGroup(); + + String name=null, type, desc; + int start, end; + String strand, tag; + int annot_idx, genenum, gene_idx, numhits, itype; + + ResultSet rs = null; + try { + String size_query = + ""SELECT (SELECT length FROM pseudos WHERE grp_idx="" + grpIdx + "") as size, ""+ + "" (SELECT name FROM xgroups WHERE idx="" + grpIdx + "") as name; ""; + + rs = dbc2.executeQuery(size_query); + rs.next(); // a row no matter what + + if (rs.wasNull()) { + System.err.println(""No information in db found for Sequence with group id ""+grpIdx); + return null; + } + name = rs.getString(2); + + HashMap geneMap = new HashMap (); + + String annot_query = + ""SELECT idx, type,name,start,end,strand, genenum, gene_idx, tag, numhits FROM pseudo_annot "" + + "" WHERE grp_idx="" + grpIdx + "" and ""; + + for (int i=0; i<2; i++) { + String sql = (i==0) ? "" type='"" + Globals.geneType + ""'"" + : "" (type!='"" + Globals.geneType + ""' && type!='"" + Globals.pseudoType + ""')""; + rs = dbc2.executeQuery(annot_query + sql + "" order by start ASC""); + while (rs.next()) { + annot_idx = rs.getInt(1); + type = rs.getString(2); + desc = rs.getString(3); + start = rs.getInt(4); + end = rs.getInt(5); + strand = rs.getString(6); + genenum = rs.getInt(7); + gene_idx = rs.getInt(8); + tag = rs.getString(9); + numhits = rs.getInt(10); + + tag = (tag==null || tag.contentEquals("""")) ? type : tag; + if (type.equals(Globals.geneType)) itype = Annotation.GENE_INT; + else if (type.equals(Globals.exonType)) itype = Annotation.EXON_INT; + else if (type.equals(Globals.gapType)) itype = Annotation.GAP_INT; + else if (type.equals(Globals.centType)) itype = Annotation.CENTROMERE_INT; + else { + itype=Annotation.numTypes+1; + System.out.println(tag + "" unknown type: "" + type); + } + + Annotation aObj = new Annotation(seqObj, desc,itype,start,end,strand, tag, gene_idx, annot_idx, genenum, numhits); + annoVec.add(aObj); + + if (i==0) geneMap.put(annot_idx, aObj); + else if (type.equals(""exon"")) { + Annotation gObj = geneMap.get(gene_idx); + if (gObj!=null) gObj.addExon(aObj); + } + } + } + rs.close(); + geneMap.clear(); + + // Sort the annotations by type (ascending order) so that 'exons' are drawn on top of 'genes'. + Collections.sort(annoVec, + new Comparator() { + public int compare(Annotation a1, Annotation a2) { + if (a1.isGene() && a2.isGene()) { + if (a1.getGeneNum()==a2.getGeneNum()) return a1.getStart()-a2.getStart(); + return a1.getGeneNum()-a2.getGeneNum(); // sort on gene# + } + return (a1.getType() - a2.getType()); + } + } + ); + + } catch (Exception sql) {ErrorReport.print(sql, ""SQL exception acquiring sequence data."");} + + return name; + } + protected synchronized void close() {} + + protected int getNumAllocs(int grpIdx) { // exactly alloc correct size for Sequence.allAnnoVec + try { + return dbc2.executeCount(""select count(*) from pseudo_annot where grp_idx="" + grpIdx); + } + catch (Exception e) {ErrorReport.print(e, ""Getting number of annotations for "" + grpIdx); return 0;} + } + // for popup + protected TreeMap getGeneHits(int geneIdx, int grpIdx, boolean isAlgo1) { + TreeMap hitMap = new TreeMap (); + try { + ResultSet rs = dbc2.executeQuery(""select pha.hit_idx, pha.olap, pha.exlap "" + + "" from pseudo_hits_annot as pha "" + + "" join pseudo_annot as pa on pa.idx=pha.annot_idx "" + + "" where pha.annot_idx="" + geneIdx + "" and pa.grp_idx="" + grpIdx); + while (rs.next()) { + int hitIdx = rs.getInt(1); + int olap = rs.getInt(2); + int exlap = rs.getInt(3); + String scores = ""Gene "" + olap + ""%""; + if (!isAlgo1) scores += "" Exon "" + exlap + ""%""; + hitMap.put(hitIdx, scores); + } + return hitMap; + } + catch (Exception e) {ErrorReport.print(e, ""Getting number of annotations for "" + geneIdx); return hitMap;} + } + /******************************************************* + * XXX Gene placement algorithm: Called during init(); used in build(); adjusts x coord for overlapping genes + */ + private final int OVERLAP_OFFSET=12; + protected void buildOlap(HashMap olapMap, Vector geneVec) { + int lastGeneNum=-1; + Vector numList = new Vector (); + + for (Annotation annot : geneVec) { + if (annot.getGeneNum() == lastGeneNum) { + numList.add(annot); + continue; + } + + buildPlace(olapMap, numList, lastGeneNum); + numList.clear(); + + lastGeneNum = annot.getGeneNum(); + numList.add(annot); + } + buildPlace(olapMap, numList, lastGeneNum); + + if (olapMap.size()==0) olapMap.put(-1,-1); // need at least one value so will not compute again + } + /******************************************************* + * Compute how to display overlapping genes based on genenum + * uses genenum to find set of overlapping, + * but does not use genenum suffix (uses same overlap check as in AnnoLoadPost.computeGeneNum) + */ + private void buildPlace(HashMap olapMap, Vector numList, int lastGeneNum) { + try { + if (numList.size()==1) return; + if (numList.size()==2) { // get(0) has no offset + olapMap.put(numList.get(1).getAnnoIdx(), OVERLAP_OFFSET); + return; + } + // Create vector ordered by length + Vector gdVec = new Vector (); + for (Annotation annot : numList) gdVec.add(new GeneData(annot)); + + Collections.sort(gdVec, + new Comparator() { + public int compare(GeneData a1, GeneData a2) { + if (a1.start!=a2.start) return (a1.start - a2.start); // it does not always catch =start + return (a2.len - a1.len); + } + }); + // first is level 0; + for (int i=1; i= 0) lev[gdj.level]++; + } + + if (lev[0]==0) gdi.level = 0; + else if (lev[1]==0) gdi.level = 1; + else if (lev[2]==0) gdi.level = 2; + else { + if (lev[0] gidxRefVec = (isRefSeq1L) ? hitsObjL.getSeqObj1().getGeneIdxVec() : + hitsObjL.getSeqObj2().getGeneIdxVec(); + + HashMap gnMarkMap = new HashMap (); //geneIdx, mark class + for (int idx : gidxRefVec) gnMarkMap.put(idx, new Mark()); + gidxRefVec.clear(); + + /* Mark */ + // Visible g2 - add hd and vis + int cntNoGene=0; + Vector visHitSetL = hitsObjL.getVisG2Hits(); + + for (HitData hd : visHitSetL) { + int idx = (isRefSeq1L) ? hd.getAnnot1() : hd.getAnnot2(); + if (gnMarkMap.containsKey(idx)) { + Mark mk = gnMarkMap.get(idx); + mk.addL(hd, true); + } + else if (cntNoGene++<2) Globals.dprt(""No geneIdx "" + idx + "" for hit "" + hd.getHitNum()); + } + visHitSetL.clear(); + + Vector visHitSetR = hitsObjR.getVisG2Hits(); + for (HitData hd : visHitSetR) { + int idx = (isRefSeq1R) ? hd.getAnnot1() : hd.getAnnot2(); + if (gnMarkMap.containsKey(idx)) { + Mark mk = gnMarkMap.get(idx); + mk.addR(hd, true); + } + else if (cntNoGene++<2) Globals.dprt(""No geneIdx "" + idx + "" for hit "" + hd.getHitNum()); + } + visHitSetR.clear(); + + if (cntNoGene>0) { // should not happen... + System.out.println(""Possible sync problem - genes not found: "" + cntNoGene); + return; + } + + // Filtered g2 - complete g2 if no existing hit-wire, only add one + Vector invHitSetL = hitsObjL.getInVisG2Hits(); + for (HitData hd : invHitSetL) { + int idx = (isRefSeq1L) ? hd.getAnnot1(): hd.getAnnot2(); + Mark mk = gnMarkMap.get(idx); + if (mk.oHitArrL==null && mk.oHitArrR!=null) mk.addL(hd, false); + } + invHitSetL.clear(); + + Vector invHitSetR = hitsObjR.getInVisG2Hits(); + for (HitData hd : invHitSetR) { + int idx = (isRefSeq1R) ? hd.getAnnot1(): hd.getAnnot2(); + Mark mk = gnMarkMap.get(idx); + if (mk.oHitArrL!=null && mk.oHitArrR==null) mk.addR(hd, false); + } + invHitSetR.clear(); + + /* Highlight */ + // Green: Highlight visible g2/g1 + for (Mark mk : gnMarkMap.values()) { + if (mk.oHitArrL!=null) { + for (int i=0; i g1HitSetL = hitsObjL.getVisG1Hits(side0); + for (HitData hd : g1HitSetL) { + int idx = (isRefSeq1L) ? hd.getAnnot1(): hd.getAnnot2(); + if (!gnMarkMap.containsKey(idx)) continue; + + Mark mk = gnMarkMap.get(idx); + if (!mk.doneL && mk.oHitArrR!=null) hd.setForceG2xN(true); + } + g1HitSetL.clear(); + + side0 = (isRefSeq1R) ? 2 : 1; + Vector g1HitSetR = hitsObjR.getVisG1Hits(side0); + for (HitData hd : g1HitSetR) { + int idx = (isRefSeq1R) ? hd.getAnnot1(): hd.getAnnot2(); + if (!gnMarkMap.containsKey(idx)) continue; + + Mark mk = gnMarkMap.get(idx); + if (!mk.doneR && mk.oHitArrL!=null) hd.setForceG2xN(true); + } + g1HitSetR.clear(); + + gnMarkMap.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Finding g2xN genes"");} + } + + private class Mark { + boolean doneL=false, doneR=false; + ArrayList oHitArrL=null, oHitArrR=null; + ArrayList bVisArrL=null, bVisArrR=null; + + private void addL(HitData hd, boolean vis) { + if (oHitArrL==null) { + oHitArrL = new ArrayList (3); + bVisArrL= new ArrayList (3); + } + oHitArrL.add(hd); + bVisArrL.add(vis); + } + private void addR(HitData hd, boolean vis) { + if (oHitArrR == null) { + oHitArrR = new ArrayList (3); + bVisArrR = new ArrayList (3); + } + oHitArrR.add(hd); + bVisArrR.add(vis); + } + private boolean isUseFilt(boolean isL) { // both sides have hits, one filt one not + if (oHitArrL==null || oHitArrR==null) return false; + if ( isL && !bVisArrL.get(0) && bVisArrR.get(0)) return true; // force filtered L + if (!isL && bVisArrL.get(0) && !bVisArrR.get(0)) return true; // force filtered R + return false; + } + + private boolean isG2(boolean isBoth) { + if (isBoth) { + return oHitArrL!=null && oHitArrR!=null; + } + return (oHitArrL==null && oHitArrR!=null) || (oHitArrL!=null && oHitArrR==null); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/Sequence.java",".java","53392","1505","package symap.sequence; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.awt.font.FontRenderContext; +import java.awt.font.TextLayout; +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.Vector; + +import javax.swing.JComponent; + +import java.util.HashMap; +import java.util.TreeMap; + +import props.PropsDB; +import props.PropertiesReader; +import symap.Globals; +import symap.closeup.TextShowSeq; +import symap.drawingpanel.DrawingPanel; +import symap.frame.HelpListener; +import symap.mapper.HitData; +import symap.mapper.SeqHits; +import util.Utilities; +import util.Popup; +import util.ErrorReport; + +/** + * The Sequence track for a chromosome. Called from DrawingPanel + * Has a vector of annotations, which it also draws. The hit is drawn in this rectangle by PseudoPseudoHits + * Sequence & TrackHolder are 1-1; get replaced with different sequence unless a current sequence uses. + */ +public class Sequence implements HelpListener, KeyListener,MouseListener,MouseMotionListener,MouseWheelListener { + protected int grpIdx=Globals.NO_VALUE; + protected String chrName; // e.g. Chr01 + protected int projIdx=Globals.NO_VALUE, otherProjIdx=Globals.NO_VALUE; + private String projectName, displayName, otherProjName; + protected int chrSize = 0; // full chr size, static; was long + public int position; // track position; public for SeqHits. + protected int orient = Globals.LEFT_ORIENT; // right (-1) center(0) left (1) + private Color bgColor; + private TextLayout titleLayout; + + protected SeqHits hitsObj1=null, hitsObj2=null; // Obj2 for 3-track; + private boolean isQuery1=false, isQuery2=false;// True => this sequence is Query (pseudo_hits.annot1_idx); + + private SeqPool seqPool; + private Vector ruleList= new Vector(15,2); + protected Vector allAnnoVec = new Vector(1); // include exons, needs initial size; see loadAnnoFromDB + private Vector geneVec = new Vector (); // vector for faster searching; + private Point2D.Float headerPoint = new Point2D.Float(), footerPoint = new Point2D.Float(); + private TextLayout headerLayout = null, footerLayout = null; + + private HashMap olapMap = new HashMap (); // for overlapping genes; + + /******* Track ************************************/ + private Rectangle2D.Double rect = new Rectangle2D.Double(); // blue track rectangle + protected Dimension dimension = new Dimension(); + protected double height=Globals.NO_VALUE, // blue track height, can change + width=DEFAULT_WIDTH; // blue track width (w/o ruler or anno), static + protected int chrDisplayStart = 0, chrDisplayEnd = 0; // displayed start, end; changes with zoom + + private Rectangle dragRect = new Rectangle(); + private Point dragPoint = new Point(), trackOffset= new Point(); + + private Point adjustMoveOffset = new Point(); + private Point2D.Float titlePoint = new Point2D.Float(); + private Point2D defaultTrackOffset = defaultSequenceOffset; + protected double defaultBpPerPixel=1, bpPerPixel=1; // MIN_DEFAULT_BP_PER_PIXEL + private double startResizeBpPerPixel=Globals.NO_VALUE; + private int curCenter=0, curWidth=0; // for +/- buttons + + private boolean hasLoad, hasBuild, firstBuild = true; + + private DrawingPanel drawingPanel; + private TrackHolder holder; + private PropsDB propDB; + protected Sfilter sfilObj; + + private int distance_for_anno = 0; + + private int nG2xN=0; // 2=both, 1=one, 0-none + private String buildCntMsg="""", paintCntMsg=""""; + private void dprt(String msg) {symap.Globals.dprt(""SQ: "" + msg);} + + /** the Sequence object is created when 2D is started */ + public Sequence(DrawingPanel dp, TrackHolder holder) { + this.drawingPanel = dp; + this.holder = holder; + + if (holder.getTrack() != null) this.bgColor = holder.getTrack().bgColor; // maintain color when ""back to block view"" selected + if (holder.getTrack() != null) this.position = holder.getTrack().position; // maintain position when ""back to block view"" selected + + propDB = dp.getPropDB(); + + this.seqPool = new SeqPool(dp.getDBC()); + } + + public void setup(int projIdx, int grpIdx) { // Sequence, Drawing panel + this.grpIdx = grpIdx; + this.projIdx = projIdx; + displayName = propDB.getDisplayName(projIdx); + projectName = propDB.getName(projIdx); + if (Utilities.isEmpty(displayName)) displayName=projectName; // need for new projects; + + loadAnnosFromDB(); + + trackOffset.setLocation((int)defaultTrackOffset.getX(),(int)defaultTrackOffset.getY()); + dragPoint.setLocation(0,0); + titlePoint.setLocation(0,0); + dimension.setSize(0,0); + adjustMoveOffset.setLocation(Globals.NO_VALUE,Globals.NO_VALUE); + dragRect.setRect(0,0,Globals.NO_VALUE,Globals.NO_VALUE);; + } + + // Set the annotation vector here + private boolean loadAnnosFromDB() { // resetData, setup + try { + int n = seqPool.getNumAllocs(grpIdx); + allAnnoVec = new Vector (n); + + chrSize = seqPool.loadChrSize(this); + chrName = seqPool.loadSeqData(this, allAnnoVec); // Add annotations to allAnnoVec, and gnSize value + if (allAnnoVec.size() >0) { + int geneLen=0; + for (Annotation aObj : allAnnoVec) { + if (aObj.isGene()) { + geneVec.add(aObj); + geneLen += aObj.getGeneLen(); + } + } + if (geneVec.size()>0) { + int avg_gene = (geneVec.size()>0) ? (int)(geneLen/geneVec.size()) : 0; + distance_for_anno = avg_gene/GENES_FOR_ANNOT_DESC; + if (distance_for_anno1;} // hitObj2 is not known when filter created + /** + * XXX Build layout: Sets up the drawing objects for this sequence. Called by DrawingPanel and Track + * The Gene boxes are drawn in Annotations.setRectangle and its paintComponent + * The Hit Length, Hit %Id Value and Bar are drawn in mapper.SeqHits.DrawHits.paintHitLen and its paintComponent + */ + public boolean buildGraphics() { // DrawingPanel.buildAll & firstViewBuild; Sequence.mouseDragged + if (hasBuild) return true; + if (!hasLoad) return false; + if (chrDisplayEnd==0 || chrDisplayEnd==chrDisplayStart) return false; // Timing issue from dotplot + if (allAnnoVec.size() == 0) sfilObj.bShowAnnot = sfilObj.bShowGeneNum = false; + + if (firstBuild) { + bpPerPixel = (chrDisplayEnd - chrDisplayStart) / getAvailPixels(); + if (bpPerPixel < MIN_DEFAULT_BP_PER_PIXEL) bpPerPixel = MIN_DEFAULT_BP_PER_PIXEL; + else if (bpPerPixel > MAX_DEFAULT_BP_PER_PIXEL) bpPerPixel = MAX_DEFAULT_BP_PER_PIXEL; + + defaultBpPerPixel = bpPerPixel; + } + + TextLayout layout; + FontRenderContext frc; + Rectangle2D bounds; + double x, y, h, x1, x2, tx, ty; + Rectangle2D.Double totalRect = new Rectangle2D.Double(); + + if (height > 0) { // after 1st build + int diff = Math.abs(chrDisplayEnd-chrDisplayStart); + double bp = BpNumber.getBpPerPixel(diff, height); // diff/height + if (bp > 0) bpPerPixel = bp; + } + // this started happening with later Java versions if they click too fast + double dif = getPixelValue(chrDisplayEnd) - getPixelValue(chrDisplayStart); + if (!(dif > 0 && dif <= MAX_PIXEL_HEIGHT)) { // make popup + Popup.showWarningMessage(""Unable to size sequence view. Try again. ("" + chrDisplayStart + "","" + chrDisplayEnd + "")""); + if (height == Globals.NO_VALUE) height = getAvailPixels(); + bpPerPixel = (chrDisplayEnd-chrDisplayStart)/height; + } + int len = chrDisplayEnd - chrDisplayStart; + rect.setRect(trackOffset.getX(), trackOffset.getY(), width, getPixelValue(len)); // chr rect + + totalRect.setRect(0, 0, rect.x + rect.width + 2, rect.y + rect.height + 2); + frc = getFontRenderContext(); + + // Setup the sequence ruler + ruleList.clear(); + if (sfilObj.bShowRuler) { + if (orient == Globals.LEFT_ORIENT) { + x1 = rect.x - OFFSET_SMALL; + x2 = x1 - RULER_LINE_LENGTH; + } else if (orient == Globals.RIGHT_ORIENT) { + x1 = rect.x + rect.width + OFFSET_SMALL; + x2 = x1 + RULER_LINE_LENGTH; + } else { // center + x1 = rect.x + rect.width - OFFSET_SMALL; + x2 = x1 - RULER_LINE_LENGTH; + } + h = rect.y + rect.height; + double bpSep = SPACE_BETWEEN_RULES * bpPerPixel; + + for (y = rect.y; y < h + SPACE_BETWEEN_RULES; y += SPACE_BETWEEN_RULES) { + if (y < h && y > h - SPACE_BETWEEN_RULES) continue; + + if (y > h) y = h; + Rule rObj = new Rule(unitColor, unitFont); + rObj.setLine(x1, y, x2, y); + + double bp = BpNumber.getCbPerPixel(bpPerPixel, (sfilObj.bFlipped ? h-y : y-rect.y)) + chrDisplayStart; + String num = BpNumber.getFormatted(bpSep, bp, bpPerPixel); + layout = new TextLayout(num, unitFont, frc); + bounds = layout.getBounds(); + ty = y + (bounds.getHeight() / 2.0); + totalRect.height = Math.max(totalRect.height, ty); + totalRect.y = Math.min(totalRect.y, ty); + + if (orient == Globals.RIGHT_ORIENT) { + tx = x2 + OFFSET_SMALL; + totalRect.width = Math.max(totalRect.width, bounds.getWidth() + bounds.getX() + tx); + } + else { + tx = x2 - OFFSET_SMALL - bounds.getWidth() - bounds.getX(); + totalRect.x = Math.min(totalRect.x, tx); + } + rObj.setText(layout, tx, ty); + ruleList.add(rObj); + } + } + + // Setup the annotations + boolean isRight = (orient == Globals.RIGHT_ORIENT); + double lastStart=0; + int lastInc=1; + + getHolder().removeAll(); + Rectangle2D centRect = new Rectangle2D.Double(rect.x+1,rect.y,rect.width-2,rect.height); + + if (olapMap.size()==0) seqPool.buildOlap(olapMap, geneVec); // builds first time only + + int cntAnno=0; + // XXX Sorted by genes (genenum, start), then exons + Annotation last=null; + for (Annotation annot : allAnnoVec) { + if ( (annot.isGap() && !sfilObj.bShowGap) + || (annot.isCentromere() && !sfilObj.bShowCentromere) + || ((annot.isGene() || annot.isExon()) && !sfilObj.bShowGene) ) + { + annot.clear(); + continue; // Does not display track if, return true; + } + + // Display gene: first Calc displayWidth, hoverWidth and offset for gene + double dwidth = rect.width, hwidth=0; + int offset=0; + + if (annot.isGene()) { + hwidth = EXON_WIDTH; + dwidth = EXON_WIDTH/GENE_DIV; + if (olapMap.containsKey(annot.getAnnoIdx())) offset = olapMap.get(annot.getAnnoIdx()); + } + else if (annot.isExon()) { + dwidth = EXON_WIDTH; + if (olapMap.containsKey(annot.getGeneIdx())) offset = olapMap.get(annot.getGeneIdx()); + } + if (offset>0 && isRight) offset = -offset; + + annot.setRectangle(centRect, chrDisplayStart, chrDisplayEnd,bpPerPixel, dwidth, hwidth, sfilObj.bFlipped, offset, + sfilObj.bHighGenePopup, sfilObj.bShowGeneLine, sfilObj.bShowGeneNum, sfilObj.bShowGeneNumHit, nG2xN); + + if (last!=null) annot.setLastY(last); // annotation are separated, used during paint; + last=annot; + + if (annot.isGene() && annot.isVisible()) cntAnno++; //isVis needs rect set; + } // end for loop of (all annotations) + + buildCntMsg = String.format(""Genes: %,d"", cntAnno); + + if (sfilObj.bShowAnnot || sfilObj.bShowAnnotHit) { // Gray anno box + if (symap.Globals.DEBUG) { + String bp = Utilities.kText((int) bpPerPixel); + buildCntMsg += String.format(""\nAnnotation: if x(%s) distance_for_anno) + : ((int)bpPerPixel > (distance_for_anno*2)); + if (ifNoShow) buildCntMsg += ""\n\nZoom in for annotation""; + else { + double lastBP=rect.y + rect.height; + for (Annotation annot : allAnnoVec) { + if (!(annot.isGene() && annot.hasDesc() && annot.isVisible())) continue; + if (sfilObj.bShowAnnotHit && !annot.showGeneHasHit()) continue; + + x1 = isRight ? (rect.x + rect.width + RULER_LINE_LENGTH + 2) : rect.x; + x2 = isRight ? x1 + RULER_LINE_LENGTH : x1 - RULER_LINE_LENGTH; + + ty = annot.getY1(); + if (lastStart+OVERLAP_OFFSET>ty) { + x1 = x1 + (lastInc*OVERLAP_OFFSET); + lastInc++; + if (lastInc>=4) lastInc=1; + } + else lastInc=1; + lastStart=ty; + + TextBox tb = new TextBox(annot.getGeneBoxDesc(),unitFont, (int)x1, (int)ty, annot.getBorderColor()); + if (tb.getLowY()>lastBP) continue; // if flipped, this may be first, so do not break + + getHolder().add(tb); // adds it to the TrackHolder JComponent + + bounds = tb.getBounds(); + totalRect.height = Math.max(totalRect.height, ty); // adjust totalRect for this box + totalRect.y = Math.min(totalRect.y, ty); + if (isRight) { + tx = x2 + OFFSET_SMALL; + totalRect.width = Math.max(totalRect.width, bounds.getWidth()+bounds.getX()+tx); + } + else { + tx = x2-OFFSET_SMALL-bounds.getWidth()-bounds.getX(); + totalRect.x = Math.min(totalRect.x, tx); + } + } + } + } + + // Set header and footer + bounds = new Rectangle2D.Double(0, 0, 0, 0); + x = (rect.x + (rect.width / 2.0)) - (bounds.getX() + (bounds.getWidth() / 2.0)); + if (sfilObj.bFlipped) y = rect.y + rect.height + OFFSET_SPACE + bounds.getHeight(); + else y = rect.y - OFFSET_SPACE; + headerPoint.setLocation((float) x, (float) y); + + totalRect.width = Math.max(totalRect.width, x + bounds.getX() + bounds.getWidth()); + totalRect.x = Math.min(totalRect.x, x); + totalRect.y = Math.min(totalRect.y, y - bounds.getHeight()); + + footerLayout = new TextLayout(BpNumber.getFormatted(chrDisplayEnd-chrDisplayStart+1, bpPerPixel)+ + "" of ""+BpNumber.getFormatted(chrSize, bpPerPixel), footerFont, frc); + bounds = footerLayout.getBounds(); + x = (rect.x + (rect.width / 2.0)) - (bounds.getX() + (bounds.getWidth() / 2.0)); + if (sfilObj.bFlipped) y = rect.y - OFFSET_SPACE; + else y = rect.y + rect.height + OFFSET_SPACE + bounds.getHeight(); + footerPoint.setLocation((float) x, (float) y); + + totalRect.width = Math.max(totalRect.width, x + bounds.getX() + bounds.getWidth()); + totalRect.x = Math.min(totalRect.x, x); + totalRect.height = Math.max(totalRect.height, y); + + totalRect.width = totalRect.width - totalRect.x; + totalRect.height = totalRect.height - totalRect.y; + dimension.setSize(Math.ceil(totalRect.width) + defaultSequenceOffset.getX(), + Math.ceil(totalRect.height)+ defaultSequenceOffset.getY()); + + // Offset everything + rect.x -= totalRect.x; + rect.y -= totalRect.y; + for (Rule rule : ruleList) + rule.setOffset(totalRect.x, totalRect.y); + for (Annotation annot : allAnnoVec) + annot.setOffset(totalRect.x-1, totalRect.y); + + headerPoint.x -= totalRect.x; + headerPoint.y -= totalRect.y; + footerPoint.x -= totalRect.x; + footerPoint.y -= totalRect.y; + + setTitle(); + hasBuild = true; + firstBuild = false; + + return true; + } + private void setTitle() {// Sequence.build + String title = getTitle(); + if (title==null) { + title=""bug""; + dprt(""no title for "" + chrName); + } + titleLayout = new TextLayout(title,titleFont,getFontRenderContext()); + Rectangle2D bounds = titleLayout.getBounds(); + Point2D point = getTitlePoint(bounds); + + if (dimension.getWidth() < point.getX() + bounds.getX() + bounds.getWidth()) { + dimension.setSize(point.getX() + bounds.getX() + bounds.getWidth(), dimension.getHeight()); + } + titlePoint.setLocation((float) point.getX(), (float) point.getY()); + + if (holder != null) + holder.setPreferredSize(dimension); + } + private Point2D getTitlePoint(Rectangle2D titleBounds) { + Rectangle2D headerBounds = (sfilObj.bFlipped ? footerLayout.getBounds() : /*headerLayout.getBounds()*/new Rectangle2D.Double(0, 0, 0, 0)); + Point2D headerP = (sfilObj.bFlipped ? footerPoint : headerPoint); + Point2D point = new Point2D.Double((rect.getWidth() / 2.0 + rect.x) - (titleBounds.getWidth() / 2.0 + titleBounds.getX()), + headerP.getY() - headerBounds.getHeight() - titleOffset.getY()); + + if (point.getX() + titleBounds.getX() + titleBounds.getWidth() > dimension.getWidth()) + point.setLocation(dimension.getWidth()- (titleBounds.getX() + titleBounds.getWidth()), point.getY()); + + if (point.getX() < titleOffset.getX()) + point.setLocation(titleOffset.getX(), point.getY()); + + return point; + } + private FontRenderContext getFontRenderContext() { + if (holder != null && holder.getGraphics() != null) + return ((Graphics2D)holder.getGraphics()).getFontRenderContext(); + return null; + } + /***********************************************************************************/ + public void paintComponent(Graphics g) { // TrackHolder.paintComponent + if (!hasBuild) return; + + Graphics2D g2 = (Graphics2D) g; + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + g2.setPaint((position % REFPOS == 0 ? bgColor1 : bgColor2)); + g2.fill(rect); + g2.setPaint(border); + g2.draw(rect); + + if (sfilObj.bShowRuler) { + for (Rule rule : ruleList) + rule.paintComponent(g2); + } + // Paint Annotation + paintCntMsg=""""; + int cntCon=0; // conserved can be set and build not called, so compute here + for (Annotation annot : allAnnoVec) { + if (annot.isVisible()) { // whether in range + annot.paintComponent(g2); + if (annot.isGene() && annot.isHighG2xN()) cntCon++; + } + } + if (nG2xN!=0) { + String x = (nG2xN==2) ? ""g2x2"" : ""g2x1""; + paintCntMsg = String.format(""\n%s genes: %,d"", x, cntCon); + } + + g2.setFont(footerFont); + g2.setPaint(footerColor); + + if (headerLayout != null) headerLayout.draw(g2, headerPoint.x, headerPoint.y); + if (footerLayout != null) footerLayout.draw(g2, footerPoint.x, footerPoint.y); + + // Track code + if (position % 2 == 0) g2.setPaint(REFNAME); + else g2.setPaint(titleColor); + + if (titleLayout != null) titleLayout.draw(g2, titlePoint.x, titlePoint.y); + + if (!isCleared(dragRect)) { + g2.setPaint(dragColor); + g2.fill(dragRect); + g2.setPaint(dragBorder); + g2.draw(dragRect); + } + } + + /* Show Alignment */ + private void showCloseupAlign(int start, int end) { + if (drawingPanel == null || drawingPanel.getCloseUp() == null) return; + + try {// The CloseUp panel created at startup and reused. + if (end-start>Globals.MAX_CLOSEUP_BP) { + Popup.showWarningMessage(""Region greater than "" + Globals.MAX_CLOSEUP_K + "". Cannot align.""); + return; + } + Vector hitList1 = new Vector (); + Vector hitList2 = new Vector (); + + // one side + int numShow=1; + hitsObj1.getHitsInRange(hitList1, start, end, isQuery1); + if (hitList1.size()>0) { + int rc = drawingPanel.getCloseUp().showCloseUp(hitList1, this, start, end, + isQuery1, hitsObj1.getOtherChrName(this), numShow++); + if (rc < 0) Popup.showWarningMessage(""Error showing close up view.""); + } + // if a track has a track on both sides (e.g. 2 track shown), this is the otherside + if (hitsObj2!=null) { + hitsObj2.getHitsInRange(hitList2, start, end, isQuery2); + if (hitList2.size()>0) { + int rc = drawingPanel.getCloseUp().showCloseUp(hitList2, this, start, end, + isQuery2, hitsObj2.getOtherChrName(this), numShow); + if (rc < 0) Popup.showWarningMessage(""Error showing close up view.""); + } + } + + if (hitList1.size()==0 && hitList2.size()==0) { + Popup.showWarningMessage(""No hits found in region. Cannot align without hits.""); + return; + } + } + catch (OutOfMemoryError e) { + Popup.showOutOfMemoryMessage(); + drawingPanel.smake(""seq out of mem""); // redraw after user clicks ""ok"" + } + } + + private void showSequence(int start, int end) { + try { + if (end-start > 1000000) { + String x = ""Regions is greater than 1Mbp ("" + (end-start+1) + "")""; + if (!Popup.showContinue(""Show Sequence"", x)) return; + } + new TextShowSeq(drawingPanel, this, getProjectDisplayName(), getGroup(), start, end, isQuery1); + } + catch (Exception e) {ErrorReport.print(e, ""Error showing popup of sequence"");} + } + /** + * XXX returns the desired text for when the mouse is over a certain point. + * Called from symap.frame.HelpBar mouseMoved event + */ + public String getHelpText(MouseEvent event) { + Point p = event.getPoint(); + if (rect.contains(p)) { // within blue rectangle of track + String x = null; + int gIdx=0; + for (Annotation annot : allAnnoVec) { + if (annot.contains(p)) { + if (x==null) { + if (annot.isGap()) return annot.getHoverDesc().trim(); + if (annot.isCentromere()) return annot.getHoverDesc().trim(); + + x = annot.getHoverDesc().trim(); + gIdx = annot.getAnnoIdx(); + } + else { // Messes up with overlapping genes + if (annot.isExon() && annot.getGeneIdx()==gIdx) { + x += ""\n"" + annot.getHoverDesc().trim(); + return x; + } + } + } + } + if (x!=null) return x; + } + + return getTitle() + "" \n\n"" + buildCntMsg + ""\n"" + paintCntMsg; // + ""\n\n"" + drawingPanel.mouseFunction; + } + + public boolean isFlipped() { return sfilObj.bFlipped; } // Sfilter, TrackData + public boolean isQuery() { return isQuery1; } // mapper.SeqHits.DrawHit; + + /*****************************************************************************/ + // Called by CloseUpDialog and TextShowSeq (gene only); type is Gene or Exon + public Vector getAnnoGene(int start, int end) { + Vector out = new Vector(); + + for (Annotation a : geneVec) { + if (isOlap(start, end, a.getStart(), a.getEnd())) + out.add(a); + } + return out; + } + public Vector getAnnoExon(int gene_idx) { + Vector out = new Vector(); + + for (Annotation a : allAnnoVec) { + if (a.isExon() && a.getGeneIdx()==gene_idx) + out.add(a); + } + return out; + } + public Annotation getAnnoObj(int idx1, int idx2) { + if (idx1>0) { + for (Annotation aObj : geneVec) { + if (aObj.getAnnoIdx()==idx1) return aObj; + } + } + if (idx2>0) { + for (Annotation aObj : geneVec) { + if (aObj.getAnnoIdx()==idx2) return aObj; + } + } + return null; + } + + public String getGeneNumFromIdx(int idx1) { // called from HitData for its popup + for (Annotation aObj : geneVec) { + if (aObj.getAnnoIdx()==idx1) return aObj.getFullGeneNum(); + } + return """"; + } + + public int getGroup() {return grpIdx;} + + public String getChrName() { + String prefix = drawingPanel.getPropDB().getProperty(getProjIdx(),""grp_prefix""); + if (prefix==null) prefix = """"; + String grp = (chrName==null) ? """" : chrName; + return prefix + grp; + } + + public void setAnnotation() {sfilObj.bShowAnnot=true;} + public void setGeneNum() {sfilObj.bShowGeneNumHit=true;} // for 2D-3track query + + protected TrackData getData() {return new TrackData(this);} // TrackHolder.getTrackData + + protected String getFullName() { + return ""Track #"" + getHolder().getTrackNum() + "" "" + getProjectDisplayName() + "" "" + getChrName(); + } + public String getTitle() { + return getProjectDisplayName()+"" ""+getChrName(); + } + public String toString() { + int tn = getHolder().getTrackNum(); + String ref = (tn%2==0) ? "" REF "" : "" ""; + return ""[Sequence ""+ getFullName() + "" (Grp"" + getGroup() + "") "" + + getOtherProjectName() + "" p"" + position + "" orient "" + orient + ""] "" + ref; + } + + /************************************************ + * XXX Interface between Sfilter and DrawingPanel, etc + */ + public boolean getShowAnnot() { return sfilObj.bShowAnnot || sfilObj.bShowAnnotHit;} // drawingpanel + + //SeqHits.DrawHits + public boolean getShowHitLen() { return sfilObj.bShowHitLen; } + public boolean getShowScoreLine() { return sfilObj.bShowScoreLine; } + public boolean getShowScoreText() { return sfilObj.bShowScoreText; } + public boolean getShowHitNumText() { return sfilObj.bShowHitNumText; } + public boolean getShowBlockText() { return sfilObj.bShowBlockText; } + public boolean getShowBlock1stText(){ return sfilObj.bShowBlock1stText; } + public boolean getShowCsetText() { return sfilObj.bShowCsetText; } + public boolean getHasText() { // for drawing text on top + return sfilObj.bShowScoreText || sfilObj.bShowHitNumText + || sfilObj.bShowBlockText || sfilObj.bShowBlock1stText || sfilObj.bShowCsetText; + } + public int[] getAnnotationTypeCounts() { + int[] counts = new int[Annotation.numTypes]; + + for (Annotation a : allAnnoVec) + counts[a.getType()]++; + + return counts; + } + // Filter: enter gene# + protected int getSelectGeneCoord(String name) { // Sfilter + int mid = -1; + for (Annotation aObj : geneVec) { + mid = aObj.isMatchGeneN(name); // Sets selectGeneObj and return mid coordinate + if (mid>0) { + sfilObj.selectGeneObj = aObj; + aObj.setIsSelectedGene(true); + return mid; + } + } + return mid; + } + protected void setSelectGene(Annotation aObj) { // Filter actions and display + if (aObj==null) { + if (sfilObj.selectGeneObj!=null) { + sfilObj.selectGeneObj.setIsSelectedGene(false); + sfilObj.selectGeneObj=null; + } + } + else { + sfilObj.selectGeneObj = aObj; + aObj.setIsSelectedGene(true); + } + } + + /****************************************************************** + * Hit interface + ****************************************************************/ + /* g2xN methods */ + + // Sfilter.FilterListener.xHighG2xN called for reference track + protected void refSetG2xN(int which, boolean high) {// 2=g2x2, 1=g2x1, 0=none + if (hitsObj1!=null) hitsObj1.clearHighG2xN(); + if (hitsObj2!=null) hitsObj2.clearHighG2xN(); + + if (high) { + if (which==2) { + seqPool.computeG2xN(true, hitsObj1, hitsObj2, this); // T=G2x2 + hitsObj1.setnG2xN(2); // sets Seqhits.nG2xN, SeqHits.seqObj1.setIsG2xN(b); + hitsObj2.setnG2xN(2); // sets Seqhits.nG2xN, SeqHits.seqObj2.setIsG2xN(b); + } + else if (which==1) { + seqPool.computeG2xN(false, hitsObj1, hitsObj2, this);// F=G2x1 + hitsObj1.setnG2xN(1); hitsObj2.setnG2xN(1); + } + } + } + protected Vector getGeneIdxVec() { // seqPool.computeG2xN needs list of genes + Vector idxVec = new Vector (); + for (Annotation annot : geneVec) idxVec.add(annot.getAnnoIdx()); + return idxVec; + } + // mapper.HitData: seqPool.computeG2xN + // calls HitData.setHighAnnoG2xN(true) + // calls this method setAnnoG2xN for both tracks + // the gene anno object sets all its exon anno objects + public void setAnnoG2xN(int annot1_idx, int annot2_idx, boolean isHigh) { + for (Annotation aObj : geneVec) { + int idx = aObj.getAnnoIdx(); + if (idx==annot1_idx || idx==annot2_idx) { + aObj.setIsG2xN(isHigh); // sets isG2x2 for genes/exons; highlight exons + return; + } + } + } + public void setnG2xN(int nG2xN) {this.nG2xN=nG2xN;} // for non-ref + + // Sfilter.FilterListener; sets special flag to only show HitData.isHighG2xN=true (which are already set) + protected void showG2xN(boolean high) { + hitsObj1.setOnlyG2xN(high); + hitsObj2.setOnlyG2xN(high); + } + /////////////////////////////////////////////////////////////////// + /* mapper methods */ + public void setHighforHit(int annot1_idx, int annot2_idx, boolean isHigh) { // mapper.HitData.setIsPopup; highlight gene of hit + for (Annotation aObj : geneVec) { + int idx = aObj.getAnnoIdx(); + if (idx==annot1_idx || idx==annot2_idx) { + aObj.setIsHitPopup(isHigh); + return; + } + } + } + + public Point2D getPointForHit(int hitMidPt, int trackPos) { // mapper.seqHits & DrawHit + if (hitMidPt < chrDisplayStart) hitMidPt = chrDisplayStart; + if (hitMidPt > chrDisplayEnd) hitMidPt = chrDisplayEnd; + + double x = (trackPos == Globals.LEFT_ORIENT) ? rect.x + rect.width : rect.x; + + double y = rect.y + BpNumber.getPixelValue(hitMidPt-chrDisplayStart ,bpPerPixel); + + if (sfilObj.bFlipped) y = rect.y + rect.y + rect.height - y; + + return new Point2D.Double(x, y); + } + public Point getLocation() { // mapper.SeqHits.paintComponent + if (holder != null) return holder.getLocation(); + else return new Point(); + } + public boolean isHitInRange(int num) { // mapper.SeqHits.isVisHitWire + return num >= chrDisplayStart && num <= chrDisplayEnd; + } + public boolean isHitOlap(int hs, int he) { // mapper.SeqHits.isOlapHit; for partial hit + return isOlap(hs, he, (int) chrDisplayStart, (int) chrDisplayEnd); + } + private boolean isOlap(int s1, int e1, int s2, int e2) { + int olap = Math.min(e1,e2) - Math.max(s1,s2) + 1; + return (olap>0); + } + /************************************************************************ + * From Track + */ + public TrackHolder getHolder() { return holder;}// Called by Sequence and DrawingPanel + + /* getGraphics returns the holders graphics object if a holder exists, null otherwise.*/ + public Graphics getGraphics() { + if (holder != null) return holder.getGraphics(); + return null; + } + + protected double getMidX() {return rect.getX()+(rect.getWidth()/2.0);} // trackLayout + + public int getProjIdx() {return projIdx;} + + public String getOtherProjectName() {return otherProjName;} // Closeup + + public String getProjectDisplayName() {return displayName;} + + public double getBpPerPixel() { return bpPerPixel;} // DrawingPanel.drawToScale + + protected boolean hasLoad() {return hasLoad;} + + // Implements the +/- buttons. + // It stores the current region width and center so that (-) can exactly undo (+) even + // when the (+) expands beyond the bounds of one sequence. + public void changeAlignRegion(double factor) { // DrawingPanel + int s = chrDisplayStart; + int e = chrDisplayEnd; + int mid = (s + e)/2; + int width = (e - s)/2; + boolean showingFull = (2*width > .95*getTrackSize()); + + if (curCenter == 0) { + curCenter = mid; + curWidth = width; + } + + curWidth *= factor; + + int sNew = Math.max(1,curCenter - curWidth); + int eNew = Math.min(curCenter + curWidth,getTrackSize()); + + setStartBP(sNew, false); + setEndBP(eNew, false); + + if (showingFull && factor > 1) return; // don't scale if already at max + + double displayedWidth = (eNew - sNew)/2; + double effectiveFactor = displayedWidth/width; + + setBpPerPixel( bpPerPixel * ( 1.0 / effectiveFactor ) ); + } + public boolean fullyExpanded() { // Drawing panel + int s = getStart(); + int e = getEnd(); + if (s > 1 || e < getTrackSize()) return false; + return true; + } + public void setBpPerPixel(double bp) { // DrawingPanel; Used with +/- buttons; drawToScale; + if (bp > 0) { + height = Globals.NO_VALUE; + + if (bp != bpPerPixel) { + bpPerPixel = bp; + setTrackBuild(); + } + } + } + private void setHeight(double pixels) { // mouseDragged + pixels = Math.min(Math.max(pixels,1),MAX_PIXEL_HEIGHT); + if (height != pixels) { + height = pixels; + setTrackBuild(); + } + } + private void clearHeight() { // mouseReleased + if (height != Globals.NO_VALUE) { + height = Globals.NO_VALUE; + setTrackBuild(); + } + } + protected void setOrientation(int orientation) { // TrackHolder.setTrack + if (orientation != Globals.RIGHT_ORIENT && orientation != Globals.CENTER_ORIENT) orientation = Globals.LEFT_ORIENT; + if (orientation != orient) { + orient = orientation; + setTrackBuild(); + } + } + public void resetEnd() { // DrawingPanel, Sequence + if (chrDisplayEnd != chrSize) { + chrDisplayEnd = chrSize; + setAllBuild(); + } + } + public void resetStart() {// DrawingPanel, Sequence + if (chrDisplayStart != 0) { + chrDisplayStart = 0; + setAllBuild(); + } + } + public void setStart(int startValue) { // DrawingPanel, Sfilter; + if (startValue > chrSize) { + Popup.showWarningMessage(""Start value ""+startValue+"" is greater than size ""+chrSize+"".""); + return; + } + if (startValue < 0) { + Popup.showWarningMessage(""Start value is less than zero.""); + return; + } + if (chrDisplayStart != startValue) { + firstBuild = true; + + chrDisplayStart = startValue; + setAllBuild(); + } + } + public int setEnd(int endValue) { // DrawingPanel, Sfilter; + if (endValue < 0) { + Popup.showWarningMessage(""End value is less than zero.""); + return chrSize; + } + if (endValue > chrSize) endValue = chrSize; + + if (chrDisplayEnd != endValue) { + firstBuild = true; + + chrDisplayEnd = endValue; + setAllBuild(); + } + return endValue; + } + public void setStartBP(int startBP, boolean resetPlusMinus) { // Track, DrawingPanel, Sequence + if (startBP > chrSize) { + Popup.showWarningMessage(""Start value ""+startBP+"" is greater than size ""+chrSize+"".""); + return; + } + if (startBP < 0) { + Popup.showWarningMessage(""Start value ""+startBP+"" is less than zero.""); + return; + } + if (resetPlusMinus) curCenter = 0; + if (chrDisplayStart != startBP) { + firstBuild = true; + chrDisplayStart = startBP; + setAllBuild(); + } + } + public int setEndBP(int endBP, boolean resetPlusMinus) {// Track, DrawingPanel, Sequence + if (endBP < 0) Popup.showWarningMessage(""End value is less than zero.""); + + if (endBP > chrSize || endBP<0) endBP = chrSize; + + if (resetPlusMinus) curCenter = 0; + if (chrDisplayEnd != endBP) { + firstBuild = true; + chrDisplayEnd = endBP; + setAllBuild(); + } + return endBP; + } + public void setDefPixel() { + bpPerPixel = (chrDisplayEnd - chrDisplayStart) / getAvailPixels(); + if (bpPerPixel < MIN_DEFAULT_BP_PER_PIXEL) bpPerPixel = MIN_DEFAULT_BP_PER_PIXEL; + else if (bpPerPixel > MAX_DEFAULT_BP_PER_PIXEL) bpPerPixel = MAX_DEFAULT_BP_PER_PIXEL; + + defaultBpPerPixel = bpPerPixel; + setAllBuild(); + } + + protected void setAllBuild() { // TrackData and all methods that data + if (drawingPanel != null) + drawingPanel.setTrackBuild(); // sets hasBuild to false on all tracks + else setTrackBuild(); + } + public void setTrackBuild() {hasBuild = false; } // DrawingPanel, Sequence + + public void setWideWidth(boolean b) { + if (b) width = DEFAULT_WIDE_WIDTH; + else width = DEFAULT_WIDTH; + } + public int getStart() {return chrDisplayStart;} // Track, Sequence, Mapper + public int getEnd() {return chrDisplayEnd; } + public int getTrackSize() {return chrSize;} + + protected Dimension getDimension() {return dimension; } // TrackHolder + + protected double getValue(int cb, String units) { return BpNumber.getValue(units, cb,bpPerPixel);} // Sfilter + private double getPixelValue(int num) {return (double)num/(double)bpPerPixel;} + + private double getAvailPixels() { + return (drawingPanel.getViewHeight() - (trackOffset.getY() * 2)); + } + + private int getBP(double y) {// Sequence mouseReleased + y -= rect.getY(); + if (y < 0) y = 0; + else if (y > rect.getHeight()) y = rect.getHeight(); + y *= bpPerPixel; + y += chrDisplayStart; + + if (y != Math.round(y)) y = Math.round(y); + + if (y < chrDisplayStart) y = chrDisplayStart; + else if (y > chrDisplayEnd) y = chrDisplayEnd; + + return (int)Math.round(y); + } + + private boolean isSouthResizePoint(Point p) { + return (p.getX() >= rect.x && + p.getX() <= rect.x + rect.width && + p.getY() >= (rect.y+rect.height) - MOUSE_PADDING && + p.getY() <= (rect.y+rect.height) + MOUSE_PADDING); + } + + /**** Clear for sequence and track */ + public void clearData() { // DrawingPanel.clearData, resetData + ruleList.clear(); + allAnnoVec.clear(); + geneVec.clear(); + olapMap.clear(); + } + + private boolean isCleared(Rectangle r) { + return r.x == 0 && r.y == 0 && r.width == Globals.NO_VALUE && r.height == Globals.NO_VALUE; + } + + /*** XXX Mouse **************************/ + public void mouseDragged(MouseEvent e) { + // Track first + Cursor cursor = getCursor(); + if (cursor != null && cursor.getType() == Cursor.WAIT_CURSOR) return; + + Point p = e.getPoint(); + + if (cursor.getType() == Cursor.S_RESIZE_CURSOR) { + double height = p.getY() - rect.getY(); + if (height > 0 && height < MAX_PIXEL_HEIGHT) { + if (startResizeBpPerPixel == Globals.NO_VALUE) startResizeBpPerPixel = bpPerPixel; + setHeight(height); + if (buildGraphics()) layout(); + } + } + else if (drawingPanel.isMouseFunction()){ + if (isCleared(dragRect)) { + dragPoint.setLocation(p); + if (dragPoint.getX() < rect.x) dragPoint.setLocation(rect.x, dragPoint.getY()); + else if (dragPoint.getX() > rect.x + rect.width) dragPoint.setLocation(rect.x + rect.width, dragPoint.getY()); + if (dragPoint.getY() < rect.y) dragPoint.setLocation(dragPoint.getX(), rect.y); + else if (dragPoint.getY() > rect.y + rect.height)dragPoint.setLocation(dragPoint.getX(), rect.y + rect.height); + dragRect.setLocation(dragPoint); + dragRect.setSize(0, 0); + } else { + if (p.getX() < dragPoint.x) { + dragRect.width = dragPoint.x - p.x; + dragRect.x = p.x; + } else { + dragRect.width = p.x - dragRect.x; + } + if (p.getY() < dragPoint.y) { + dragRect.height = dragPoint.y - p.y; + dragRect.y = p.y; + } else { + dragRect.height = p.y - dragRect.y; + } + } + // match with rect + dragRect.width = (int) rect.width; + dragRect.x = (int) rect.x; + if (dragRect.height > 0 && dragRect.getY() < rect.y) { + dragRect.height = (int) (dragRect.height + dragRect.y - rect.y); + dragRect.y = (int) rect.y; + } + if (dragRect.height > 0 && dragRect.getY() + dragRect.getHeight() > rect.y + rect.height) + dragRect.height = (int) (rect.height + rect.y - dragRect.getY()); + + if (dragRect.height < 0) dragRect.height = 0; + } + + repaint(); + + // Sequence Close-up + if (!(drawingPanel.isMouseFunctionCloseup() && getCursor().getType() != Cursor.S_RESIZE_CURSOR)) return; + + Point point = e.getPoint(); + int happened = 0; + if (isCleared(dragRect)) { + dragPoint.setLocation(point); + if (dragPoint.getX() < rect.x) + dragPoint.setLocation(rect.x, dragPoint.getY()); + else if (dragPoint.getX() > rect.x + rect.width) + dragPoint.setLocation(rect.x + rect.width, dragPoint.getY()); + + if (dragPoint.getY() < rect.y) + dragPoint.setLocation(dragPoint.getX(), rect.y); + else if (dragPoint.getY() > rect.y + rect.height) + dragPoint.setLocation(dragPoint.getX(), rect.y + rect.height); + + dragRect.setLocation(dragPoint); + dragRect.setSize(0, 0); + } + else { + if (point.getX() < dragPoint.x) { + dragRect.width = dragPoint.x - point.x; + dragRect.x = point.x; + } + else + dragRect.width = point.x - dragRect.x; + + if (point.getY() < dragPoint.y) { + happened = 1; + dragRect.height = dragPoint.y - point.y; + dragRect.y = point.y; + } + else { + dragRect.height = point.y - dragRect.y; + happened = 2; + } + } + + // match with rect (do we want this?) + dragRect.width = (int) rect.width; + dragRect.x = (int) rect.x; + if (dragRect.height > 0 && dragRect.getY() < rect.y) { + dragRect.height = (int) (dragRect.height + dragRect.y - rect.y); + dragRect.y = (int) rect.y; + } + if (dragRect.height > 0 && dragRect.getY() + dragRect.getHeight() > rect.y + rect.height) + dragRect.height = (int) (rect.height + rect.y - dragRect.getY()); + if (dragRect.height < 0) + dragRect.height = 0; + + if (happened != 0) { + int mh = (int)Math.round(Globals.MAX_CLOSEUP_BP / bpPerPixel); + if (happened == 1) { + if (dragRect.height * bpPerPixel > Globals.MAX_CLOSEUP_BP) { + dragRect.height = mh; + if (dragRect.height+dragRect.y < dragPoint.y) + dragPoint.y = dragRect.height+dragRect.y; + } + } + else { + if (dragRect.height * bpPerPixel > Globals.MAX_CLOSEUP_BP) { + dragRect.y += dragRect.height - mh; + dragRect.height = mh; + if (dragPoint.y < dragRect.y) + dragPoint.y = dragRect.y; + } + } + } + } + // mouseIn click in anno space: if click on gene, popup info; else pass to parent + public void mousePressed(MouseEvent e) { + // Sequence 1st + if (e.isPopupTrigger()) { // popup on right click + String title = getTitle(); // DisplayName Chr + Point p = e.getPoint(); + if (rect.contains(p)) { // within blue rectangle of track + for (Annotation annot : geneVec) { // + if (annot.contains(p)) { // in this gene annotation + setForGenePopup(annot); + annot.popupDesc(getHolder(), title, title); + if (sfilObj.bHighGenePopup) drawingPanel.smake(""seq: mousepressed""); // to highlight + return; + } + } + } + } + // Track 2nd + Cursor cursor = getCursor(); + Point point = e.getPoint(); + + if (e.isPopupTrigger()) { + holder.showPopupFilter(e); + } + else if (cursor.getType() == Cursor.S_RESIZE_CURSOR) { } // Resize + + else { //(e.isControlDown()) { // Zoom + setCursor(Globals.CROSSHAIR_CURSOR); + if (isCleared(dragRect)) { + dragPoint.setLocation(point); + if (dragPoint.getX() < rect.x) dragPoint.setLocation(rect.x, dragPoint.getY()); + else if (dragPoint.getX() > rect.x + rect.width) dragPoint.setLocation(rect.x + rect.width, dragPoint.getY()); + if (dragPoint.getY() < rect.y) dragPoint.setLocation(dragPoint.getX(), rect.y); + else if (dragPoint.getY() > rect.y + rect.height)dragPoint.setLocation(dragPoint.getX(), rect.y + rect.height); + dragRect.setLocation(dragPoint); + dragRect.setSize(0, 0); + } + } + } + public void mouseReleased(MouseEvent e) { + // Sequence + if (drawingPanel.isMouseFunctionPop()) { + if (dragRect.getHeight() > 0 /*&& rect.contains(p)*/) { + int start = getBP( dragRect.getY() ); + int end = getBP( dragRect.getY() + dragRect.getHeight() ); + + if (sfilObj.bFlipped) { + int temp = start; + start = (int)getEnd() - end + (int)getStart(); + end = (int)getEnd() - temp + (int)getStart(); + } + + if (drawingPanel.isMouseFunctionCloseup()) showCloseupAlign(start, end); // XXX + else showSequence(start, end); + } + } + // Track + boolean needUpdate = false; + + if (e.isPopupTrigger()) { + holder.showPopupFilter(e); // this never seems to happen + } + else { // sequence.mouseRelease is first, and checks for Align or Show popup; else, comes here for zoom + if (!isCleared(dragRect) && drawingPanel.isMouseFunctionZoom()) { + try { + int newStart = getBP(dragRect.y); + int newEnd = getBP(dragRect.y+dragRect.height); + if (newEnd != newStart) { + if (sfilObj.bFlipped) { + int temp = newStart; + newStart = chrDisplayEnd - newEnd + chrDisplayStart; + newEnd = chrDisplayEnd - temp + chrDisplayStart; + } + setEndBP(newEnd, true); + setStartBP(newStart, true); + + if (drawingPanel.isMouseFunctionZoomAll()) + drawingPanel.zoomAllTracks(this, (int)newStart, (int)newEnd); + + if (!hasBuild) { + clearHeight(); // want to resize to screen + needUpdate = true; + if (drawingPanel != null) drawingPanel.smake(""seq: mouse release""); + } + } + } catch (Exception ex) {ErrorReport.print(ex, ""Exception resizing track!"");} + } + if (needUpdate) { + drawingPanel.updateHistory(); + } + clearMouseSettings(); + } + } + + public void mouseWheelMoved(MouseWheelEvent e) { + int notches = e.getWheelRotation(); + int viewSize = getEnd() - getStart() + 1; + + if (e.isControlDown()) // Zoom + zoomRange(notches, e.getPoint().getY() - rect.y + 1, viewSize); + else + scrollRange(notches, viewSize); + } + + public void mouseWheelMoved(MouseWheelEvent e, int viewSize) { + int notches = e.getWheelRotation(); + + if (e.isControlDown()) // Zoom - + zoomRange(notches, e.getPoint().getY() - rect.y + 1, viewSize); + else + scrollRange(notches, viewSize); + } + public void mouseMoved(MouseEvent e) { + Cursor c = getCursor(); + if (c == null || c.getType() != Cursor.WAIT_CURSOR) { + Point p = e.getPoint(); + + if (e.isControlDown()) // Zoom + setCursor(Globals.CROSSHAIR_CURSOR); + else if (isSouthResizePoint(p)) // Resize + setCursor(Globals.S_RESIZE_CURSOR); + else { + if (drawingPanel.isMouseFunction()) + setCursor(Globals.CROSSHAIR_CURSOR); + else { + setCursor(null); + clearMouseSettings(); + } + } + } + } + public void mouseEntered(MouseEvent e) { holder.requestFocusInWindow();} + public void mouseClicked(MouseEvent e) { } + public void mouseExited(MouseEvent e) { } + public void keyTyped(KeyEvent e) { } + public void keyPressed(KeyEvent e) { } + public void keyReleased(KeyEvent e) { } + + //** Mouse methods **/ + private void repaint() { + if (drawingPanel != null) drawingPanel.repaint(); + else if (holder != null) holder.repaint(); + } + private Cursor getCursor() { + return drawingPanel.getCursor(); + } + private void setCursor(Cursor c) { + if (c == null) drawingPanel.setCursor(Globals.DEFAULT_CURSOR); + else drawingPanel.setCursor(c); + } + private void layout() { // mouseDragged + if (holder != null && holder.getParent() instanceof JComponent) { + ((JComponent)holder.getParent()).doLayout(); + ((JComponent)holder.getParent()).repaint(); + } + else if (drawingPanel != null) { + drawingPanel.doLayout(); + drawingPanel.repaint(); + } + } + private void clearMouseSettings() { + if (!isCleared(dragRect)) { + dragRect.setRect(0,0,Globals.NO_VALUE,Globals.NO_VALUE);; + repaint(); + } + //startMoveOffset.setLocation(Globals.NO_VALUE,Globals.NO_VALUE); + adjustMoveOffset.setLocation(Globals.NO_VALUE,Globals.NO_VALUE); + dragPoint.setLocation(Globals.NO_VALUE,Globals.NO_VALUE); + startResizeBpPerPixel = Globals.NO_VALUE; + } + // Scroll wheel + // Called from mouseWheelMoved, which is called from Mapper.mouseWheelMoved + // if sequence is flipped, should go negative instead of continued positive + private void scrollRange(int notches, int viewSize) { + int curViewSize = getEnd() - getStart() + 1; + + if (curViewSize >= getTrackSize()) return; + + int offset = notches*(viewSize/mouseWheelScrollFactor); + int newStart, newEnd; + + newStart = (sfilObj.bFlipped) ? (chrDisplayStart-offset) : (chrDisplayStart+offset); + if (newStart < 0) { + newStart = 0; + newEnd = viewSize; + } + else { + newEnd = (sfilObj.bFlipped) ? (chrDisplayEnd-offset) : (chrDisplayEnd+offset); + if (newEnd > getTrackSize()) { + newStart = getTrackSize() - viewSize; + newEnd = getTrackSize(); + } + } + + setStartBP(newStart,true); + setEndBP(newEnd,true); + if (drawingPanel != null) drawingPanel.smake(""seq: scrollrange""); + } + private void zoomRange(int notches, double focus, int length) { + double r1 = (focus / rect.height) / mouseWheelZoomFactor; + double r2 = ((rect.height - focus) / rect.height) / mouseWheelZoomFactor; + if (sfilObj.bFlipped) { + double temp = r1; + r1 = r2; + r2 = temp; + } + int newStart = chrDisplayStart + (int)(length*r1*notches); + int newEnd = chrDisplayEnd - (int)(length*r2*notches); + + if (newEnd < 0) newEnd = 0; // unnecessary? + else if (newEnd > getTrackSize()) newEnd = getTrackSize(); + if (newStart < 0) newStart = 0; + else if (newStart > getTrackSize()) newStart = getTrackSize(); // unnecessary? + if (newStart < newEnd) { + setEndBP(newEnd,true); + setStartBP(newStart,true); + if (drawingPanel != null) drawingPanel.smake(""seq: zoom range""); + } + } + // called on mousePressed for Gene Popup + private void setForGenePopup(Annotation annot) { + annot.setExonList(); + + if (hitsObj1!=null) { + if (!annot.hasHitList()) { + boolean isAlgo1 = propDB.isAlgo1(projIdx, otherProjIdx); + TreeMap scoreMap = seqPool.getGeneHits(annot.getAnnoIdx(), grpIdx, isAlgo1); + if (scoreMap.size()>0) { + String hits = hitsObj1.getHitsForGenePopup(this, annot, scoreMap); + annot.setHitList(hits, scoreMap); + } + } + } + if (hitsObj2!=null) {// for 3-track + if (!annot.hasHitList2()) { + boolean isAlgo1 = propDB.isAlgo1(projIdx, otherProjIdx); + TreeMap scoreMap = seqPool.getGeneHits(annot.getAnnoIdx(), grpIdx, isAlgo1); + if (scoreMap.size()>0) { + String hits = hitsObj2.getHitsForGenePopup(this, annot, scoreMap); + annot.setHitList2(hits, scoreMap); + } + } + } + } + // The following allow the GeneNum or Annot box to only be shown if a gene has a hit that is visible + protected boolean hasAnnoHit(int x, Annotation annot) { // Called from Annot to display GeneNum if has hit + if (x==2 && hitsObj2==null) return false; + + boolean isAlgo1 = propDB.isAlgo1(projIdx, otherProjIdx); + TreeMap scoreMap = seqPool.getGeneHits(annot.getAnnoIdx(), grpIdx, isAlgo1); + if (scoreMap.size()==0) return false; + + SeqHits hitObj = (x==1) ? hitsObj1 : hitsObj2; + + String hits = hitObj.getHitsForGenePopup(this, annot, scoreMap); + if (x==1) annot.setHitList(hits, scoreMap); + else annot.setHitList2(hits, scoreMap); + return true; + } + protected boolean hasVisHit(int x, int [] hitIdxList) { // goes with hasHit for Annot + if (x==1) return hitsObj1.hasVisHit(hitIdxList); + else return (hitsObj2==null || hitsObj2.hasVisHit(hitIdxList)); + } + /************************************************************************/ + private class Rule { // was separate file; CAS575 cleanup + private Color unitColor; + private Font unitFont; + private Line2D.Double line; + private Point2D.Float point; + private TextLayout layout; + + private Rule(Color unitColor, Font unitFont) { + this.unitColor = unitColor; + this.unitFont = unitFont; + line = new Line2D.Double(); + point = new Point2D.Float(); + } + private void setLine(double x1, double y1, double x2, double y2) { + line.setLine(x1, y1, x2, y2); + } + private void setText(TextLayout textLayout, double x, double y) { + layout = textLayout; + point.setLocation((float) x, (float) y); + } + private void setOffset(double x, double y) { + line.setLine(line.x1 - x, line.y1 - y, line.x2 - x, line.y2 - y); + point.setLocation(point.x - x, point.y - y); + } + public void paintComponent(Graphics2D g2) { + if (layout != null) { + g2.setPaint(unitColor); + g2.draw(line); + g2.setFont(unitFont); + layout.draw(g2, point.x, point.y); + } + } + } + + /*************************************************************************/ + // Track + private static final int REFPOS=2; + private static final int MAX_PIXEL_HEIGHT = 10000; + private static final Color REFNAME = new Color(0,0,200); + private static final Color titleColor = Color.black; + private static final Color dragColor = new Color(255,255,255,120); + private static final Color dragBorder = Color.black; + private static final Font titleFont = new Font(""Arial"", 1, 14); + + // Sequence + private static final int OVERLAP_OFFSET = 18; + + private static final double MOUSE_PADDING = 2; + + private static final double OFFSET_SPACE = 7; // header/footer + private static final double OFFSET_SMALL = 1; + + private static final double DEFAULT_WIDTH = 90.0; // Width of track; + private static final double DEFAULT_WIDE_WIDTH = 100.0; + + protected static final double EXON_WIDTH = 15.0; // used by Annotation too + private static final int GENE_DIV = 4; // Gene is this much narrower than exon + private static final int MIN_BP_FOR_ANNOT_DESC = 500; // minimum bp for show anno + private static final int GENES_FOR_ANNOT_DESC = 20; // average distance for 20 genes + + private static final double SPACE_BETWEEN_RULES = 35.0; + private static final double RULER_LINE_LENGTH = 3.0; + + private static final double MIN_DEFAULT_BP_PER_PIXEL = 1; + private static final double MAX_DEFAULT_BP_PER_PIXEL =1000000; + + private static final Color border = Color.black; + private static Color footerColor = Color.black; + private static Font footerFont = new Font(""Arial"",0,10); + private static Font unitFont = new Font(""Arial"",0,10); + private static final Point2D defaultSequenceOffset = new Point2D.Double(20,40); + private static final Point2D titleOffset = new Point2D.Double(1,3); + private static int mouseWheelScrollFactor = 20; + private static int mouseWheelZoomFactor = 4; + + public static Color unitColor, bgColor1, bgColor2; + + static { // colors that can be set by user + PropertiesReader props = new PropertiesReader(Globals.class.getResource(""/properties/sequence.properties"")); + + unitColor = props.getColor(""unitColor""); + bgColor1 = props.getColor(""bgColor1""); + bgColor2 = props.getColor(""bgColor2""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/TrackData.java",".java","3928","123","package symap.sequence; + +/** + * The data for the Track (i.e. project name, display name, orientation, etc...) + * It is used for History, i.e back and forth + */ +public class TrackData { + private int project, otherProject; + private int orient; + + private double defaultBpPerPixel, bpPerPixel; + private int start, end, size; + private double height, width; + + private int grpIdx; + + private boolean bShowRuler, bShowGap, bShowCentromere, bShowGene, bShowHitLen, bShowScoreLine; + private boolean bShowGeneNum, bShowAnnot, bShowGeneNumHit, bShowAnnotHit; + private boolean bShowGeneLine, bHighPopupGene; + private boolean bShowScoreText, bShowHitNumText, bShowBlockText, bShowBlock1stText, bShowCsetText, bShowNoText; + + private boolean bFlipped; + private boolean bGeneNCheck; + private Annotation selectGeneObj=null; + + private boolean bHighHit2g2, bHighHit2g1, bHighHit2g0; + + // This is called every time there is a change to the Display; save current state for back button + protected TrackData(Sequence seq) { + project = seq.projIdx; + start = seq.chrDisplayStart; + end = seq.chrDisplayEnd; + size = seq.chrSize; + orient = seq.orient; + defaultBpPerPixel = seq.defaultBpPerPixel; + bpPerPixel = seq.bpPerPixel; + height = seq.height; + width = seq.width; + otherProject = seq.otherProjIdx; + + grpIdx = seq.grpIdx; + + bFlipped = seq.isFlipped(); + + Sfilter sf = seq.sfilObj; + bShowRuler = sf.bShowRuler; + bShowGap = sf.bShowGap; + bShowCentromere = sf.bShowCentromere; + bShowGene = sf.bShowGene; + bShowHitLen = sf.bShowHitLen; + bShowScoreLine = sf.bShowScoreLine; + + bShowGeneNum = sf.bShowGeneNum; + bShowGeneNumHit = sf.bShowGeneNumHit; + bShowAnnotHit = sf.bShowAnnotHit; + bShowGeneLine = sf.bShowGeneLine; + bHighPopupGene = sf.bHighGenePopup; + + bShowNoText = sf.bShowNoText; + bShowBlock1stText = sf.bShowBlock1stText; + bShowBlockText = sf.bShowBlockText; + bShowCsetText = sf.bShowCsetText; + bShowScoreText = sf.bShowScoreText; + bShowHitNumText = sf.bShowHitNumText; + + bGeneNCheck = sf.bGeneNCheck; + selectGeneObj = sf.selectGeneObj; + + bHighHit2g2 = sf.bHighG2x2; + bHighHit2g1 = sf.bHighG2x1; + bHighHit2g0 = sf.bHighG2x0; + } + + // this gets called on History back/forth to reinstate state + protected void setTrack(Sequence seq) { + Sfilter sf = seq.sfilObj; + + seq.chrDisplayStart = start; + seq.chrDisplayEnd = end; + seq.chrSize = size; + seq.projIdx = project; + seq.orient = orient; + seq.defaultBpPerPixel = defaultBpPerPixel; + seq.bpPerPixel = bpPerPixel; + seq.height = height; + seq.width = width; + seq.otherProjIdx = otherProject; + seq.setAllBuild(); // set Track.hasBuild = false; for all seqs + + seq.grpIdx = grpIdx; + sf.xFlipSeq(bFlipped); + sf.bShowRuler = bShowRuler; + sf.bShowGap = bShowGap; + sf.bShowCentromere = bShowCentromere; + sf.bShowGene = bShowGene; + sf.bShowHitLen = bShowHitLen; + sf.bShowScoreLine = bShowScoreLine; + + sf.bShowGeneNum = bShowGeneNum; + sf.bShowGeneNumHit = bShowGeneNumHit; + sf.bShowAnnot = bShowAnnot; + sf.bShowAnnotHit = bShowAnnotHit; + sf.bShowGeneLine = bShowGeneLine; + sf.bHighGenePopup = bHighPopupGene; + + sf.bShowNoText = bShowNoText; + sf.bShowBlock1stText = bShowBlock1stText; + sf.bShowBlockText = bShowBlockText; + sf.bShowCsetText = bShowCsetText; + sf.bShowScoreText = bShowScoreText; + sf.bShowHitNumText = bShowHitNumText; + + if (sf.selectGeneObj!=null) seq.setSelectGene(null); + if (selectGeneObj!=null) seq.setSelectGene(selectGeneObj); + sf.selectGeneObj = selectGeneObj; + sf.bGeneNCheck = bGeneNCheck; + + sf.bHighG2x2 = bHighHit2g2; + sf.bHighG2x1 = bHighHit2g1; + sf.bHighG2x0 = bHighHit2g0; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/BpNumber.java",".java","2890","94","package symap.sequence; + +import java.text.NumberFormat; +import java.util.HashMap; + +/** + * This originally was written for FPC CB units and Seq BP units. + */ +public class BpNumber { + public static final int DEFAULT_FRACTION_DIGITS = 2; + + private static final String BP = ""BP""; + protected static final String KB = ""KB""; + private static final String MB = ""MB""; + private static final String GB = ""GB""; + + protected static final String[] ABS_UNITS = { BP, KB, MB, GB }; + + public static final String PIXEL = ""pixel""; + + protected static final HashMap unitConversion = new HashMap(); + static { + unitConversion.put(BP, 1); + unitConversion.put(KB, 1000); + unitConversion.put(MB, 1000000); + unitConversion.put(GB, 1000000000); + } + + private static final NumberFormat nf = NumberFormat.getNumberInstance(); + static { + nf.setMaximumFractionDigits(DEFAULT_FRACTION_DIGITS); + } + + protected static double getCbPerPixel(double bpPerPixel, double pixel) {return bpPerPixel * pixel;} + + protected static double getPixelValue(double cb, double bpPerPixel) {return cb / bpPerPixel;} + + protected static double getValue(String units, double bp, double bpPerPixel) { + double r; + if (units.equals(PIXEL)) r = bp / bpPerPixel; + else r = bp / (unitConversion.get(units)).doubleValue(); + return r; + } + + protected static String getFormatted(String units, double bp, double bpPerPixel, NumberFormat numFormat) { + return numFormat.format(getValue(units, bp,bpPerPixel))+"" ""+units; + } + + protected static String getFormatted(double bp, double bpPerPixel) { + return getFormatted(bp,bpPerPixel,nf); + } + + protected static String getFormatted(double bp0, double bpPerPixel, NumberFormat numFormat) { + String unit = GB; + double bp = getValue(BP, bp0,bpPerPixel); + int mult = unitConversion.get(unit); + if (bp < mult) { + unit = MB; + mult = unitConversion.get(unit); + if (bp < mult) { + unit = KB; + mult = unitConversion.get(unit); + if (bp < mult) unit = BP; + } + } + return getFormatted(unit, bp0,bpPerPixel,numFormat); + } + + protected static String getFormatted(double bpSep, double cb, double bpPerPixel) { + return getFormatted(bpSep, cb,bpPerPixel,nf); + } + + protected static String getFormatted(double bpSep, double cb, double bpPerPixel, NumberFormat numFormat) { + String unit = GB; + double bp = getValue(BP, cb,bpPerPixel); + int mult = unitConversion.get(unit); + if (bp < mult || bpSep < mult/100.0) { + unit = MB; + mult = unitConversion.get(unit); + if (bp < mult || bpSep < mult/100.0) { + unit = KB; + mult = unitConversion.get(unit); + if (bp < mult || bpSep < mult/100.0) { + unit = BP; + } + } + } + return getFormatted(unit, cb,bpPerPixel,numFormat); + } + + protected static double getBpPerPixel(int bp, double pixels) {return bp / pixels;} + protected static int getUnitConversion(String unit) {return unitConversion.get(unit);} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/sequence/Sfilter.java",".java","44386","1110","package symap.sequence; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseEvent; +import java.awt.event.ActionEvent; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButton; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; +import javax.swing.JTextField; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; + +import symap.Globals; +import symap.drawingpanel.DrawingPanel; +import util.Jcomp; +import util.Jhtml; +import util.Popup; +import util.Utilities; + +/** + * Sequence filter + */ +public class Sfilter extends JDialog { + private static final long serialVersionUID = 1L; + + private static final String DEFAULT_UNIT_KB = BpNumber.KB; + + // WHEN ALTER these, alter in initValues and TrackData! + static private final boolean bDefRuler=true, bDefGap=true, bDefCentromere=true; + static private final boolean bDefGene=true, bDefScoreLine=false, bDefHitLen=true; + static private final boolean bDefGeneNum=false, bDefAnnot=false, bDefGeneLine=false; + static private final boolean bDefHighG2xN=false, bDefGeneHigh=true; + static private final boolean bDefScoreText=false, bDefHitNumText=false, + bDefBlockText=false, bDefBlock1stText=false, + bDefCsetText=false, bDefNoText=true; + static private final boolean bDefFlipped=false; + + // Current values - many shared between Filter and Popup; accessed in Sequence and TrackData + // Copied in trackdata for history back/forth; this is serious rats nest... + protected boolean bShowRuler, bShowGap, bShowCentromere, bShowGene, bShowScoreLine, bShowHitLen; + protected boolean bShowGeneNum, bShowGeneNumHit, bShowAnnotHit, bShowAnnot, bShowGeneLine, bHighGenePopup; + protected boolean bShowScoreText, bShowHitNumText; + protected boolean bShowBlockText, bShowBlock1stText, bShowCsetText, bShowNoText; + protected boolean bFlipped; + protected boolean bGeneNCheck; + protected boolean bHighG2x2, bHighG2x1, bHighG2x0, bShowG2xN; // These highlight gene and hit + + // Save values for Cancel + private boolean bSavRuler, bSavGap, bSavCentromere, bSavGene, bSavScoreLine, bSavHitLen; + private boolean bSavGeneNum, bSavGeneNumHit, bSavAnnot, bSavAnnotHit, bSavGeneLine, bSavGeneHigh; + private boolean bSavScoreText, bSavHitNumText, bSavBlockText, bSavBlock1stText, bSavCsetText, bSavNoText, bSavFlipped; + private boolean bSavHighG2x2, bSavHighG2x1, bSavHighG2x0, bSavShowG2xN; + + protected boolean bSavGeneNCheck=false; + protected Annotation savSelectGeneObj=null; + protected String savGeneNStr=""""; + + private String savStartStr="""", savEndStr=""""; + private int savStartInd=0, savEndInd=0; + + // Filter panel + private JButton okButton, cancelButton, defaultButton, helpButton; + private JPanel buttonPanel; + private JPopupMenu popup=null; + private JMenuItem popupTitle; + + private JCheckBox flippedCheck; + private JButton fullButton; + private JLabel startLabel, endLabel; + private JTextField startText, endText; + private JComboBox startCombo, endCombo; + + private JCheckBox geneNCheck; + private JTextField geneNText; + protected Annotation selectGeneObj=null; // setting this sets the startText/startEnd and + + private JCheckBox rulerCheck, gapCheck, centromereCheck, geneCheck, scoreLineCheck, hitLenCheck; + private JCheckBox geneLineCheck, geneHighCheck; // delimiter, gene popup highlight gene + private JCheckBox geneNumCheck, annotCheck, geneNumHitCheck, annotHitCheck; + private JRadioButton scoreTextRadio, hitNumTextRadio, blockTextRadio,block1stTextRadio, csetTextRadio, noTextRadio; + + private JRadioButton highG2x2Radio, highG2x1Radio, highG2x0Radio; // set in Ref track, highlights genes/hits in L/Ref/R-tracks + private JCheckBox showG2xNCheck; // only show g2xN hits + + // Filter Popup + private JMenuItem fullSeqPopup; + private JCheckBoxMenuItem annotPopup, geneNumPopup, geneLinePopup, flippedPopup, annotHitPopup, geneNumHitPopup; + private JRadioButtonMenuItem scoreTextPopup, hitNumTextPopup, blockTextPopup, block1stTextPopup, csetTextPopup, noTextPopup; + + // Other + private Sequence seqObj; + private DrawingPanel drawingPanel; + private boolean bReplace=false; // Filter window text change in stateChanged; save in Save + private boolean bNoListen=false; + private int numGenes; + + // Created when 2d is displayed, one for each sequence and track + public Sfilter(Frame owner, DrawingPanel dp, Sequence sequence) { + super(owner,""Sequence Filter #"" + sequence.position, true); + this.drawingPanel = dp; + this.seqObj = sequence; + seqObj.setFilter(this); // access values from here + numGenes = seqObj.allAnnoVec.size(); + + initValues(); + + FilterListener listener = new FilterListener(); + + createFilterPanel(listener); + createPopup(listener); + setEnables(); + } +/** Startup **/ + // Filter dialog + private void createFilterPanel(FilterListener listener) { + String b1="" "", b2="" ""; + int textLen=7; + + // Checkbox options; takes effect immediately; but lost on cancel (must use save) + rulerCheck = Jcomp.createCheckBoxGray(""Ruler"", ""Show ruler along side of track""); + rulerCheck.addChangeListener(listener); + gapCheck = Jcomp.createCheckBoxGray(""Gaps"", ""Show gaps sympbol along sequence""); + gapCheck.addChangeListener(listener); + centromereCheck = Jcomp.createCheckBoxGray(""Centromere"", ""Show centromere symbol along sequence""); + centromereCheck.addChangeListener(listener); + geneCheck = Jcomp.createCheckBoxGray(""Genes"", ""Show gene graphics along sequence""); + geneCheck.addChangeListener(listener); + hitLenCheck = Jcomp.createCheckBoxGray(""Hit length"", ""Show hit length line along the inner boundary of the sequence""); + hitLenCheck.addChangeListener(listener); + scoreLineCheck = Jcomp.createCheckBoxGray(""Hit %Id bar"", ""Placement of Hit length is proportional to the %Identity""); + scoreLineCheck.addChangeListener(listener); + geneHighCheck = Jcomp.createCheckBoxGray(""Gene popup"", ""Highlight the gene when its Gene Popup is displayed""); + geneHighCheck.addChangeListener(listener); + annotCheck = Jcomp.createCheckBoxGray(""Annotation"", ""Show the annotation in a grey box on the side of the track (zoom in to show)""); + annotCheck.addChangeListener(listener); + geneNumCheck = Jcomp.createCheckBoxGray(""Gene#"", ""Show the Gene# beside the gene""); + geneNumCheck.addChangeListener(listener); + annotHitCheck = Jcomp.createCheckBoxGray(""Annotation"", ""Only show the annotation if the gene has a hit (zoom in to show)""); + annotHitCheck.addChangeListener(listener); + geneNumHitCheck = Jcomp.createCheckBoxGray(""Gene#"", ""Only show the Gene# if it has a hit""); + geneNumHitCheck.addChangeListener(listener); + geneLineCheck = Jcomp.createCheckBoxGray(""Delimiter"", ""Seperate gene graphics with a horizonal bar""); + geneLineCheck.addChangeListener(listener); + + block1stTextRadio = Jcomp.createRadioGray(""Block# 1st"", ""Show the Block# beside the 1st hit of block""); + block1stTextRadio.addChangeListener(listener); + blockTextRadio = Jcomp.createRadioGray(""Block# All"", ""Show the Block# beside the each hit""); + blockTextRadio.addChangeListener(listener); + csetTextRadio = Jcomp.createRadioGray(""Collinear#"", ""Show the Collinear# beside the hit""); + csetTextRadio.addChangeListener(listener); + scoreTextRadio = Jcomp.createRadioGray(""Hit %Id"", ""Show the %Identity beside the hit""); + scoreTextRadio.addChangeListener(listener); + hitNumTextRadio = Jcomp.createRadioGray(""Hit#"", ""Show the Hit# beside the hit""); + hitNumTextRadio.addChangeListener(listener); + noTextRadio = Jcomp.createRadioGray(""None"", ""Do not show any text beside the hit""); + noTextRadio.addChangeListener(listener); + ButtonGroup geneBG = new ButtonGroup(); + geneBG.add(block1stTextRadio);geneBG.add(blockTextRadio); + geneBG.add(scoreTextRadio); geneBG.add(hitNumTextRadio); + geneBG.add(csetTextRadio); geneBG.add(noTextRadio); + + // Ref only when 3-track + highG2x2Radio = Jcomp.createRadioGray(""g2x2"", ""Conserved gene: both L and R have g2 hit""); + highG2x2Radio.addChangeListener(listener); + highG2x1Radio = Jcomp.createRadioGray(""g2x1"", ""Not conserved: only L or R has g1 hit""); + highG2x1Radio.addChangeListener(listener); + highG2x0Radio = Jcomp.createRadioGray(""None"", ""Ignore""); + highG2x0Radio.addChangeListener(listener); + ButtonGroup hitBG = new ButtonGroup(); + hitBG.add(highG2x2Radio); hitBG.add(highG2x1Radio); hitBG.add(highG2x0Radio); + showG2xNCheck = Jcomp.createCheckBoxGray(""High only"", ""Only show the highlighted hit-wires""); + showG2xNCheck.addChangeListener(listener); + + // Coordinate options; takes effect on Apply; only specific listeners + flippedCheck = Jcomp.createCheckBoxGray(""Flip sequence "", ""Flip sequence so coordinates are Descending order""); + + fullButton = Jcomp.createMonoButtonSmGray(""Full"", ""Set start/end to full sequence""); + fullButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setFullSequence(); + } + }); + JPanel flipPanel = Jcomp.createRowPanelGray(); + flipPanel.add(flippedCheck); flipPanel.add(fullButton); + + startText = new JTextField(""0.0"",textLen); + startText.setMaximumSize(startText.getPreferredSize()); startText.setMinimumSize(startText.getPreferredSize()); + startCombo = new JComboBox (BpNumber.ABS_UNITS); + startCombo.setSelectedItem(DEFAULT_UNIT_KB); + startCombo.setMaximumSize(startCombo.getPreferredSize()); startCombo.setMinimumSize(startCombo.getPreferredSize()); + + String v = seqObj.getValue(seqObj.getEnd(), DEFAULT_UNIT_KB)+""""; + endText = new JTextField(v,textLen); + endText.setMaximumSize(endText.getPreferredSize()); endText.setMinimumSize(endText.getPreferredSize()); + endCombo = new JComboBox (BpNumber.ABS_UNITS); + endCombo.setSelectedItem(DEFAULT_UNIT_KB); + endCombo.setMaximumSize(endCombo.getPreferredSize()); endCombo.setMinimumSize(endCombo.getPreferredSize()); + + JPanel coordPanel = Jcomp.createRowPanelGray(); + startLabel = Jcomp.createLabelGray(b2+""Start"", ""Enter start coordinate for display""); startLabel.setEnabled(true); + coordPanel.add(startLabel); coordPanel.add(startText); coordPanel.add(startCombo); + endLabel = Jcomp.createLabelGray(b2+""End"", ""Enter end coordinate for display""); endLabel.setEnabled(true); + coordPanel.add(endLabel); coordPanel.add(endText); coordPanel.add(endCombo); + + JPanel genePanel = Jcomp.createRowPanelGray(); + genePanel.add(new JLabel(b2+ ""or "")); + geneNCheck = Jcomp.createCheckBoxGray(""Gene#"", ""Enter Gene# to search on""); + geneNCheck.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + geneNText.setEnabled(geneNCheck.isSelected()); + setCoordsEnable(); + } + }); + geneNText = new JTextField("""",7); + geneNText.setMaximumSize(geneNText.getPreferredSize()); geneNText.setMinimumSize(geneNText.getPreferredSize()); + JLabel reg = Jcomp.createMonoLabelGray("" (region "" + Globals.MAX_2D_DISPLAY_K + "")"", + ""Center on gene; gene take precedences over start/end""); + genePanel.add(geneNCheck); genePanel.add(geneNText); genePanel.add(reg); + + // Lower button panel + okButton = Jcomp.createButtonGray(""Save"",""Apply coordinate changes, save all changes, and close""); + okButton.addActionListener(listener); + + cancelButton = Jcomp.createButtonGray(""Cancel"", ""Discard changes and close""); + cancelButton.addActionListener(listener); + + defaultButton = Jcomp.createButtonGray(""Defaults"", ""Reset to defaults""); + defaultButton.addActionListener(listener); + + helpButton = Jhtml.createHelpIconUserSm(Jhtml.seqfilter); + + JButton helpButtonSm= Jcomp.createIconButton(null,null,null,""/images/info.png"", ""Quick Help Popup""); + helpButtonSm.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + popupHelp(); + } + }); + + buttonPanel = new JPanel(new BorderLayout()); + buttonPanel.add(new JSeparator(),BorderLayout.NORTH); + JPanel innerPanel = new JPanel(); + innerPanel.add(okButton); + innerPanel.add(cancelButton); + innerPanel.add(defaultButton); + innerPanel.add(helpButton); + innerPanel.add(helpButtonSm); + buttonPanel.add(innerPanel,BorderLayout.CENTER); + + /// Gridbag + Container contentPane = getContentPane(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + + contentPane.setLayout(gbl); + gbc.gridheight = 1; + gbc.ipadx = 5; + gbc.ipady = 8; + gbc.anchor = GridBagConstraints.WEST; + gbc.fill = GridBagConstraints.HORIZONTAL; + int rem = GridBagConstraints.REMAINDER; + + // section 1 + JLabel retain = Jcomp.createMonoLabelGray("" Save to retain changes"", ""Does not create new history event""); + addToGrid(contentPane, gbl, gbc, retain, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Highlight""), 1); + addToGrid(contentPane, gbl, gbc, geneHighCheck, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Show Gene""), 1); + addToGrid(contentPane, gbl, gbc, geneLineCheck, 1); + addToGrid(contentPane, gbl, gbc, geneNumCheck, 1); + addToGrid(contentPane, gbl, gbc, annotCheck, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+"" ""), 1); + addToGrid(contentPane, gbl, gbc, new JLabel("" Has hit""), 1); + addToGrid(contentPane, gbl, gbc, geneNumHitCheck, 1); + addToGrid(contentPane, gbl, gbc, annotHitCheck, rem); + + // section 2 + addToGrid(contentPane, gbl, gbc, new JSeparator(), rem); + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Show Text""), 1); + addToGrid(contentPane, gbl, gbc, block1stTextRadio, 1); + addToGrid(contentPane, gbl, gbc, blockTextRadio, 1); + addToGrid(contentPane, gbl, gbc, csetTextRadio, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel("" ""), 1); + addToGrid(contentPane, gbl, gbc, scoreTextRadio, 1); + addToGrid(contentPane, gbl, gbc, hitNumTextRadio, 1); + addToGrid(contentPane, gbl, gbc, noTextRadio, rem); + + // section 3 + addToGrid(contentPane, gbl, gbc, new JSeparator(), rem); + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Graphics""), 1); + addToGrid(contentPane, gbl, gbc, rulerCheck, 1); + addToGrid(contentPane, gbl, gbc, gapCheck, 1); + addToGrid(contentPane, gbl, gbc, centromereCheck, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel("" ""), 1); + addToGrid(contentPane, gbl, gbc, geneCheck, 1); + addToGrid(contentPane, gbl, gbc, hitLenCheck, 1); + addToGrid(contentPane, gbl, gbc, scoreLineCheck, rem); + + // section 4 + addToGrid(contentPane, gbl, gbc, new JSeparator(),rem); + JLabel apply = Jcomp.createMonoLabelGray("" Save to apply changes"", ""Create new history event""); + addToGrid(contentPane, gbl, gbc, apply, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Coordinates ""), 1); + addToGrid(contentPane, gbl, gbc, flipPanel, rem); + addToGrid(contentPane, gbl, gbc, coordPanel, rem); + addToGrid(contentPane, gbl, gbc, genePanel, rem); + + if (seqObj.isRef() && seqObj.is3Track() && numGenes>0) { + addToGrid(contentPane, gbl, gbc, new JSeparator(),rem); + + JLabel refOnly = Jcomp.createMonoLabelGray("" Reference only"", ""Does not create new history event""); + addToGrid(contentPane, gbl, gbc, refOnly, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Highlight""), 1); + addToGrid(contentPane, gbl, gbc, highG2x2Radio, 1); + addToGrid(contentPane, gbl, gbc, highG2x1Radio, 1); + addToGrid(contentPane, gbl, gbc, highG2x0Radio, rem); + + addToGrid(contentPane, gbl, gbc, new JLabel(b1+""Show""), 1); + addToGrid(contentPane, gbl, gbc, showG2xNCheck, rem); + } + + addToGrid(contentPane, gbl, gbc, buttonPanel, rem); + + pack(); + setResizable(false); + setLocationRelativeTo(null); + } + private void addToGrid(Container cp, GridBagLayout layout, GridBagConstraints con, Component comp, int w) { + con.gridwidth = w; + layout.setConstraints(comp, con); + cp.add(comp); + } + + // Popup + private void createPopup(FilterListener listener) { + popup = new JPopupMenu(); + popup.setBackground(Color.white); + popup.addPopupMenuListener(new MyPopupMenuListener()); + + flippedPopup = new JCheckBoxMenuItem("" Flip sequence""); + fullSeqPopup = new JCheckBoxMenuItem("" Full""); + + // if geneGraphicsCheck is turned off, these still show but do nothing - breaks when try to make it conditional + annotPopup = new JCheckBoxMenuItem("" Annotation all""); + annotHitPopup = new JCheckBoxMenuItem("" Annotation with hit""); + geneNumPopup = new JCheckBoxMenuItem("" Gene# all""); + geneNumHitPopup = new JCheckBoxMenuItem("" Gene# with hit""); + geneLinePopup = new JCheckBoxMenuItem("" Delimiter""); + + scoreTextPopup = new JRadioButtonMenuItem("" Hit %Id""); + hitNumTextPopup = new JRadioButtonMenuItem("" Hit# ""); + block1stTextPopup = new JRadioButtonMenuItem("" Block# 1st""); + blockTextPopup = new JRadioButtonMenuItem("" Block# All""); + csetTextPopup = new JRadioButtonMenuItem("" Collinear# ""); + noTextPopup = new JRadioButtonMenuItem("" None""); + ButtonGroup grp = new ButtonGroup(); + grp.add(scoreTextPopup); grp.add(hitNumTextPopup); grp.add(blockTextPopup); grp.add(block1stTextPopup); + grp.add(csetTextPopup); grp.add(noTextPopup); + noTextPopup.setSelected(true); + + popupTitle = new JMenuItem(""Sequence Options""); popupTitle.setEnabled(false); + popup.add(popupTitle); + + popup.addSeparator(); + JMenuItem stext = new JMenuItem(""Coordinate changes""); stext.setEnabled(false); // do not use JLabel; results in white space on right + popup.add(stext); + popup.add(flippedPopup); flippedPopup.addActionListener(listener); + popup.add(fullSeqPopup); fullSeqPopup.addActionListener(listener); + + popup.add(new JSeparator()); + JMenuItem gtext = new JMenuItem(""Show gene (toggle)""); gtext.setEnabled(false); + popup.add(gtext); + popup.add(geneNumHitPopup); geneNumHitPopup.addActionListener(listener); + popup.add(geneNumPopup); geneNumPopup.addActionListener(listener); + popup.add(geneLinePopup); geneLinePopup.addActionListener(listener); + JMenuItem atext = new JMenuItem("" Zoom in to view""); atext.setEnabled(false); + popup.add(atext); + popup.add(annotHitPopup); annotHitPopup.addActionListener(listener); + popup.add(annotPopup); annotPopup.addActionListener(listener); + + popup.add(new JSeparator()); + JMenuItem text = new JMenuItem(""Show text (one only)""); text.setEnabled(false); + popup.add(text); + popup.add(block1stTextPopup); block1stTextPopup.addActionListener(listener); + popup.add(blockTextPopup); blockTextPopup.addActionListener(listener); + popup.add(csetTextPopup); csetTextPopup.addActionListener(listener); + popup.add(hitNumTextPopup); hitNumTextPopup.addActionListener(listener); + popup.add(scoreTextPopup); scoreTextPopup.addActionListener(listener); + popup.add(noTextPopup); noTextPopup.addActionListener(listener); + + popup.setMaximumSize(popup.getPreferredSize()); + popup.setMinimumSize(popup.getPreferredSize()); + } + // disable if not exist + private void setEnables() { + bNoListen=true; + int[] annotTypeCounts = seqObj.getAnnotationTypeCounts(); + boolean b=true; + b = !(annotTypeCounts[Annotation.GAP_INT] == 0); + gapCheck.setEnabled(b); + + b = !(annotTypeCounts[Annotation.CENTROMERE_INT] == 0); + centromereCheck.setEnabled(b); + + b = !(annotTypeCounts[Annotation.GENE_INT] == 0 && annotTypeCounts[Annotation.EXON_INT] == 0); + geneCheck.setEnabled(b); + geneNumCheck.setEnabled(b); geneNumHitCheck.setEnabled(b); + geneLineCheck.setEnabled(b); + annotCheck.setEnabled(b); annotHitCheck.setEnabled(b); + highG2x2Radio.setEnabled(b); + highG2x1Radio.setEnabled(b); + geneHighCheck.setEnabled(b); + + geneNCheck.setEnabled(b); geneNText.setEnabled(b); + + annotPopup.setEnabled(b); annotHitPopup.setEnabled(b); + geneNumPopup.setEnabled(b); geneNumHitPopup.setEnabled(b); + geneLinePopup.setEnabled(b); + + bNoListen=false; + } +/** End Startup **/ + + // Used by drawingpanel.FilterHandle + public void showPopup(MouseEvent e) { + popup.show(e.getComponent(), e.getX(), e.getY()); + } + public boolean canShow() { + if (seqObj == null) return false; + return seqObj.hasLoad(); + } + public void closeFilter() { + if (isShowing()) { + actionCancel(); + setVisible(false); + } + } + /***********************************************************/ + /*** XXX Called when Sequence Filter button clicked ***/ + public void displaySeqFilter() { + if (isShowing()) { // this seems to always be false.. + super.setVisible(true); + return; + } + saveCurrentSettings(); + + // values can be changed in popup + flippedCheck.setSelected(bSavFlipped); + geneNumCheck.setSelected(bSavGeneNum && geneNumCheck.isEnabled()); + geneNumHitCheck.setSelected(bSavGeneNumHit && geneNumHitCheck.isEnabled()); + annotCheck.setSelected(bSavAnnot && annotCheck.isEnabled()); + annotHitCheck.setSelected(bSavAnnotHit && annotHitCheck.isEnabled()); + geneLineCheck.setSelected(bSavGeneLine && geneLineCheck.isEnabled()); + + block1stTextRadio.setSelected(bSavBlock1stText); + blockTextRadio.setSelected(bSavBlockText); + csetTextRadio.setSelected(bSavCsetText); + scoreTextRadio.setSelected(bSavScoreText); + hitNumTextRadio.setSelected(bSavHitNumText); + noTextRadio.setSelected(bSavNoText); + + // values only changed in filter window + rulerCheck.setSelected(bSavRuler); + gapCheck.setSelected(bSavGap && gapCheck.isEnabled()); + centromereCheck.setSelected(bSavCentromere && centromereCheck.isEnabled()); + geneCheck.setSelected(bSavGene && geneCheck.isEnabled()); + geneHighCheck.setSelected(bSavGeneHigh && geneHighCheck.isEnabled()); + hitLenCheck.setSelected(bSavHitLen); + scoreLineCheck.setSelected(bSavScoreLine); + + geneNCheck.setSelected(bSavGeneNCheck); + if (bSavGeneNCheck && selectGeneObj!=null) { + geneNText.setText(selectGeneObj.getFullGeneNum()); + seqObj.setSelectGene(selectGeneObj); + } + else geneNText.setText(""""); + setCoordsEnable(); + + highG2x2Radio.setSelected(bSavHighG2x2 && highG2x2Radio.isEnabled()); + highG2x1Radio.setSelected(bSavHighG2x1 && highG2x1Radio.isEnabled()); + highG2x0Radio.setSelected(bSavHighG2x0 && highG2x0Radio.isEnabled()); + showG2xNCheck.setSelected(bSavShowG2xN && showG2xNCheck.isEnabled()); + + super.setVisible(true); + } + + private void saveCurrentSettings() { // showSeqFilter (Button) and popup + bSavRuler = bShowRuler; + bSavGap = bShowGap && gapCheck.isEnabled(); + bSavCentromere = bShowCentromere && centromereCheck.isEnabled(); + bSavGene = bShowGene && geneCheck.isEnabled(); + bSavHitLen = bShowHitLen; + bSavScoreLine = bShowScoreLine; + + bSavGeneHigh = bHighGenePopup && geneHighCheck.isEnabled(); + bSavGeneNum = bShowGeneNum && geneNumCheck.isEnabled(); + bSavGeneNumHit = bShowGeneNumHit&& geneNumHitCheck.isEnabled(); + bSavAnnot = bShowAnnot && annotPopup.isEnabled(); + bSavAnnotHit = bShowAnnotHit && annotHitPopup.isEnabled(); + bSavGeneLine = bShowGeneLine && geneLinePopup.isEnabled(); + + bSavScoreText = bShowScoreText; + bSavHitNumText = bShowHitNumText; + bSavBlock1stText = bShowBlock1stText; + bSavBlockText = bShowBlockText; + bSavCsetText = bShowCsetText; + bSavNoText = bShowNoText; + + bSavFlipped = bFlipped; + + bSavGeneNCheck = bGeneNCheck; + savGeneNStr = geneNText.getText(); + savSelectGeneObj = selectGeneObj; + + bSavHighG2x2 = bHighG2x2; + bSavHighG2x1 = bHighG2x1; + bSavHighG2x0 = bHighG2x0; + bSavShowG2xN = bShowG2xN; + + // values may have changed from mouse drag, so these are current + int start = seqObj.getStart(); + Object item = startCombo.getSelectedItem(); + double val = seqObj.getValue(start, item.toString()); + startText.setText(val+""""); + + int end = seqObj.getEnd(); + item = endCombo.getSelectedItem(); + val = seqObj.getValue(end, item.toString()); + endText.setText(val + """"); + + savStartStr = startText.getText().trim(); + savEndStr = endText.getText().trim(); + savStartInd = startCombo.getSelectedIndex(); + savEndInd = endCombo.getSelectedIndex(); + } + /***************************************************************************/ + // The change in coords get processed here on Save + // Check boxes (except geneNCheck and flippedCheck) are processed immediately; + private boolean actionSave() { + if (!seqObj.hasLoad()) return true; + double tstart=0, tend=0; + boolean bChg=false; + + String gStr = geneNText.getText().trim(); // gene# takes precedence + if (gStr.equals("""") && geneNCheck.isSelected()) { + geneNCheck.setSelected(false); + bGeneNCheck = false; + } + + if (geneNCheck.isSelected()) { + if (!Utilities.isValidGenenum(gStr)) { + Popup.showWarning(gStr + "" is not a valid Gene#""); + return false; + } + if (!gStr.equals(savGeneNStr)) { + if (!gStr.contains(""."")) gStr += "".""; + + int mid = seqObj.getSelectGeneCoord(gStr); // highlight if found + if (mid<0) { + Popup.showWarning(gStr + "" is not found on this chromosome.""); + return false; + } + bGeneNCheck = true; + + tstart = Math.max(0,mid-Globals.MAX_2D_DISPLAY); + tend = Math.min(seqObj.getTrackSize(), mid+Globals.MAX_2D_DISPLAY); + + startText.setText((tstart/1000)+"""");startCombo.setSelectedItem(BpNumber.KB); + endText.setText((tend/1000)+""""); endCombo.setSelectedItem(BpNumber.KB); + + seqObj.setStart((int)tstart); + seqObj.setEnd((int)tend); + + bChg = true; + } + } + else { + bChg = applyCoordChanges(); // uses entered values + } + + if (bChg) { // will do replace and flip changes too + drawingPanel.setUpdateHistory(); + drawingPanel.smake(""Sf: saveaction update bchg""); + } + else if (xFlipSeq(flippedCheck.isSelected())) { + drawingPanel.setUpdateHistory(); + drawingPanel.smake(""Sf: saveaction update flip""); + } + else if (bReplace) { + drawingPanel.setReplaceHistory(); + drawingPanel.smake(""Sf: saveaction replace""); + } + return true; + } + + protected void actionCancel() { + if (bSavHighG2x2 || bSavHighG2x1) xDefG2xN(); + + gapCheck.setSelected(bSavGap); + centromereCheck.setSelected(bSavCentromere); + rulerCheck.setSelected(bSavRuler); + geneCheck.setSelected(bSavGene); + hitLenCheck.setSelected(bSavHitLen); + scoreLineCheck.setSelected(bSavScoreLine); + + annotCheck.setSelected(bSavAnnot); annotHitCheck.setSelected(bSavAnnotHit); + geneNumCheck.setSelected(bSavGeneNum); geneNumHitCheck.setSelected(bSavGeneNumHit); + geneLineCheck.setSelected(bSavGeneLine); + geneHighCheck.setSelected(bSavGeneHigh); + highG2x2Radio.setSelected(bSavHighG2x2); + highG2x1Radio.setSelected(bSavHighG2x1); + highG2x0Radio.setSelected(bSavHighG2x0); + showG2xNCheck.setSelected(bSavShowG2xN); + + block1stTextRadio.setSelected(bSavBlock1stText); + blockTextRadio.setSelected(bSavBlockText); + csetTextRadio.setSelected(bSavCsetText); + scoreTextRadio.setSelected(bSavScoreText); + hitNumTextRadio.setSelected(bSavHitNumText); + noTextRadio.setSelected(bSavNoText); + + flippedCheck.setSelected(bSavFlipped); + + seqObj.setSelectGene(savSelectGeneObj); + geneNCheck.setSelected(bSavGeneNCheck); + geneNText.setText(savGeneNStr); + + startText.setText(savStartStr); startCombo.setSelectedIndex(savStartInd); + endText.setText(savEndStr); endCombo.setSelectedIndex(savEndInd); + } + private void actionDefault() { // Default button; + xDefG2xN(); + + rulerCheck.setSelected(bDefRuler); + gapCheck.setSelected(bDefGap && gapCheck.isEnabled()); + centromereCheck.setSelected(bDefCentromere && centromereCheck.isEnabled()); + geneCheck.setSelected(bDefGene && geneCheck.isEnabled()); + hitLenCheck.setSelected(bDefHitLen); + scoreLineCheck.setSelected(bDefScoreLine); + + annotCheck.setSelected(bDefAnnot); annotHitCheck.setSelected(bDefAnnot); + geneNumCheck.setSelected(bDefGeneNum); geneNumHitCheck.setSelected(bDefGeneNum); + geneLineCheck.setSelected(bDefGeneLine); + geneHighCheck.setSelected(bDefGeneHigh); + highG2x2Radio.setSelected(bDefHighG2xN); + highG2x1Radio.setSelected(bDefHighG2xN); + highG2x0Radio.setSelected(!bDefHighG2xN); + + scoreTextRadio.setSelected(bDefScoreText); + hitNumTextRadio.setSelected(bDefHitNumText); + block1stTextRadio.setSelected(bDefBlock1stText); + blockTextRadio.setSelected(bDefBlockText); + csetTextRadio.setSelected(bDefCsetText); + noTextRadio.setSelected(bDefNoText); + + flippedCheck.setSelected(bDefFlipped); + + geneNText.setText(""""); geneNCheck.setSelected(false); + seqObj.setSelectGene(null); + selectGeneObj = null; + + startCombo.setSelectedItem(DEFAULT_UNIT_KB); + startText.setText(""0.0""); + + endCombo.setSelectedItem(DEFAULT_UNIT_KB); + int size = seqObj.getTrackSize(); + double end = seqObj.getValue(size, DEFAULT_UNIT_KB); + endText.setText(end + """"); + endCombo.setSelectedItem(DEFAULT_UNIT_KB); + } + + private void setCoordsEnable() { + boolean b = !geneNCheck.isSelected(); + startLabel.setEnabled(b); startText.setEnabled(b); + endLabel.setEnabled(b); endText.setEnabled(b); + fullButton.setEnabled(b); flippedCheck.setEnabled(b); + } + + private void setFullSequence() { + geneNCheck.setSelected(false); + + startText.setText(""0.0""); + startCombo.setSelectedItem(DEFAULT_UNIT_KB); + + int size = seqObj.getTrackSize(); + double end = seqObj.getValue(size, DEFAULT_UNIT_KB); + endText.setText(end + """"); + endCombo.setSelectedItem(DEFAULT_UNIT_KB); + } + private boolean applyCoordChanges() { // Full Coordinates and actionSave + double tstart=0, tend=0; + int eInd = endCombo.getSelectedIndex(); + String eStr = endText.getText(); + int sInd = startCombo.getSelectedIndex(); + String sStr = startText.getText(); + + boolean numChgE = (eInd!=savEndInd || !eStr.contentEquals(savEndStr)); + boolean numChgS = (sInd!=savStartInd || !sStr.contentEquals(savStartStr)); + + if (!numChgS && !numChgE) return false; + + try { + tstart = Double.parseDouble(sStr); + } catch (NumberFormatException nfe) { + Popup.showErrorMessage(sStr + "" is not a valid start point""); + return false; + } + tstart = tstart * BpNumber.getUnitConversion(BpNumber.ABS_UNITS[sInd]); + + try { + tend = Double.parseDouble(eStr); + } catch (NumberFormatException nfe) { + Popup.showErrorMessage(eStr + "" is not a valid end point""); + return false; + } + tend = tend * BpNumber.getUnitConversion(BpNumber.ABS_UNITS[eInd]); + + if (tstart>=tend) { + Popup.showErrorMessage(""The start ("" + tstart + "") must be less than end ("" + tend + "")""); + return false; + } + seqObj.setStart((int)tstart); + seqObj.setEnd((int)tend); + + return true; + } + + /************************************************************************************/ + private class FilterListener implements ActionListener, ChangeListener, ItemListener { + private FilterListener() { } + + // Called for panel ok/cancel/default buttons and popup menu events + public void actionPerformed(ActionEvent event) { + Object src = event.getSource(); + boolean bUp = false, bRep = false; + + if (src == okButton) { // changed already made except of for sequence + actionSave(); + setVisible(false); + } + else if (src == cancelButton) { + actionCancel(); + setVisible(false); + } + else if (src == defaultButton) { + actionDefault(); + } + // The rest are for the popup and happen immediately + else if (src == fullSeqPopup) { + setFullSequence(); + bUp = applyCoordChanges(); + } + else if (src == flippedPopup) bUp = xFlipSeq(!bSavFlipped); + else if (src == annotPopup) bRep = xShowAnnot(annotPopup.getState()); + else if (src == annotHitPopup) bRep = xShowAnnotHit(annotHitPopup.getState()); + else if (src == geneNumPopup) bRep = xShowGeneNum(geneNumPopup.getState()); + else if (src == geneNumHitPopup) bRep = xShowGeneNumHit(geneNumHitPopup.getState()); + else if (src == geneLinePopup) bRep = xShowGeneLine(geneLinePopup.getState()); + + else if (src == scoreTextPopup) bRep = xShowScoreText(scoreTextPopup.isSelected()); + else if (src == hitNumTextPopup) bRep = xShowHitNumText(hitNumTextPopup.isSelected()); + else if (src == block1stTextPopup) bRep = xShowBlock1stText(block1stTextPopup.isSelected()); + else if (src == blockTextPopup) bRep = xShowBlockText(blockTextPopup.isSelected()); + else if (src == csetTextPopup) bRep = xShowCsetText(csetTextPopup.isSelected()); + else if (src == noTextPopup) bRep = xShowNoText(noTextPopup.isSelected()); + + if (bUp || bRep) { + drawingPanel.smake(""Sf: filterlistener actionperformed""); + if (bUp) drawingPanel.updateHistory(); + else drawingPanel.replaceHistory(); + } + } + // From Filter Panel, all events that use immediate change (not flipped or geneNCheck) + public void stateChanged(ChangeEvent event) { + if (bNoListen) return; + + Object src = event.getSource(); + boolean bDiff = false; + + if (src == geneCheck || numGenes==0) {// no anno shown/exist + bDiff = xShowGene(geneCheck.isSelected()); + boolean b = geneCheck.isSelected(); + annotCheck.setEnabled(b); annotHitCheck.setEnabled(b); + geneNumCheck.setEnabled(b); geneNumHitCheck.setEnabled(b); + geneLineCheck.setEnabled(b); + geneHighCheck.setEnabled(b); + highG2x2Radio.setEnabled(b); + highG2x1Radio.setEnabled(b); + highG2x0Radio.setEnabled(b); + showG2xNCheck.setEnabled(highG2x1Radio.isSelected() || highG2x2Radio.isSelected()); + } + else if (src == annotCheck) { + bDiff = xShowAnnot(annotCheck.isSelected()); + if (annotCheck.isSelected()) annotHitCheck.setSelected(false); + } + else if (src == annotHitCheck) { + bDiff = xShowAnnotHit(annotHitCheck.isSelected()); + if (annotHitCheck.isSelected()) annotCheck.setSelected(false); + } + else if (src == geneNumCheck) { + bDiff = xShowGeneNum(geneNumCheck.isSelected()); + if (geneNumCheck.isSelected()) geneNumHitCheck.setSelected(false); + } + else if (src == geneNumHitCheck) { + bDiff = xShowGeneNumHit(geneNumHitCheck.isSelected()); + if (geneNumHitCheck.isSelected()) geneNumCheck.setSelected(false); + } + else if (src == geneLineCheck) bDiff = xShowGeneLine(geneLineCheck.isSelected()); + else if (src == geneHighCheck) bDiff = xHighGenePopup(geneHighCheck.isSelected()); + + else if (src == block1stTextRadio) bDiff = xShowBlock1stText(block1stTextRadio.isSelected()); + else if (src == blockTextRadio) bDiff = xShowBlockText(blockTextRadio.isSelected()); + else if (src == csetTextRadio) bDiff = xShowCsetText(csetTextRadio.isSelected()); + else if (src == hitNumTextRadio)bDiff = xShowHitNumText(hitNumTextRadio.isSelected()); + else if (src == scoreTextRadio) bDiff = xShowScoreText(scoreTextRadio.isSelected()); + else if (src == hitNumTextRadio)bDiff = xShowHitNumText(hitNumTextRadio.isSelected()); + else if (src == noTextRadio) bDiff = xShowNoText(noTextRadio.isSelected()); + + else if (src == rulerCheck) bDiff = xShowRuler(rulerCheck.isSelected()); + else if (src == gapCheck) bDiff = xShowGap(gapCheck.isSelected()); + else if (src == centromereCheck)bDiff = xShowCentromere(centromereCheck.isSelected()); + else if (src == hitLenCheck) bDiff = xShowHitLen(hitLenCheck.isSelected()); + else if (src == scoreLineCheck) bDiff = xShowScoreLine(scoreLineCheck.isSelected()); + + else if (src == highG2x2Radio) bDiff = xHighG2xN(2, highG2x2Radio.isSelected()); + else if (src == highG2x1Radio) bDiff = xHighG2xN(1, highG2x1Radio.isSelected()); + else if (src == highG2x0Radio) bDiff = xHighG2xN(0, highG2x0Radio.isSelected()); + else if (src == showG2xNCheck) bDiff = xShowG2xN(showG2xNCheck.isSelected()); + + if (bDiff) { + drawingPanel.smake(""Sf: filterlistener state changed "" + src.hashCode());// sets drawingPanel.setUpdateHistory() on Save + bReplace = true; + } + } + + public void itemStateChanged(ItemEvent evt) {} + } // end listener + + // called when popup become visible + class MyPopupMenuListener implements PopupMenuListener { + public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {} + + public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {} + + public void popupMenuWillBecomeVisible(PopupMenuEvent event) { + saveCurrentSettings(); + + annotPopup.setSelected(bSavAnnot); + annotHitPopup.setSelected(bSavAnnotHit); + geneNumPopup.setSelected(bSavGeneNum); + geneNumHitPopup.setSelected(bSavGeneNumHit); + geneLinePopup.setSelected(bSavGeneLine); + + scoreTextPopup.setSelected(bSavScoreText); + hitNumTextPopup.setSelected(bSavHitNumText); + block1stTextPopup.setSelected(bSavBlock1stText); + blockTextPopup.setSelected(bSavBlockText); + csetTextPopup.setSelected(bSavCsetText); + noTextPopup.setSelected(bSavNoText); + + flippedPopup.setSelected(bSavFlipped); + } + } // end popup listener + + ////////////////////////////////////////////////////////////////////// + private void initValues() { + bFlipped = bDefFlipped; + bShowRuler = bDefRuler; + bShowGap = bDefGap; + bShowCentromere = bDefCentromere; + bShowGene = bDefGene; + bShowHitLen = bDefHitLen; + bShowScoreLine = bDefScoreLine; + + bShowGeneNum = bShowGeneNumHit = bDefGeneNum; + bShowAnnot = bShowAnnotHit = bDefAnnot; + bShowGeneLine = bDefGeneLine; + bHighGenePopup = bDefGeneHigh; + + bShowScoreText = bDefScoreText; + bShowHitNumText = bDefHitNumText; + bShowBlock1stText = bDefBlock1stText; + bShowBlockText = bDefBlockText; + bShowCsetText = bDefCsetText; + bShowNoText = bDefNoText; + + bHighG2x2 = bDefHighG2xN; + bHighG2x1 = bDefHighG2xN; + bHighG2x0 = !bDefHighG2xN; + bShowG2xN = bDefHighG2xN; + + bGeneNCheck = false; + selectGeneObj = null; + + // Start and end get initialized from seqObj when filter window popups up + } + + protected boolean xFlipSeq(boolean flip) { // track & filter + if (bFlipped != flip) {bFlipped = flip; seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xShowRuler(boolean show) { + if (bShowRuler != show) {bShowRuler = show; seqObj.setTrackBuild();return true;} + return false; + } + private boolean xShowGap(boolean show) { + if (bShowGap != show) {bShowGap = show; seqObj.setTrackBuild();return true;} + return false; + } + private boolean xShowCentromere(boolean show) { + if (bShowCentromere != show) {bShowCentromere = show; seqObj.setTrackBuild();return true;} + return false; + } + private boolean xShowGene(boolean show) { + if (bShowGene != show) {bShowGene = show; seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xShowHitLen(boolean show) { + if (bShowHitLen != show) {bShowHitLen = show; seqObj.setTrackBuild(); return true; } + return false; + } + private boolean xShowScoreLine(boolean show) { + if (bShowScoreLine != show) {bShowScoreLine = show; seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xShowAnnot(boolean show) { + if (seqObj.allAnnoVec.size() == 0) {bShowAnnot = false; return false;} + + if (bShowAnnot != show) { + bShowAnnot = show; + if (show) bShowAnnotHit = false; + seqObj.setTrackBuild(); + return true; + } + return false; + } + private boolean xShowAnnotHit(boolean show) { + if (seqObj.allAnnoVec.size() == 0) {bShowAnnotHit = false; return false;} + + if (bShowAnnotHit != show) { + bShowAnnotHit = show; + if (show) bShowAnnot = false; + seqObj.setTrackBuild(); + return true; + } + return false; + } + private boolean xShowGeneNum(boolean show) { + if (bShowGeneNum != show) { + bShowGeneNum = show; + if (show) bShowGeneNumHit = false; + seqObj.setTrackBuild(); + return true; + } + return false; + } + private boolean xShowGeneNumHit(boolean show) { + if (bShowGeneNumHit != show) { + bShowGeneNumHit = show; + if (show) bShowGeneNum = false; + seqObj.setTrackBuild(); + return true; + } + return false; + } + private boolean xShowGeneLine(boolean show) { + if (bShowGeneLine != show) {bShowGeneLine = show; seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xHighGenePopup(boolean high) { + if (bHighGenePopup != high) { + bHighGenePopup = high; seqObj.setTrackBuild(); + if (!high) + for (Annotation aObj : seqObj.allAnnoVec) aObj.setIsPopup(false); // exons are highlighted to, so use all + return true; + } + return false; + } + private boolean xShowScoreText(boolean show) { + if (bShowScoreText != show) {xSetText(false, false, false, false, show); seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xShowHitNumText(boolean show) { + if (bShowHitNumText != show) {xSetText(false, false, false, show, false); seqObj.setTrackBuild(); return true; } + return false; + } + private boolean xShowBlock1stText(boolean show) { + if (bShowBlock1stText != show) {xSetText(show, false, false, false, false); seqObj.setTrackBuild(); return true; } + return false; + } + private boolean xShowBlockText(boolean show) { + if (bShowBlockText != show) {xSetText(false, show, false, false, false); seqObj.setTrackBuild(); return true; } + return false; + } + private boolean xShowCsetText(boolean show) { + if (bShowCsetText != show) {xSetText(false, false, show, false, false); seqObj.setTrackBuild(); return true;} + return false; + } + private boolean xShowNoText(boolean show) { + if (bShowNoText != show) {xSetText(false, false, false, false, false); seqObj.setTrackBuild(); return true; } + return false; + } + private void xSetText(boolean b1, boolean b, boolean c, boolean h, boolean s) { + bShowBlock1stText = b1; + bShowBlockText = b; + bShowCsetText = c; + bShowHitNumText = h; + bShowScoreText = s; + + if (!b1 && !b && !c && !s && !h) bShowNoText=true; + else bShowNoText=false; + } + /* g2xN methods reference only */ + private boolean xHighG2xN(int which, boolean high) { + if (which==2) { + if (bHighG2x2==high) return false; + bHighG2x2 = high; + } + else if (which==1) { + if (bHighG2x1==high) return false; + bHighG2x1 = high; + } + else if (which==0) { + if (bHighG2x0==high) return false; + bHighG2x0 = high; + } + showG2xNCheck.setEnabled(bHighG2x2 || bHighG2x1); + + seqObj.refSetG2xN(which, high); // sets the genes.hit highlighted in L-Ref-R tracks (very messy) + + return true; + } + private boolean xShowG2xN(boolean high) { + if (bShowG2xN==high) return false; + + bShowG2xN=high; + highG2x0Radio.setEnabled(!high); // have to uncheck Show before select another + highG2x1Radio.setEnabled(!high); + highG2x2Radio.setEnabled(!high); + + seqObj.showG2xN(high); // turns special flag on/off + + return true; + } + private void xDefG2xN() { + if (bHighG2x2) xHighG2xN(2, false); + else if (bHighG2x1) xHighG2xN(1, false); + + xShowG2xN(false); + + showG2xNCheck.setSelected(false); showG2xNCheck.setEnabled(false); + highG2x0Radio.setSelected(true); + } + + /////////////////////////////////////////////////////////////// + private void popupHelp() { + String msg = ""The check boxes and radio buttons for the top 3 sections"" + + ""\n take immediate effect, but are only saved on Save"" + + ""\n and do not create a history event."" + + + ""\n\nCoordinate changes only take effect on Save,"" + + ""\n and do create a history event."" + + ""\nChecking Gene# changed the coordinates and highlights the gene."" + + + ""\n\nHistory Event: uses the < and > icons on the control bar."" + + + ""\n\nClick in white space of a track for a subset of the filters."" + ; + if (seqObj.isRef() && seqObj.is3Track()) { + msg +=""\n\nReference 3-track only:"" + + ""\n g2x2: Both left and right are g2 to a reference gene (conserved) "" + + ""\n g2x1: Only left or right is g2 to a reference gene (unique)"" + + ""\n where g2 is a gene on both ends of the hit"" + + ""\n High only: only show the highlighted hit-wires"" + + ""\nNOTE: all chromosomes MUST be annotated, or there are no results."" + + ""\n Highlights, etc are often lost when view is changed."" + ; + } + Popup.displayInfoMonoSpace(this, ""Sequence Filter Quick Help"", msg, false); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/SeqHits.java",".java","30902","848","package symap.mapper; + +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.geom.Point2D; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; +import java.awt.event.MouseEvent; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Font; +import java.util.TreeMap; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Vector; +import java.util.ArrayList; + +import symap.closeup.TextShowInfo; +import symap.closeup.AlignPool; +import symap.sequence.Annotation; +import symap.sequence.Sequence; +import symap.Globals; + +/*********************************************** + * All hits for a chr-chr pair; internal class DrawHit has both ends, which links to HitData + * Mapper: Tracks 0-N are in order of display; Ref is always seqObj1 + * Hit Wire is the line between chromosomes + * Hit Rect is the hit rectangle in the track, one on each end of wire + * DrawHit: draws hit part the occurs on sequence: hit length and text (e.g. block#) + */ +public class SeqHits { + private static final int MOUSE_PADDING = 3; + private static final int HIT_OFFSET = 15, HIT_MIN_OFFSET=6; // amount line enters track; 15, 12,9,6 + private static final int HIT_INC = 3, HIT_OVERLAP = 75; // default minimum match bases is 100, so hits should be more + private static final int TEXTCLOSE = 7; + + public static Font textFont = Globals.textFont; + private static Font textFontBig = new Font(Font.MONOSPACED,Font.BOLD,16); + + private int projIdx1, projIdx2; // project IDs + private int grpIdx1, grpIdx2; // groupIDs: chromosome + + private Mapper mapper; + private DrawHit[] allHitsArray; + + // query has dbName < target; seqObj1 is query (corresponds to pseudo_hits.annot1_idx); + private Sequence seqObj1, seqObj2; // query, target; query may be the left or right track + private boolean st1LTst2=true; // if seqObj1.track# blockMap = new HashMap (); + + // called in MapperPool + public SeqHits(Mapper mapper, Sequence st1, Sequence st2, Vector hitList) { + this.mapper = mapper; + this.seqObj1 = st1; + this.seqObj2 = st2; + boolean bHit1 = st1.position==1 || st2.position==1; + + int off1 = HIT_OFFSET, off2 = HIT_OFFSET; + HitData lasthd = null; + TreeMap s2Map = new TreeMap (); // order by start2 + + allHitsArray = new DrawHit[hitList.size()]; // transfer hitList to allHitsArray; ordered by start1 + for (int i = 0; i < allHitsArray.length; i++) { + HitData hd = hitList.get(i); + allHitsArray[i] = new DrawHit(hd); + + boolean isSelected = mapper.isQuerySelHit(hd.getHitNum(), bHit1); // for group or hit highlight; + allHitsArray[i].set(isSelected); + + // Calc offset for display for seq1 + int olap = (lasthd!=null) ? Math.min(lasthd.end1,hd.end1) - Math.max(lasthd.start1,hd.start1) : 0; + if (olap > HIT_OVERLAP) { + off1 -= HIT_INC; + if (off1 < HIT_MIN_OFFSET) off1 = HIT_OFFSET; + } + else off1 = HIT_OFFSET; + allHitsArray[i].off1 = off1; + + if (lasthd==null) lasthd = hd; + else if (hd.end1>lasthd.end1) lasthd = hd; // otherwise, contained + + if (s2Map.containsKey(hd.start2)) s2Map.put(hd.start2+1, i); + else s2Map.put(hd.start2, i); + + // Set up blocks - 1st/last gets set per display + int b = hd.getBlock(); + if (b>0) { + if (!blockMap.containsKey(b)) { + Block blk = new Block(); + blockMap.put(b, blk); + blk.isInv = hd.isBlkInv(); + } + } + } + // Calc offset for display for seq2 + lasthd = null; + for (int i : s2Map.values()) { + HitData hd = hitList.get(i); + int olap = (lasthd!=null) ? Math.min(lasthd.end2,hd.end2) - Math.max(lasthd.start2,hd.start2) : 0; + if (olap > HIT_OVERLAP) { + off2 -= HIT_INC; + if (off2 < HIT_MIN_OFFSET) off2 = HIT_OFFSET; + } + else off2 = HIT_OFFSET; + allHitsArray[i].off2 = off2; + + if (lasthd==null) lasthd = hd; + else if (hd.end2>lasthd.end2) lasthd = hd; + } + + projIdx1 = st1.getProjIdx(); + projIdx2 = st2.getProjIdx(); + grpIdx1 = st1.getGroup(); + grpIdx2 = st2.getGroup(); + + seqObj1.setSeqHits(this, mapper.isQueryTrack(seqObj1.getHolder().getTrack())); // seqObj has hits + seqObj2.setSeqHits(this, mapper.isQueryTrack(seqObj2.getHolder().getTrack())); + + // 1st track is listed first on hover and popups + int t1 = seqObj1.getHolder().getTrackNum(); + int t2 = seqObj2.getHolder().getTrackNum(); + st1LTst2 = (t1 hitList, int start, int end, boolean swap) { + for (int i = 0; i < allHitsArray.length; i++) + allHitsArray[i].getHit(hitList,start,end,swap); // adds to hitList + } + + /* g2xN methods */ + public Vector getVisG2Hits() { // SeqPool.computeG2xN + Vector hitList = new Vector (); + for (DrawHit hObj : allHitsArray) { + if (hObj.isOlapHit()) { // hit overlaps visible chromosome + if (hObj.hitDataObj.is2Gene() && !hObj.isFiltered()) + hitList.add(hObj.hitDataObj); + } + } + return hitList; + } + public Vector getInVisG2Hits() { // SeqPool.computeG2xN + Vector hitList = new Vector (); + for (DrawHit hObj : allHitsArray) { + if (hObj.isOlapHit()) { + if (hObj.hitDataObj.is2Gene() && hObj.isFiltered()) + hitList.add(hObj.hitDataObj); + } + } + return hitList; + } + public Vector getVisG1Hits(int which) { // SeqPool.computeG2xN + Vector hitList = new Vector (); + for (DrawHit dht : allHitsArray) { + if (dht.isOlapHit() && dht.hitDataObj.is1Gene() && !dht.isFiltered()) { + if (which==1 && dht.hitDataObj.annot1_idx==0) hitList.add(dht.hitDataObj); + else if (which==2 && dht.hitDataObj.annot2_idx==0) hitList.add(dht.hitDataObj); + } + } + return hitList; + } + public void setnG2xN(int n) { // Sequence.refHighG2xN + nG2xN=n; + seqObj1.setnG2xN(n); seqObj2.setnG2xN(n); + } + public void setOnlyG2xN(boolean b) {isOnlyG2xN=b;} // Sequence.showG2xN + + public void clearHighG2xN() { // Sequence.refHighG2xN + for (DrawHit hd: allHitsArray) + hd.hitDataObj.clearG2xN(); + + seqObj1.setnG2xN(0); seqObj2.setnG2xN(0); // need to get set in L/R also + + cntHighG2xN=cntFiltG2xN=cntPossG2xN=0; + nG2xN=0; + } + /***************************************************** + * XXX Paint all hits + */ + public void paintComponent(Graphics2D g2) { + lastText1=lastText2=0; + + mapper.setHelpText(null); // will be set if hover; CAS577 + + Point stLoc1 = seqObj1.getLocation(); + Point stLoc2 = seqObj2.getLocation(); + int trackPos1 = mapper.getTrackPosition(seqObj1); // left or right + int trackPos2 = mapper.getTrackPosition(seqObj2); + ArrayList selHits = new ArrayList(); + + TreeMap highMap = new TreeMap (); // if collinear or blocks is highlighted + int hcolor=1; + + HfilterData hf = mapper.getHitFilter(); + boolean bHiCset = hf.isHiCset(); + boolean bHiBlock = hf.isHiBlock(); + boolean bHiLight = (bHiCset || bHiBlock); + boolean bHi = bHiLight || hf.isHi0Gene() || hf.isHi1Gene() || hf.isHi2Gene(); + + // Create blk/coset color map; allHitArray sorted by start1; !correspond to sequential blocks (sorted sets). + if (bHiLight) { + for (DrawHit h : allHitsArray) { + if (!h.isOlapHit()) continue; + + int set = (bHiCset) ? h.getCollinearSet() : h.getBlock(); + if (set!=0 && !highMap.containsKey(set)) { + highMap.put(set, hcolor); + hcolor++; + if (hcolor==5) hcolor=1; // redone for cosets below; 4 colors for blocks + } + } + hcolor=1; + if (bHiCset) { //sorted by start1 does not correspond to sequence sets + for (int set : highMap.keySet()) { + highMap.put(set, hcolor); + hcolor++; + if (hcolor==3) hcolor=1; + } + } + } + // Set block 1st/last for this display + if (seqObj1.getShowBlock1stText() || seqObj2.getShowBlock1stText()) { + for (Block blk : blockMap.values()) blk.hitnum1 = blk.hitnumN = 0; + + for (DrawHit h : allHitsArray) { + if (h.isOlapHit() && !h.isFiltered()) { + int n = h.getBlock(); + if (n>0) { + Block b = blockMap.get(h.getBlock()); + int num = h.hitDataObj.getHitNum(); + if (b.hitnum1==0) b.hitnum1 = num; + b.hitnumN = num; + } + } + } + } + cntShowHit=cntHighHit=cntHighG2xN=cntPossG2xN=cntFiltG2xN=0; // counted in paint + HashSet numSet = new HashSet (); // count blocks/sets shown + hcolor=1; + + // Draw all lines but hover or selected from Query Table + for (DrawHit dh : allHitsArray) { + if (!dh.isOlapHit() || dh.isFiltered()) continue; + + if (bHiLight) { + int set = (bHiCset) ? dh.getCollinearSet() : dh.getBlock(); + if (set!=0) hcolor = highMap.get(set); + } + if (dh.isHover || dh.isQuerySelHit) selHits.add(dh); + else { + dh.paintComponent(g2, trackPos1, trackPos2, stLoc1, stLoc2, hcolor, false); + if (bHiLight) { + int set = (bHiCset) ? dh.getCollinearSet() : dh.getBlock(); + if (set!=0 && !numSet.contains(set)) numSet.add(set); + } + } + } + int cntGrpHits=0; + + // Draw hover hits on top with highlight + for (DrawHit dh : selHits) { + if (!dh.isOlapHit() || dh.isFiltered()) continue; + + dh.paintComponent(g2,trackPos1,trackPos2,stLoc1,stLoc2, 1, false); + if (bHiLight) { + int set = (bHiCset) ? dh.getCollinearSet() : dh.getBlock(); + if (set!=0 && !numSet.contains(set)) numSet.add(set); + } + if (dh.isQuerySelHit) cntGrpHits++; + } + + // Draw text on top of hits + if (seqObj1.getHasText() || seqObj2.getHasText()) { + for (DrawHit dh : allHitsArray) { + dh.paintComponent(g2,trackPos1,trackPos2,stLoc1,stLoc2, 1, true); + } + } + + // Information box on Stats; \n and extra blanks removed for Query 2D in HelpBar.setHelp + infoMsg = String.format(""Hits: %,d"", cntShowHit); + + if (bHi) infoMsg += String.format(""\nHigh: %,d"", cntHighHit);// after hits since it high hits + if (cntGrpHits>0) infoMsg += String.format(""\nGroup Hits: %,d"", cntGrpHits);// only from Queries Group + + if (bHiBlock) infoMsg += String.format(""\nBlocks: %,d"", numSet.size()); + else if (bHiCset) infoMsg += String.format(""\nCosets: %,d"", numSet.size()); + + if (nG2xN>0) { + String x = (nG2xN==2) ? ""g2x2"" : ""g2x1""; + int cnt = (nG2xN==2) ? (cntHighG2xN+cntFiltG2xN) : cntHighG2xN; + if (cntHighG2xN>0 && (cntFiltG2xN>0 ||cntPossG2xN>0)) infoMsg += String.format(""\n\n%-11s: %,3d"", x, cnt); + else infoMsg += String.format(""\n\n%s: %,d"", x, cnt); + + if (cntFiltG2xN>0) infoMsg += String.format(""\n%-11s: %,3d"", ""Filtered g2"", cntFiltG2xN); + if (cntPossG2xN>0) infoMsg += String.format(""\n%-11s: %,3d (red)"", ""Possible g2"", cntPossG2xN); + } + } + /************************************************************* + * Hover and popups + */ + // Hit list: each is HitTag\ncoord1\ncoord2 + // For sequence object - hits aligned to a gene; Annotation.popDesc expects this format + public String getHitsForGenePopup(Sequence seqObj, Annotation annoObj, TreeMap hitScores) { + String listVis= """"; + boolean isQuery = mapper.isQueryTrack(seqObj); + + for (DrawHit drObj : allHitsArray) { + HitData hdObj = drObj.hitDataObj; + if (!hitScores.containsKey(hdObj.getID())) continue; + + String star = hdObj.getMinorForGenePopup(isQuery, annoObj.getAnnoIdx()); + String score = ""("" + hitScores.get(hdObj.getID()) + "")""; + + String minorTag = (star.equals(""*"")) ? annoObj.getFullGeneNum() : null; + String coords = hdObj.getHitCoordsForGenePopup(isQuery, minorTag) + ""\n""; + + String hit = String.format(""%s%s %s\n%s"", star.trim(), hdObj.hitGeneTag, score, coords); + + listVis += hit + "";""; + } + return listVis; + } + public boolean hasVisHit(int [] idxList) { // Called from Sequence for Annotation display GeneNum + for (DrawHit drObj : allHitsArray) { + if (!drObj.isDisplayed) continue; + int idx = drObj.hitDataObj.getID(); + for (int i=0; i hitList, int start, int end, boolean swap) { + if ( isContained(start, end, swap) ) + hitList.add(hitDataObj); + } + + private void setMinMax(HfilterData hf) {// for seqHits + hf.condSetPctid(hitDataObj.getPctid()); + } + private boolean isFiltered() { + // hit filter PCT + HfilterData hf = mapper.getHitFilter(); + boolean bIsNotPCT = (hitDataObj.getPctid()0) { + if (hitDataObj.getBlock() == hf.getBlock()) return false; + isDisplayed=false; + return true; + } + + boolean noNoOtherSet = !hf.isCset() && !hf.is2Gene() && !hf.is1Gene() && !hf.is0Gene(); + if (!hf.isBlock() && noNoOtherSet) return false; // all hits + + if (hf.isBlock()) { // block set + boolean bHitIsBlk = hitDataObj.isBlock();// block hit + if (bHitIsBlk && noNoOtherSet) return false; // no other checks, so not filtered + + boolean and = (hf.isBlockAnd()); + if (!and && bHitIsBlk) return false; // or, is block, show regardless what else + + if (and && !bHitIsBlk) { + isDisplayed=false; + return true; // and, !block, filter + } + } + if (hitDataObj.isCset() && hf.isCset()) return false; + if (hitDataObj.is2Gene() && hf.is2Gene()) return false; + if (hitDataObj.is1Gene() && hf.is1Gene()) return false; + if (hitDataObj.is0Gene() && hf.is0Gene()) return false; + + // not display + isDisplayed=false; + return true; + } + private Color getCColor(String orient, int hcolor, boolean bCnt) { + if (isHover) return Mapper.pseudoLineHoverColor; + + HfilterData hf = mapper.getHitFilter(); + + if (hf.isHiPopup() && hitDataObj.isPopup()) return Mapper.pseudoLineGroupColor; + if (hf.isHiPopup() && isQuerySelHit) return Mapper.pseudoLineGroupColor; + + if (hitDataObj.isHighG2xN()) { // takes precedence over highlight + if (hitDataObj.isForceG2xN()) { + if (bCnt) cntFiltG2xN++; + return Mapper.pseudoLineHighlightColor2; // default pink + } + else{ + if (bCnt) cntHighG2xN++; + return Mapper.pseudoLineHighlightColor1; // default green + } + } + else if (hitDataObj.isForceG2xN()) { + if (bCnt) cntPossG2xN++; + return Color.red; // default red + } + + boolean isHi=false; + if (hf.isHiBlock() && hitDataObj.isBlock()) isHi=true; + else if (hf.isHiCset() && hitDataObj.isCset()) isHi=true; + else if (hf.isHi2Gene() && hitDataObj.is2Gene()) isHi=true; + else if (hf.isHi1Gene() && hitDataObj.is1Gene()) isHi=true; + else if (hf.isHi0Gene() && hitDataObj.is0Gene()) isHi=true; + if (isHi) { + if (bCnt) cntHighHit++; + if (hcolor==1) return Mapper.pseudoLineHighlightColor1; + else if (hcolor==2) return Mapper.pseudoLineHighlightColor2; + else if (hcolor==3) return Mapper.pseudoLineHighlightColor3; + else if (hcolor==4) return Mapper.pseudoLineHighlightColor4; + } + + if (orient.contentEquals(""++"")) return Mapper.pseudoLineColorPP; + if (orient.contentEquals(""+-"")) return Mapper.pseudoLineColorPN; + if (orient.contentEquals(""-+"")) return Mapper.pseudoLineColorNP; + if (orient.contentEquals(""--"")) return Mapper.pseudoLineColorNN; + return Mapper.pseudoLineColorPP; + } + //////////////////////////////////////////////////////////////////// + private boolean isOlapHit() { // partial hit can be viewed + boolean seq1 = seqObj1.isHitOlap(hitDataObj.start1, hitDataObj.end1); + boolean seq2 = seqObj2.isHitOlap(hitDataObj.start2, hitDataObj.end2); + return seq1 && seq2; + } + + // is Hit Wire contained in hover, or hits for align; + private boolean isContained(int start, int end, boolean isQuery) { + if (!isOlapHit()) return false; + if (isFiltered()) return false; + + int s = (isQuery) ? hitDataObj.start1 : hitDataObj.start2; + int e = (isQuery) ? hitDataObj.end1 : hitDataObj.end2; + + return (s >= start && s <= end) || (e >= start && e <= end) || (start >= s && end <= e); + } + + private boolean lineContains(Point p) { + double lx1 = hitWire.getX1(); + double lx2 = hitWire.getX2(); + double ly1 = hitWire.getY1(); + double ly2 = hitWire.getY2(); + + double delta = p.getY() - ly1 - ((ly2-ly1)/(lx2-lx1)) * (p.getX()-lx1); + + return (delta >= -MOUSE_PADDING && delta <= MOUSE_PADDING); + } + protected boolean isContained(Point point) { + return isOlapHit() && lineContains(point); + } + private void set(boolean isSelectedHit) { + isQuerySelHit = isSelectedHit; + } + + // provide hover; called from main mouseMoved + private boolean mouseMovedHit(MouseEvent e) { + if (!isDisplayed) return false; + + boolean b = isOlapHit() && lineContains(e.getPoint()); + if (setHover(b)) { + mapper.getDrawingPanel().repaint(); + return true; + } + return false; + } + + protected boolean setHover(boolean bHover) { // mouseMoved/isHover + if (bHover != this.isHover) { + this.isHover = bHover; + return true; + } + return false; + } + + /*************************************************************************** + * Draw hit line connector, and hit info on seq1/seq2 rectangle (%ID, hitLen) + * draw if any of the hit is visible; if hit wire not visible, draw length and put hit-wire at very end + * trackPos1 and trackPos2: 1 or 2 indicating left or right + * stLoc1 and stLoc2: x,y from origin + */ + private boolean paintComponent(Graphics2D g2, int trackPos1, int trackPos2, Point stLoc1, Point stLoc2, int hcolor, boolean isText) { + if (!isOlapHit() || isFiltered()) return false; + + if (!isText) cntShowHit++; + + // get border locations of sequence tracks to draw hit stuff to it and along it + // sqObj.getPointForHit truncates point to not overlap track ends + Point2D hw1 = seqObj1.getPointForHit(hitDataObj.mid1 , trackPos1 ); + hw1.setLocation(hw1.getX() + stLoc1.getX(), hw1.getY() + stLoc1.getY()); + + Point2D hw2 = seqObj2.getPointForHit(hitDataObj.mid2 , trackPos2 ); + hw2.setLocation(hw2.getX() + stLoc2.getX(), hw2.getY() + stLoc2.getY()); + + int x1 = (int)hw1.getX(), y1 = (int)hw1.getY(); + int x2 = (int)hw2.getX(), y2 = (int)hw2.getY(); + int pctid = (int)hitDataObj.getPctid(); + + // hitLine: hit connecting seq1/seq2 chromosomes + if (!isText) { + Color c = getCColor(hitDataObj.getOrients(), hcolor, true); + if (c==Mapper.pseudoLineGroupColor) g2.setStroke(new BasicStroke(3)); + g2.setPaint(c); + hitWire.setLine(hw1,hw2); + g2.draw(hitWire); + if (c==Mapper.pseudoLineGroupColor) g2.setStroke(new BasicStroke(1)); + + /* %id line: paint in seq1/2 rectangle the %id length; */ + // id=19 is 5 outside rect, id=23 is 7 inside rect; id=100 is 30 far in rect + + int lineScoreLen = Math.max(1, 30*(pctid+1)/(100+1)); + int len1=off1, len2 = off2; + if (trackPos1 == Globals.RIGHT_ORIENT) { + lineScoreLen = 0 - lineScoreLen; + len1 = 0 - len1; + len2 = 0 - len2; + } + + // Hit length: paint in sequence objects the rectangle for the hit length graphics ; + // if no hitLen, then no scoreLine either. If no scoreLine, use LINE_W + if (seqObj1.getShowHitLen()) { + int wlen1 = seqObj1.getShowScoreLine() ? lineScoreLen : len1; + g2.drawLine(x1, y1, x1-wlen1, y1); + + Point2D rp1 = seqObj1.getPointForHit(hitDataObj.getStart1(), trackPos1); + Point2D rp2 = seqObj1.getPointForHit(hitDataObj.getEnd1(), trackPos1); + + if (Math.abs(rp2.getY()-rp1.getY()) > 3) { // only draw if it will be visible + rp1.setLocation(x1-wlen1, rp1.getY()); + rp2.setLocation(x1-wlen1, rp2.getY()); + + paintHitLen(g2, seqObj1, rp1, rp2, trackPos1, hitDataObj.isPosOrient1(), hcolor); + } + } + if (seqObj2.getShowHitLen()) { + int wlen2 = seqObj2.getShowScoreLine() ? lineScoreLen : len2; + g2.drawLine(x2, y2, x2+wlen2, y2); + + Point2D rp3 = seqObj2.getPointForHit(hitDataObj.getStart2(), trackPos2); + Point2D rp4 = seqObj2.getPointForHit(hitDataObj.getEnd2(), trackPos2); + + if (Math.abs(rp4.getY()-rp3.getY()) > 3) { // only draw if it will be visible + rp3.setLocation(x2+wlen2, rp3.getY()); + rp4.setLocation(x2+wlen2, rp4.getY()); + + paintHitLen(g2, seqObj2, rp3, rp4, trackPos2, hitDataObj.isPosOrient2(), hcolor); + } + } + // Hover over hit line connector; creation in HitData + if (isHover) mapper.setHelpText(hitDataObj.createHover(st1LTst2)); + } + else {/******** text from sequence.Filter 'Show text' ***********/ + int xr=4, xl=19; + + String numText1=null; + if (seqObj1.getShowBlock1stText()) { + int n = hitDataObj.getBlock(); + if (n>0) { + Block blk = blockMap.get(n); + int hitnum = hitDataObj.getHitNum(); + if (!seqObj1.isFlipped()) { + if (hitnum==blk.hitnum1) numText1 = ""b""+n; + } + else { + if (hitnum==blk.hitnumN) numText1 = ""b""+n; + } + } + } + else if (seqObj1.getShowBlockText()) { + int n = hitDataObj.getBlock(); + if (n>0) numText1 = ""b""+n; + } + else if (seqObj1.getShowCsetText()) { + int n = hitDataObj.getCollinearSet(); + if (n>0) numText1 = ""c""+n; + } + else if (seqObj1.getShowHitNumText()) numText1 = ""#"" + hitDataObj.getHitNum(); + else if (seqObj1.getShowScoreText()) numText1 = (int)pctid+""%""; + + if (numText1!=null) { + double textX = x1; + if (x1 < x2) textX += xr; + else { + int nl = numText1.length()-1; + textX -= (xl + (nl*4)); + } + if (Math.abs(y1-lastText1)>TEXTCLOSE) { + g2.setPaint(Color.black); + if (seqObj1.getShowBlock1stText()) g2.setFont(textFontBig); + else g2.setFont(textFont); + g2.drawString(numText1, (int)textX, (int)y1); + lastText1 = y1; + } + + } + + String numText2=null; + if (seqObj2.getShowBlock1stText()) { + int n = hitDataObj.getBlock(); + if (n>0) { + Block blk = blockMap.get(n); + int hitnum = hitDataObj.getHitNum(); + if (!seqObj2.isFlipped()) { + if ((!blk.isInv && hitnum==blk.hitnum1) || (blk.isInv && hitnum==blk.hitnumN)) numText2 = ""b""+n; + } + else { + if ((!blk.isInv && hitnum==blk.hitnumN) || (blk.isInv && hitnum==blk.hitnum1)) numText2 = ""b""+n; + } + } + } + else if (seqObj2.getShowBlockText()) { + int n = hitDataObj.getBlock(); + if (n>0) numText2 = ""b""+n; + } + else if (seqObj2.getShowCsetText()) { + int n = hitDataObj.getCollinearSet(); + if (n>0) numText2 = ""c""+n; + } + else if (seqObj2.getShowHitNumText()) numText2 = ""#""+hitDataObj.getHitNum(); + else if (seqObj2.getShowScoreText()) numText2 = (int)pctid +""%""; + + if (numText2!=null) { + double textX = x2; + if (x1 < x2) { + int nl = numText2.length()-1; + textX -= (xl + (nl*4)) ; + } + else textX += xr; + + if (Math.abs(y2-lastText2)>TEXTCLOSE) { // not sorted on this side, so may not work all the time + g2.setPaint(Color.black); + if (seqObj2.getShowBlock1stText()) g2.setFont(textFontBig); + else g2.setFont(textFont); + g2.drawString(numText2, (int)textX, (int)y2); + lastText2 = y2; + } + } + } + return true; + } + /*************************************************************************** + * Draw hit - draws the length of the hit along the blue chromosome box, which shows breaks between merged hitsd + */ + private void paintHitLen(Graphics2D g2, Sequence st, Point2D pStart, Point2D pEnd, + int trackPos, boolean forward, int hcolor) { + double psx = pStart.getX(); + double psy = pStart.getY(); + double w = Mapper.hitRibbonWidth; + + String subHits; + Rectangle2D.Double rect; + + if (mapper.isQueryTrack(st)) + subHits = hitDataObj.getQueryMerge(); + else + subHits = hitDataObj.getTargetMerge(); + + if (subHits == null || subHits.length() == 0) { + g2.setPaint(getCColor(hitDataObj.getOrients(), hcolor, false)); + rect = new Rectangle2D.Double(psx, psy, w, pEnd.getY()-psy); + + fixRect(rect); // for flipped track + g2.fill(rect); + } + else { + // Draw background rectangle + g2.setPaint(Mapper.hitRibbonBackgroundColor); // grey between merged hits + rect = new Rectangle2D.Double(psx, psy, w, pEnd.getY()-psy); + fixRect(rect); // for flipped track + g2.fill(rect); + g2.draw(rect); + + g2.setPaint(getCColor(hitDataObj.getOrients(), hcolor, false)); + + // Draw sub-hits + String[] subseq = subHits.split("",""); + for (int i = 0; i < subseq.length; i++) { + String[] pos = subseq[i].split("":""); + int start = Integer.parseInt(pos[0]); + int end = Integer.parseInt(pos[1]); + + Point2D p1 = st.getPointForHit(start, trackPos); + p1.setLocation( pStart.getX(), p1.getY() ); + + Point2D p2 = st.getPointForHit(end, trackPos); + p2.setLocation( pStart.getX(), p2.getY() ); + + rect.setRect( p1.getX(), p1.getY(), w, p2.getY()-p1.getY() ); + fixRect(rect); // for flipped track + g2.fill(rect); + g2.draw(rect); + } + } + } + // adjust rectangle coordinates for negative width or height - on flipped + private void fixRect(Rectangle2D rect) { + if (rect.getWidth() < 0) + rect.setRect(rect.getX()+rect.getWidth()+1, rect.getY(), Math.abs(rect.getWidth()), rect.getHeight()); + + if (rect.getHeight() < 0) + rect.setRect(rect.getX(), rect.getY()+rect.getHeight()+1, rect.getWidth(), Math.abs(rect.getHeight())); + } + /* popup from clicking hit wire; */ + private void popupDesc(double x, double y) { + if (mapper.getHitFilter().isHiPopup()) hitDataObj.setIsPopup(true); + + String title=""Hit #"" + hitDataObj.getHitNum(); + + String theInfo = hitDataObj.createPopup(st1LTst2) + ""\n""; + + String proj1 = seqObj1.getTitle(); //Proj Chr + String proj2 = seqObj2.getTitle(); + Annotation aObj1 = seqObj1.getAnnoObj(hitDataObj.getAnnot1(), hitDataObj.getAnnot2()); // check seqObj1 geneVec + Annotation aObj2 = seqObj2.getAnnoObj(hitDataObj.getAnnot1(), hitDataObj.getAnnot2()); // check seqObj2 geneVec + + String trailer = """"; + if (Globals.INFO) { + trailer = ""\nDB-index "" + hitDataObj.getID(); // useful for debugging + trailer += ""\nAnnot "" + hitDataObj.getAnnots(); + } + + AlignPool ap = new AlignPool(mapper.getDrawingPanel().getDBC()); + + new TextShowInfo(ap, hitDataObj, title, + theInfo, trailer, st1LTst2, proj1, proj2, aObj1, aObj2, + hitDataObj.getQuerySubhits(), hitDataObj.getTargetSubhits(), + seqObj1.isQuery(), hitDataObj.isInv(), true /*bsort*/); + } + public String toString() {return hitDataObj.createHover(true);} + } // End class DrawHit + + // To draw block num at beginning + private class Block { + int hitnum1=0, hitnumN=0; + boolean isInv=false; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/Mapper.java",".java","9706","259","package symap.mapper; + +import java.util.Vector; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.MouseMotionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseWheelListener; +import javax.swing.JComponent; +import javax.swing.JButton; + +import props.PropsDB; +import props.PropertiesReader; +import database.DBconn2; +import symap.Globals; +import symap.drawingpanel.DrawingPanel; +import symap.drawingpanel.FilterHandler; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import symap.sequence.Sequence; +import symap.sequence.TrackHolder; +import symapQuery.TableMainPanel; +import util.ErrorReport; + +/** + * The Mapper that holds two tracks (overlaying them when drawn) and all of the hits. + * Called from DrawingPanel + */ +public class Mapper extends JComponent implements MouseMotionListener, MouseListener, MouseWheelListener, HelpListener { + private static final long serialVersionUID = 1L; + // ColorDialog colors at bottom + private DrawingPanel drawingPanel; + private TrackHolder trackHolders[]; + private FilterHandler fh; + private HfilterData hitFilData; + private TableMainPanel theTablePanel; + private SeqHits seqHitObj; + private MapperPool mapPool; + + private volatile boolean initing; + private String helpText; + + // Created in DrawingPanel for display + public Mapper(DrawingPanel drawingPanel, TrackHolder th1, TrackHolder th2, + FilterHandler fh, DBconn2 dbc2, PropsDB projPool, HelpBar hb, TableMainPanel listPanel) + { + super(); + this.mapPool = new MapperPool(dbc2, projPool); + this.drawingPanel = drawingPanel; + this.fh = fh; + this.theTablePanel = listPanel; + initing = true; + + hitFilData = new HfilterData(); + fh.setHfilter(this); // creates Hfilter with this hitFilData + + trackHolders = new TrackHolder[2]; + trackHolders[0] = th1; + trackHolders[1] = th2; + + setOpaque(false); + setVisible(false); + addMouseListener(this); + addMouseWheelListener(this); + addMouseMotionListener(this); + + if (hb != null) hb.addHelpListener(this,this); + } + public boolean initHits() { // DrawingPanel.make and above + Sequence t1 = trackHolders[0].getTrack(); + Sequence t2 = trackHolders[1].getTrack(); + + if (t1 == null || t2 == null) return false; + + if (seqHitObj!=null) return true; + + initing = true; + seqHitObj = mapPool.setData(this, t1, t2); + seqHitObj.setMinMax(hitFilData); + initing = false; + + if (seqHitObj==null) ErrorReport.print(""SyMAP internal error getting hits""); + return (seqHitObj!=null); + } + public void setVisible(boolean visible) { + fh.getFilterButton().setEnabled(visible); + super.setVisible(visible); + } + + public void update() {} // HitFilter; + + public void setMapperData(MapperData md) { // DrawingPanel.setMaps for history + if (md != null) { + md.setMapper(this); + initHits(); + } + } + + public MapperData getMapperData() {return new MapperData(this);} + public DrawingPanel getDrawingPanel() { return drawingPanel;} + public HfilterData getHitFilter() {return hitFilData;} + + // For HitData.getCoordsForGenePopup and createHover + public String getGeneNum1(int annoIdx) { return seqHitObj.getSeqObj1().getGeneNumFromIdx(annoIdx);} + public String getGeneNum2(int annoIdx) { return seqHitObj.getSeqObj2().getGeneNumFromIdx(annoIdx);} + + public JButton getFilterButton() {return fh.getFilterButton();} + public Sequence getTrack1() {return trackHolders[0].getTrack();} + public Sequence getTrack2() {return trackHolders[1].getTrack();} + public Sequence getTrack(int trackNum) {return trackHolders[trackNum].getTrack();} + + protected int getTrackPosition(Sequence t) { + if (trackHolders[0].getTrack() == t) return Globals.LEFT_ORIENT; + else return Globals.RIGHT_ORIENT; + } + // closeup align + public Vector getHitsInRange(Sequence src, int start, int end) { + Vector retHits = new Vector(); + seqHitObj.getHitsInRange(retHits, start, end, isQueryTrack(src)); + return retHits; + } + + public int[] getMinMax(Sequence src, int start, int end) { + int[] minMax = new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE }; + + seqHitObj.getMinMax(minMax, start, end, isQueryTrack(src)); + + if (minMax[0] == Integer.MAX_VALUE || minMax[1] == Integer.MIN_VALUE) + return null; // no hits within range + + return minMax; + } + + /********************************************** + * hasPair is (query,target); query0) {setBlockOnly(true); setBlockNum(blockNum);} + else if (s) {setCset(true); setHiCset(true); } + else if (r) {setHiBlock(true);} + + } + // dotplot + public void setForDP(int blockNum) { + setBlockOnly(false); setBlock(false); setCset(false); setHiNone(false); + + if (blockNum>0) {setBlockOnly(true); setBlockNum(blockNum);} + else {setAll(true); setHiBlock(true);} // CAS575 add setAll + } + + // this changes initial settings for dotplot and query table + public boolean setChanged(HfilterData hf, String msg) { + boolean changed = false; + if (setHiBlock(hf.bHiBlock)) changed = true; + if (setHiCset(hf.bHiCset)) changed = true; + if (setHi2Gene(hf.bHi2Gene)) changed = true; + if (setHi1Gene(hf.bHi1Gene)) changed = true; + if (setHi0Gene(hf.bHi0Gene)) changed = true; + if (setHiNone(hf.bHiNone)) changed = true; + if (setHiPopup(hf.bHiPopup)) changed = true; + + if (setBlock(hf.bBlock)) changed = true; + if (setBlockAnd(hf.bBlockAnd)) changed = true; + if (setBlockOr(hf.bBlockOr)) changed = true; + if (setBlockOnly(hf.bBlockOnly)) changed = true; + if (setBlockNum(hf.blkNum)) changed = true; + + if (setCset(hf.bCset)) changed = true; + if (set2Gene(hf.b2Gene)) changed = true; + if (set1Gene(hf.b1Gene)) changed = true; + if (set0Gene(hf.b0Gene)) changed = true; + + if (setAll(hf.bAll)) changed = true; + + if (setPctid(hf.pctid)) changed = true; + + return changed; + } + + /*******************************************************/ +// %id + protected double getPctid() {return pctid;} + protected boolean setPctid(double score) { + if (pctid != score) { + pctid = score; + return true; + } + return false; + } + protected double getMinPctid() {return minPctid;} + protected double getMaxPctid() {return maxPctid;} + protected void condSetPctid(double hitid) { // set when HfilterData is created + if (hitid < minPctid) minPctid = hitid; + if (hitid > maxPctid) maxPctid = hitid; + } + +// highs + protected boolean isHiPopup() {return bHiPopup;} + protected boolean setHiPopup(boolean filter) { + if (filter != bHiPopup) { + bHiPopup = filter; + return true; + } + return false; + } + protected boolean isHiNone() {return bHiNone;} + protected boolean setHiNone(boolean filter) { + if (filter != bHiNone) { + bHiNone = filter; + return true; + } + return false; + } + + protected boolean isHiBlock() {return bHiBlock;} + protected boolean setHiBlock(boolean filter) { + if (filter != bHiBlock) { + bHiBlock = filter; + return true; + } + return false; + } + + protected boolean isHiCset() {return bHiCset;} + protected boolean setHiCset(boolean bFilter) { + if (bFilter != bHiCset) { + bHiCset = bFilter; + return true; + } + return false; + } + protected boolean isHi2Gene() {return bHi2Gene;} + protected boolean setHi2Gene(boolean bFilter) { + if (bFilter != bHi2Gene) { + bHi2Gene = bFilter; + return true; + } + return false; + } + protected boolean isHi1Gene() {return bHi1Gene;} + protected boolean setHi1Gene(boolean bFilter) { + if (bFilter != bHi1Gene) { + bHi1Gene = bFilter; + return true; + } + return false; + } + + protected boolean isHi0Gene() { return bHi0Gene;} + protected boolean setHi0Gene(boolean bFilter) { + if (bFilter != bHi0Gene) { + bHi0Gene = bFilter; + return true; + } + return false; + } +// shows + protected boolean isBlock() {return bBlock;} + protected boolean setBlock(boolean bFilter) { + if (bFilter != bBlock) { + bBlock = bFilter; + return true; + } + return false; + } + + protected boolean isBlockAnd() {return bBlockAnd;} + protected boolean setBlockAnd(boolean bFilter) { + if (bFilter != bBlockAnd) { + bBlockAnd = bFilter; + return true; + } + return false; + } + protected boolean isBlockOr() {return bBlockOr;} + protected boolean setBlockOr(boolean bFilter) { + if (bFilter != bBlockOr) { + bBlockOr = bFilter; + return true; + } + return false; + } + + protected boolean isBlockOnly() {return bBlockOnly;} + protected boolean setBlockOnly(boolean bFilter) { + if (bFilter != bBlockOnly) { + bBlockOnly = bFilter; + return true; + } + return false; + } + protected int getBlock() {return blkNum;} + protected boolean setBlockNum(int bn) { + if (blkNum != bn) { + blkNum = bn; + return true; + } + return false; + } + + protected boolean isCset() { return bCset;} + protected boolean setCset(boolean bFilter) { + if (bFilter != bCset) { + bCset = bFilter; + return true; + } + return false; + } + + protected boolean is2Gene() {return b2Gene;} + protected boolean set2Gene(boolean bFilter) { + if (bFilter != b2Gene) { + b2Gene = bFilter; + return true; + } + return false; + } + + protected boolean is1Gene() {return b1Gene;} + protected boolean set1Gene(boolean bFilter) { + if (bFilter != b1Gene) { + b1Gene = bFilter; + return true; + } + return false; + } + + protected boolean is0Gene() {return b0Gene;} + protected boolean set0Gene(boolean bFilter) { + if (bFilter != b0Gene) { + b0Gene = bFilter; + return true; + } + return false; + } + + protected boolean isAll() {return bAll;} + protected boolean setAll(boolean bFilter) { + if (bFilter != bAll) { + bAll = bFilter; + return true; + } + return false; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/MapperData.java",".java","467","20","package symap.mapper; + +/** + * Class MapperData holds the data of a mapper which can be + * used to recreate the same state of a Mapper - may be used for History. + * DrawingPanel and Mapper + */ +public class MapperData { + + private HfilterData hf; + + protected MapperData(Mapper mapper) { + this.hf = mapper.getHitFilter().copy(""MapperData""); + } + + protected void setMapper(Mapper mapper) { + mapper.getHitFilter().setChanged(hf, ""setMapper""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/MapperPool.java",".java","5836","149","package symap.mapper; + +import java.util.Vector; + +import java.sql.ResultSet; + +import database.DBconn2; +import database.Version; +import props.PropsDB; +import symap.Globals; +import symap.sequence.Sequence; +import util.ErrorReport; + +/** + * Create an array of Hits from the DB and passes them to a SeqHit object + */ +public class MapperPool { + private DBconn2 dbc2; + private PropsDB projPairs; // properties + + public MapperPool(DBconn2 dbc2, PropsDB projPool) { // Created when Mapper is created + this.dbc2 = dbc2; + this.projPairs = projPool; + } + + protected boolean hasPair(Sequence t1, Sequence t2) { + return projPairs.hasPair(t1.getProjIdx(),t2.getProjIdx()); + } + + protected SeqHits setData(Mapper mapper, Sequence t1, Sequence t2) { // Mapper.isInit + SeqHits seqHitObj; + + if (hasPair(t1,t2)) seqHitObj = setSeqHitData(mapper, (Sequence)t1, (Sequence)t2); + else seqHitObj = setSeqHitData(mapper, (Sequence)t2, (Sequence)t1); + + return seqHitObj; + } + + /************************************************************************* + * Update HitData + */ + private SeqHits setSeqHitData(Mapper mapper, Sequence st1, Sequence st2) { + int grpIdx1 = st1.getGroup(); + int grpIdx2 = st2.getGroup(); + boolean isSelf = st1.getProjIdx() == st2.getProjIdx(); + try { + int n = dbc2.executeCount(""select count(*) from pseudo_hits where grp1_idx=""+grpIdx1 + "" AND grp2_idx=""+ grpIdx2); + Vector hitList = new Vector (n); + + String sql = ""SELECT h.idx, h.hitnum, h.pctid, h.cvgpct, h.countpct, h.score, h.htype, h.gene_overlap, "" + + ""h.annot1_idx, h.annot2_idx, h.strand, h.start1, h.end1, h.start2, h.end2, h.query_seq, h.target_seq, "" + + ""h.runnum, h.runsize, b.blocknum, b.corr "" + + ""FROM pseudo_hits AS h "" + + ""LEFT JOIN pseudo_block_hits AS bh ON (bh.hit_idx=h.idx) "" + + ""LEFT JOIN blocks as b on (b.idx=bh.block_idx) "" + + ""WHERE h.grp1_idx="" + grpIdx1 + "" AND h.grp2_idx=""+ grpIdx2; + + if (isSelf) { // DIR_SELF; same as in QueryPanel + if (grpIdx1>grpIdx2) sql += "" and h.refidx=0 ""; // grp1>grp2 lower tile + else if (grpIdx10 ""; // grp1h.start2 ""; // lower part of self-chr diagonal for given grp only + } + sql += "" order by h.start1""; + + ResultSet rs = dbc2.executeQuery(sql); + + // 1 idx, 2 hitnum, 3 pctid, 4 cvgpct (sim), 5 countpct (merge), 6 score, 7 gene_overlap + // 8 annot1_idx, 9 annot2_idx, 10 strand, 11 start1, 12 end1, 13 start2, 14 end2, 15 query_seq, 16 target_seq, + // 17 runnum, 18 runsize, 19 block, 20 bcorr + while (rs.next()) { + int i=1; + HitData temp = new HitData(mapper, + rs.getInt(i++), // int id + rs.getInt(i++), // int hitnum + rs.getDouble(i++), // double pctid + rs.getInt(i++), // int cvgpct->avg %sim + rs.getInt(i++), // int countpct -> nMergedHits + rs.getInt(i++), // h.score + rs.getString(i++), // h.htype + rs.getInt(i++), // int gene_overlap + + rs.getInt(i++), // int annot1_idx + rs.getInt(i++), // int annot2_idx + rs.getString(i++), // String strand + rs.getInt(i++), // int start1 + rs.getInt(i++), // int end1 + rs.getInt(i++), // int start2 + rs.getInt(i++), // int end2 + rs.getString(i++), // String query_seq + rs.getString(i++), // String target_seq + + rs.getInt(i++), // int runnum + rs.getInt(i++), // int runsize + rs.getInt(i++), // int b.block + rs.getDouble(i++) // int b.corr + ); + hitList.add(temp); + } + rs.close(); + if (hitList.size()==0) { + Globals.prt(""No hits for "" + st1.getTitle() + "" to "" + st2.getTitle()); + if (st1.getProjIdx() == st2.getProjIdx()) { // VER_CHG + int pairIdx = projPairs.getPairIdx(st1.getProjIdx(), st2.getProjIdx()); + if (pairIdx==-1) Globals.eprt(""Cannot get pairIdx""); + else if (new Version(dbc2).isVerLt(pairIdx, 575)) + util.Popup.showWarning(""Self-synteny must be updated with A&S v5.7.5 or later to fully work""); + } + } + + if (projPairs.hasPseudo(st1.getProjIdx(), st2.getProjIdx())) { + zeroPseudo(1, grpIdx1, hitList); + zeroPseudo(2, grpIdx2, hitList); + } + if (Globals.TRACE) { + String x = String.format(""MP: Total hits %,d: %d (%d) Merged: %d (%d)"", + hitList.size(), HitData.cntTotal, HitData.cntTotalSH, HitData.cntMerge, HitData.cntMergeSH); + Globals.dprt(x); + Globals.dprt(st1.toString() + ""\n"" + st2.toString()); + } + HitData.cntTotal= HitData.cntMerge = HitData.cntTotalSH= HitData.cntMergeSH = 0; + + SeqHits seqHitObj = new SeqHits(mapper, st1, st2, hitList); + hitList.clear(); + return seqHitObj; + } + catch (Exception e) {ErrorReport.print(e, ""Get hit data"");return null;} + } + /*********************************************************************** + * Set numbered pseudo genes annot_idx to zero. + * Everything works when HitData has annot_idx>0 for pseudo genes, but it could cause problems. + * It is not a problem if the search is always on gene_overlap=2,1,0. + * + * All genes for a chromosome are loaded, hence, any idx after that for this chr (grpIdx) is pseudo. + * Even if another project is loaded, its idx's will not occur in this list. + */ + private void zeroPseudo(int which, int grpIdx, Vector hitList) { + try { + int maxGeneIdx = dbc2.executeCount(""select max(pa.idx) from pseudo_annot as pa "" // could also be min(idx) pseudo + + ""join xgroups as g on pa.grp_idx=g.idx "" + + ""where pa.type='gene' and pa.grp_idx="" + grpIdx); + for (HitData hd : hitList) { + if (which==1 && hd.annot1_idx>maxGeneIdx) {hd.annot1_idx=0; } + else if (which==2 && hd.annot2_idx>maxGeneIdx) {hd.annot2_idx=0; } + } + } + catch (Exception e) {ErrorReport.print(e, ""Zero #pseudo"");} + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/Hfilter.java",".java","17306","463","package symap.mapper; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.Frame; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; + +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.JRadioButton; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; + +import symap.drawingpanel.DrawingPanel; +import util.Jcomp; +import util.Jhtml; +import util.Utilities; + +/** + * Hit Filter Interface: The Mapper filter dialog implementation. + * 1. Add filter here + * 2. Add to HfilterData + * 3. Add to SeqHits.isHighLightHit() and isFiltered() + */ +public class Hfilter extends JDialog { + private static final long serialVersionUID = 1L; + private final String SYN = ""Synteny blocks""; + private final String COL = ""Collinear sets""; + private final String HIT2 = ""Hit =2 genes (g2)""; + private final String HIT1 = ""Hit =1 genes (g1)""; + private final String HIT0 = ""Hit =0 genes (g0)""; + private final String ALL = ""All hits""; + private final String POPUP =""Hit popup (or Query)""; + private final String NONE = ""None""; + + // On Menu panel + private JButton okButton, cancelButton, defaultButton, helpButton; + private JPanel buttonPanel; + private JPopupMenu popupMenu; + private JMenuItem popupTitle; + + // highlight - only one can be selected + private JRadioButton hBlockRadio = Jcomp.createRadioGray(SYN, ""Highlight synteny block hits""); + private JRadioButton hCsetRadio = Jcomp.createRadioGray(COL, ""Highlight collinear set hits""); + private JRadioButton hGene2Radio = Jcomp.createRadioGray(HIT2, ""Highlight hits that align to genes on both sides""); + private JRadioButton hGene1Radio = Jcomp.createRadioGray(HIT1, ""Highlight hits that align to a gene on one side""); + private JRadioButton hGene0Radio = Jcomp.createRadioGray(HIT0, ""Highlight hits that do not align to a gene on either side""); + private JRadioButton hNoneRadio = Jcomp.createRadioGray(NONE, ""Turn off all highlightening""); + private JCheckBox hPopupCheck = Jcomp.createCheckBoxGray(POPUP, ""Highlight hit-wire and genes for hit popup""); + + // Show - any number can be selected + private JCheckBox sBlockCheck = Jcomp.createCheckBoxGray(SYN, ""Show all synteny hits""); + private JRadioButton blockAndRadio = Jcomp.createRadioGray(""And"", ""Hits shown will pass ALL checks""); + private JRadioButton blockOrRadio = Jcomp.createRadioGray(""Or"", ""Hits shown will pass ANY checks""); + + private JCheckBox sCsetCheck = Jcomp.createCheckBoxGray(COL, ""Show all collinear sets""); + private JCheckBox sGene2Check = Jcomp.createCheckBoxGray(HIT2, ""Show all hits aligning to genes on both sides""); + private JCheckBox sGene1Check = Jcomp.createCheckBoxGray(HIT1, ""Show all hits aligning to genes on one side""); + private JCheckBox sGene0Check = Jcomp.createCheckBoxGray(HIT0, ""Show all hits that do not align to any gene""); + private JCheckBox sAllCheck = Jcomp.createCheckBoxGray(ALL, ""Show all hits - overrides all but identity""); + + // Id + private JSlider pctidSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0); // 0 to 100, start at 0 + private JLabel pctidText = new JLabel(""0%""); + + private JCheckBox blockOnlyCheck = Jcomp.createCheckBoxGray(""Block #"", ""Only show this block's hits""); + private JTextField blockOnlyText = Jcomp.createTextField(""0"", ""Block number, hit return for immediate effect"", 2); + +// On popup menu + private JRadioButtonMenuItem hBlockPopRadio = new JRadioButtonMenuItem(SYN); + private JRadioButtonMenuItem hCsetPopRadio = new JRadioButtonMenuItem(COL); + private JRadioButtonMenuItem hGene2PopRadio = new JRadioButtonMenuItem(HIT2); + private JRadioButtonMenuItem hGene1PopRadio = new JRadioButtonMenuItem(HIT1); + private JRadioButtonMenuItem hGene0PopRadio = new JRadioButtonMenuItem(HIT0); + private JRadioButtonMenuItem hNonePopRadio = new JRadioButtonMenuItem(NONE); + private JCheckBoxMenuItem hPopupPopCheck = new JCheckBoxMenuItem(POPUP); + private JCheckBoxMenuItem sAllPopCheck = new JCheckBoxMenuItem(""Show "" + ALL); + + private Mapper mapper; + private HfilterData hitFiltData; // current settings + private HfilterData lastHitFiltData; // last settings + protected DrawingPanel drawingPanel; + + public Hfilter(Frame owner, DrawingPanel dp, Mapper map) { + super(owner,""Hit Filter"", true); + + this.drawingPanel = dp; + this.mapper = map; + hitFiltData = mapper.getHitFilter(); + setInit(hitFiltData); + + FilterListener listener = new FilterListener(); + + createFilterDialog(listener); + createPopup(listener); + } + /* Filter dialog */ + private void createFilterDialog(FilterListener listener) { + // Buttons + okButton = Jcomp.createButtonGray(""Save"",""Save changes and close""); + okButton.addActionListener(listener); + + cancelButton = Jcomp.createButtonGray(""Cancel"", ""Discard changes and close""); + cancelButton.addActionListener(listener); + + defaultButton = Jcomp.createButtonGray(""Defaults"", ""Reset to defaults""); + defaultButton.addActionListener(listener); + + helpButton = Jhtml.createHelpIconUserSm(Jhtml.hitfilter); + + buttonPanel = new JPanel(new BorderLayout()); + buttonPanel.add(new JSeparator(),BorderLayout.NORTH); + JPanel innerPanel = new JPanel(); + innerPanel.add(okButton); + innerPanel.add(cancelButton); + innerPanel.add(defaultButton); + innerPanel.add(helpButton); + buttonPanel.add(innerPanel,BorderLayout.CENTER); + + // Slider + JPanel sliderRow = Jcomp.createRowPanelGray(); + sliderRow.add(new JLabel("" Identity "")); // want gray background + sliderRow.add(pctidText); sliderRow.add(pctidSlider); + pctidSlider.addChangeListener(listener); + + JPanel rowOnly = Jcomp.createRowPanelGray(); + blockOnlyCheck.addActionListener(listener); + blockOnlyText.addActionListener(listener); + rowOnly.add(blockOnlyCheck); rowOnly.add(Box.createHorizontalStrut(2)); rowOnly.add(blockOnlyText); + + // Check boxes for menu + sBlockCheck.addActionListener(listener); + blockAndRadio.addActionListener(listener); + blockOrRadio.addActionListener(listener); + + ButtonGroup b2Group = new ButtonGroup(); + b2Group.add(blockAndRadio); b2Group.add(blockOrRadio); blockAndRadio.setSelected(true); + + sCsetCheck.addActionListener(listener); + sGene2Check.addActionListener(listener); + sGene1Check.addActionListener(listener); + sGene0Check.addActionListener(listener); + sAllCheck.addActionListener(listener); + + hBlockRadio.addActionListener(listener); + hCsetRadio.addActionListener(listener); + hGene2Radio.addActionListener(listener); + hGene1Radio.addActionListener(listener); + hGene0Radio.addActionListener(listener); + hNoneRadio.addActionListener(listener); + ButtonGroup highGroup = new ButtonGroup(); + highGroup.add(hBlockRadio); highGroup.add(hCsetRadio); + highGroup.add(hGene2Radio); highGroup.add(hGene1Radio); + highGroup.add(hGene0Radio); highGroup.add(hNoneRadio); + + hPopupCheck.addActionListener(listener); + + Container contentPane = getContentPane(); + GridBagLayout gridbag = new GridBagLayout(); + GridBagConstraints c1 = new GridBagConstraints(); + + contentPane.removeAll(); + + contentPane.setLayout(gridbag); + c1.fill = GridBagConstraints.HORIZONTAL; + c1.gridheight = 1; + c1.ipadx = 4; + c1.ipady = 7; + + // highlight + int rem=GridBagConstraints.REMAINDER; + addToGrid(contentPane, gridbag, c1, new JLabel("" Highlight""), rem); + addToGrid(contentPane, gridbag, c1, hBlockRadio, 1); + addToGrid(contentPane, gridbag, c1, hNoneRadio,rem); + + addToGrid(contentPane, gridbag, c1, hCsetRadio,1); + addToGrid(contentPane, gridbag, c1, hGene2Radio, rem); + + addToGrid(contentPane, gridbag, c1, hGene1Radio, 1); + addToGrid(contentPane, gridbag, c1, hGene0Radio, rem); + + addToGrid(contentPane, gridbag, c1, hPopupCheck, rem); + addToGrid(contentPane, gridbag, c1, new JSeparator(),rem); + + // show + addToGrid(contentPane, gridbag, c1, new JLabel("" Show""),rem); + addToGrid(contentPane, gridbag, c1, sBlockCheck, 1); + addToGrid(contentPane, gridbag, c1, blockAndRadio, 2); + addToGrid(contentPane, gridbag, c1, blockOrRadio, rem); + + addToGrid(contentPane, gridbag, c1, sCsetCheck, 1); + addToGrid(contentPane, gridbag, c1, sGene2Check, rem); + + addToGrid(contentPane, gridbag, c1, sGene1Check,1); + addToGrid(contentPane, gridbag, c1, sGene0Check, rem); + + addToGrid(contentPane, gridbag, c1, sAllCheck, rem); + + // %id & block# + addToGrid(contentPane, gridbag, c1, new JSeparator(),rem); + addToGrid(contentPane, gridbag, c1, sliderRow,rem); + + addToGrid(contentPane, gridbag, c1, rowOnly, 1); + addToGrid(contentPane, gridbag, c1, new JLabel(""""), rem); // only way to force to right + + // buttons + addToGrid(contentPane, gridbag, c1, buttonPanel,rem); + + setBackground(Color.white); + pack(); + setResizable(false); + setLocationRelativeTo(null); + } + private void addToGrid(Container cp, GridBagLayout layout, GridBagConstraints con, Component comp, int w) { + con.gridwidth = w; + layout.setConstraints(comp, con); + cp.add(comp); + } + + // Popup menu + private void createPopup(FilterListener listener) { + popupMenu = new JPopupMenu(); + popupMenu.setBackground(Color.white); + popupMenu.addPopupMenuListener(new MyPopupMenuListener()); + + popupTitle = new JMenuItem(""Hit Options""); popupTitle.setEnabled(false); + popupMenu.add(popupTitle); + + popupMenu.addSeparator(); + JLabel gtext = new JLabel("" Highlight""); gtext.setEnabled(false); + popupMenu.add(gtext); + popupMenu.add(hBlockPopRadio); + popupMenu.add(hCsetPopRadio); + popupMenu.add(hGene2PopRadio); + popupMenu.add(hGene1PopRadio); + popupMenu.add(hGene0PopRadio); + popupMenu.add(hNonePopRadio); + ButtonGroup grp = new ButtonGroup(); + grp.add(hBlockPopRadio); grp.add(hCsetPopRadio); grp.add(hGene2PopRadio); + grp.add(hGene1PopRadio); grp.add(hGene0PopRadio); grp.add(hNonePopRadio); + hNonePopRadio.setSelected(true); + + popupMenu.add(new JSeparator()); + popupMenu.add(sAllPopCheck); + + popupMenu.add(new JSeparator()); + popupMenu.add(hPopupPopCheck); + + hBlockPopRadio.addActionListener(listener); + hCsetPopRadio.addActionListener(listener); + hGene2PopRadio.addActionListener(listener); + hGene1PopRadio.addActionListener(listener); + hGene0PopRadio.addActionListener(listener); + hNonePopRadio.addActionListener(listener); + + hPopupPopCheck.addActionListener(listener); + sAllPopCheck.addActionListener(listener); + + popupMenu.setMaximumSize(popupMenu.getPreferredSize()); popupMenu.setMinimumSize(popupMenu.getPreferredSize()); + } + // Creates panel + public void displayHitFilter() { + setInit(hitFiltData); // must be before setSliderMaxMin; may have changed since Hfilter created + setSliderMaxMin(); + lastHitFiltData = hitFiltData.copy(""Hfilter showX""); + + setVisible(true); + } + + private boolean okAction() { + return lastHitFiltData.setChanged(getCopyHitFilter(), ""Hfilter okAction""); + } + private void cancelAction() { + setInit(lastHitFiltData); + } + private void setDefault() { + setInit(new HfilterData()); + } + private void refresh() { + if (hitFiltData.setChanged(getCopyHitFilter(), ""Hfilter refresh"")) { + mapper.setTrackBuild(); + drawingPanel.setReplaceHistory(); + drawingPanel.smake(""Hf: refresh""); + mapper.update(); + } + } + + /***************************************** + * set current filter values like the input filter; Cancel, Defaults and save lastHitFilter + */ + private void setInit(HfilterData hf) { + pctidSlider.setValue(getSliderPctid(hf.getPctid())); + pctidText.setText(getPctidString(pctidSlider.getValue())); + + sBlockCheck.setSelected(hf.isBlock()); + blockAndRadio.setSelected(hf.isBlockAnd()); + blockOrRadio.setSelected(hf.isBlockOr()); + blockOnlyCheck.setSelected(hf.isBlockOnly()); + blockOnlyText.setText(hf.getBlock()+""""); + + sCsetCheck.setSelected(hf.isCset()); + sGene2Check.setSelected(hf.is2Gene()); + sGene1Check.setSelected(hf.is1Gene()); + sGene0Check.setSelected(hf.is0Gene()); + sAllCheck.setSelected(hf.isAll()); + + hBlockRadio.setSelected(hf.isHiBlock()); + hCsetRadio.setSelected(hf.isHiCset()); + hGene2Radio.setSelected(hf.isHi2Gene()); + hGene1Radio.setSelected(hf.isHi1Gene()); + hGene0Radio.setSelected(hf.isHi0Gene()); + hNoneRadio.setSelected(hf.isHiNone()); + hPopupCheck.setSelected(hf.isHiPopup()); + } + + private HfilterData getCopyHitFilter() { // ok and refresh + HfilterData hf = new HfilterData(); + hf.setHiBlock(hBlockRadio.isSelected()); + + hf.setHiCset(hCsetRadio.isSelected()); + hf.setHi2Gene(hGene2Radio.isSelected()); + hf.setHi1Gene(hGene1Radio.isSelected()); + hf.setHi0Gene(hGene0Radio.isSelected()); + hf.setHiNone(hNoneRadio.isSelected()); + hf.setHiPopup(hPopupCheck.isSelected()); + + hf.setBlock(sBlockCheck.isSelected()); + hf.setBlockAnd(blockAndRadio.isSelected()); + hf.setBlockOr(blockOrRadio.isSelected()); + hf.setBlockOnly(blockOnlyCheck.isSelected()); + int n = Utilities.getInt(blockOnlyText.getText()); + if (n==-1) n=0; + hf.setBlockNum(n); + + hf.setCset(sCsetCheck.isSelected()); + hf.set2Gene(sGene2Check.isSelected()); + hf.set1Gene(sGene1Check.isSelected()); + hf.set0Gene(sGene0Check.isSelected()); + + hf.setAll(sAllCheck.isSelected()); + + hf.setPctid(getPctid(pctidSlider.getValue())); + + return hf; + } + + private void setSliderMaxMin() { + pctidSlider.setMinimum(getMinSliderPctid(hitFiltData.getMinPctid())); + pctidSlider.setMaximum(getMaxSliderPctid(hitFiltData.getMaxPctid())); + + pctidSlider.setEnabled(true); + } + // drawingpanel.FilterHandler + public void closeFilter() { + if (isShowing()) { + cancelAction(); + setVisible(false); + } + } + public void showPopup(MouseEvent e) { + popupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + public boolean canShow() {return mapper!=null;} + + /************************************************************************/ + private class FilterListener implements ActionListener, ChangeListener { + private FilterListener() { } + public void actionPerformed(ActionEvent event) { + Object src = event.getSource(); + + if (src == okButton) { // changed already made + okAction(); + setVisible(false); + } + else if (src == cancelButton) { + cancelAction(); + setVisible(false); + } + else if (src == defaultButton) { + setDefault(); + } + else if (src == blockOnlyText) { + int n = Utilities.getInt(blockOnlyText.getText()); + if (n>1) blockOnlyCheck.setSelected(true); + } + // set filter with popup value + else if (src == hBlockPopRadio) hBlockRadio.setSelected(hBlockPopRadio.isSelected()); + else if (src == hCsetPopRadio) hCsetRadio.setSelected(hCsetPopRadio.isSelected()); + else if (src == hGene2PopRadio) hGene2Radio.setSelected(hGene2PopRadio.isSelected()); + else if (src == hGene1PopRadio) hGene1Radio.setSelected(hGene1PopRadio.isSelected()); + else if (src == hGene0PopRadio) hGene0Radio.setSelected(hGene0PopRadio.isSelected()); + else if (src == hNonePopRadio) hNoneRadio.setSelected(hNonePopRadio.isSelected()); + else if (src == hPopupPopCheck) hPopupCheck.setSelected(hPopupPopCheck.isSelected()); + else if (src == sAllPopCheck) sAllCheck.setSelected(sAllPopCheck.isSelected()); + refresh(); + } + + public void stateChanged(ChangeEvent event) { + if (mapper==null) return; + + double pctid = hitFiltData.getPctid(); + + if (hasSize(pctidSlider)) { + int xpctid = pctidSlider.getValue(); + + if (xpctid != (int) pctid) { + String pid = getPctidString(xpctid); + pctidText.setText(pid); + setSliderMaxMin(); + refresh(); + } + } + } + } // end listener + + // called when popup become visible + class MyPopupMenuListener implements PopupMenuListener { + public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {} + + public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {} + + public void popupMenuWillBecomeVisible(PopupMenuEvent event) { + setInit(hitFiltData); + + hBlockPopRadio.setSelected(hitFiltData.isHiBlock()); + hCsetPopRadio.setSelected(hitFiltData.isHiCset()); + hGene2PopRadio.setSelected(hitFiltData.isHi2Gene()); + hGene1PopRadio.setSelected(hitFiltData.isHi1Gene()); + hGene0PopRadio.setSelected(hitFiltData.isHi0Gene()); + hNonePopRadio.setSelected(hitFiltData.isHiNone()); + hPopupPopCheck.setSelected(hitFiltData.isHiPopup()); + sAllPopCheck.setSelected(hitFiltData.isAll()); + } + } // end popup listener + private int getSliderPctid(double pctid) {return (int)Math.round(pctid);} + private boolean hasSize(JSlider slider) {return slider.getMaximum() > slider.getMinimum();} + private double getPctid(int slider) {return (double)slider;} + private int getMinSliderPctid(double min) {return (int)Math.floor(min);} + private int getMaxSliderPctid(double max) {return (int)Math.ceil(max);} + private String getPctidString(int slider) {return slider + ""%"";} +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/mapper/HitData.java",".java","11171","304","package symap.mapper; + +import java.util.Comparator; + +import symap.Globals; +import symap.sequence.Sequence; +import util.ErrorReport; +import util.Utilities; + +/** + * Represents one Clustered Hit. + * SeqHits has the set, plus a DrawHit that is 1-to-1 with a HitData + */ +public class HitData { + protected static int cntMerge=0, cntTotal=0, cntMergeSH=0, cntTotalSH=0; + private Mapper mapper; // for way back to other data + private int idx; + private int hitnum; + private byte pctid, pctsim; + private int covScore; + private int nMerge; + private int geneOlp = -1; + private boolean isPosOrient1, isPosOrient2, isBlkInv; + protected int annot1_idx, annot2_idx; // pseudo changed to zero in MapperPool + private String query_seq, target_seq; // coordinates of subhits + + protected int start1, end1, mid1, start2, end2, mid2; // 1=q, 2=t; mid for paintComponent + protected String qMergeSH, tMergeSH; // merged subhits for faster drawing in SeqHits.DrawHit + + private int collinearSet, blocknum; + + private boolean isBlock, isCollinear; // set on init + + private boolean isPopup=false; // set when popup; + private boolean isHighG2xN=false, isForceG2xN=false; // set on seqFilter 3-track ref only; force is filtered but must be shown + + protected String hitGeneTag; // g(gene_overlap) or htype (EE) ; gNbN see MapperPool; + private String hitTag; + + // MapperPool.setSeqHitData populates, puts in array for SeqHits, where each HitData is associated with a DrawHit + protected HitData(Mapper mapper, int id, int hitnum, + double pctid, int pctsim, int nMerge, int covScore, String htype, int overlap, + int annot1_idx, int annot2_idx, + String strand, int start1, int end1, int start2, int end2, String query_seq, String target_seq, + int runnum, int runsize, int block, double corr) + { + this.mapper = mapper; + this.idx = id; + this.hitnum = hitnum; + + this.pctid = (byte)pctid; + this.pctsim = (byte) pctsim; + this.nMerge = nMerge; + this.covScore = covScore; + this.geneOlp = overlap; + + this.annot1_idx = annot1_idx; // even if not annotated are number, this will still be 0 if not annotated + this.annot2_idx = annot2_idx; + + if (strand.length() >= 3) { + this.isPosOrient1 = (strand.charAt(0) == '+'); + this.isPosOrient2 = (strand.charAt(2) == '+'); + } + else Globals.dprt(""HitData: Invalid strand value '""+strand+""' for hit id=""+id); + + this.start1 = start1; + this.end1 = end1; + this.start2 = start2; + this.end2 = end2; + this.mid1 = (start1+end1) >>1; + this.mid2 = (start2+end2) >>1; + + this.query_seq = query_seq; // start1: end1, ... + this.target_seq = target_seq; // start2: end2 + qMergeSH = calcMergeHits(query_seq, start1, end1); + tMergeSH = calcMergeHits(target_seq, start2, end2); + + this.collinearSet = runnum; + this.isCollinear = (collinearSet==0) ? false : true; + + this.blocknum = block; + this.isBlock = (blocknum>0) ? true : false; + this.isBlkInv = (corr<0); + + String gg = (htype.equals(""0"") || htype.equals("""")) ? ("" g"" + geneOlp) : ("" "" +htype); + String iv = (corr<0) ? "" Inv "" : "" ""; // Strand may be == when Inv + + String co = (runsize>0 && runnum>0) ? ("" c"" + runsize + ""."" + runnum) : """"; + hitTag = ""Hit #"" + hitnum + gg + "" Block #"" + block + iv + co; + + hitGeneTag = ""Hit #"" + hitnum + "" Block #"" + block; + } + /* The hits overlap, so merge the overlapping ones; similar to the one in anchor2.HitPair and SeqHits + * For similar sequences, there can be many merges */ + protected String calcMergeHits(String subHits, int start, int end) { + try { + if (subHits == null || subHits.length() == 0) return """"; // 1 sh; uses start,end + + String [] subseq = subHits.split("",""); + int newSH=0, origSH=subseq.length; + + int [] shstart = new int [origSH]; + int [] shend = new int [origSH]; + + for (int k = 0; k < origSH; k++) {// go through hits and either create a new one or merge + String[] pos = subseq[k].split("":""); + int s = Integer.parseInt(pos[0]); + int e = Integer.parseInt(pos[1]); + + boolean found=false; + for (int i=0; ishend[i]) shend[i] = e; + if (s1 + + cntMerge++; cntMergeSH += (origSH-newSH); + + StringBuffer sb = new StringBuffer(); + for (int i=0; i>1; } + + public int getStart1() { return start1; } + public int getEnd1() { return end1; } + public int getStart2() { return start2; } + public int getEnd2() { return end2; } + + protected int getStart1(boolean swap) { return (swap ? start2 : start1); } + protected int getEnd1(boolean swap) { return (swap ? end2 : end1); } + protected int getStart2(boolean swap) { return (swap ? start1 : start2); } + protected int getEnd2(boolean swap) { return (swap ? end1 : end2); } + + protected double getPctid() { return (double)pctid; } + protected String getTargetSeq() { return target_seq; } + protected String getQuerySeq() { return query_seq; } + + // for hit popup: the query and target seq have subhits, and are blank if just one hit; + protected String getQuerySubhits(){ + if (query_seq!=null && query_seq.length()>0) return query_seq; + return start1 + "":"" + end1; + } + protected String getTargetSubhits(){ + if (target_seq!=null && target_seq.length()>0) return target_seq; + return start2 + "":"" + end2; + } + protected String getMinorForGenePopup(boolean isQuery, int annotIdx) { + String d = (annotIdx!=annot1_idx && annotIdx!=annot2_idx) ? Globals.minorAnno : """"; + return d; + } + // for annotation popup; + // list of subhits -> coords for both sides; + protected String getHitCoordsForGenePopup(boolean isQuery, String tag) { + String tag1 = mapper.getGeneNum1(annot1_idx); + String tag2 = mapper.getGeneNum2(annot2_idx); + + if (tag!=null) { + if (isQuery) tag1 = tag; + else tag2 = tag; + } + int l = Math.max(tag1.length(), tag2.length()); + String fmt = ""%-"" + l + ""s"" + "" %s""; + + String msg1 = String.format(fmt, tag1, Utilities.coordsStr(isPosOrient1, start1, end1)); + String msg2 = String.format(fmt, tag2, Utilities.coordsStr(isPosOrient2, start2, end2)); + + String coords = isQuery ? (msg1+""\n"" + msg2) : (msg2+ ""\n""+ msg1); + return coords; + } + // Called from SeqHits.popupDesc (top of popup) and SeqHits.DrawHit (Hover) + protected String createHover(boolean isQuery) { + String msg = hitTag + ""\n""; + + String op = (nMerge>0) ? ""~"" : """"; + msg += ""Id="" + op + pctid + ""% ""; + msg += ""Sim=""+ op + pctsim + ""% ""; + msg += String.format(""Cov=%,dbp"", covScore); + + String L=""L "", R=""R ""; + String gn1 = ""#""+mapper.getGeneNum1(annot1_idx), gn2 = ""#""+mapper.getGeneNum2(annot2_idx); + String gn = isQuery ? (L + gn1+"" ""+R+ gn2) : (L +gn2+ "" ""+ R + gn1); + + String msg1 = Utilities.coordsStr(isPosOrient1, start1, end1); + String msg2 = Utilities.coordsStr(isPosOrient2, start2, end2); + + String coords = isQuery ? (L + msg1+""\n""+R+ msg2) : (L +msg2+ ""\n""+ R + msg1); + + return msg + ""\n\n"" + coords + ""\n\n"" + gn; // gn on end to be similar to popup + } + protected String createPopup(boolean isQuery) {// slightly different from createHover + String msg = hitTag + ""\n""; + + String op = (nMerge>0) ? ""~"" : """"; + msg += ""Id="" + op + pctid + ""% ""; + msg += ""Sim=""+ op + pctsim + ""% ""; + msg += String.format(""Cov=%,dbp "", covScore); + String n = (nMerge>0) ? ""#Subhits="" + nMerge + "" "" : ""#Subhit=1 ""; + msg += n; + + String L=""L "", R=""R ""; + String msg1 = Utilities.coordsStr(isPosOrient1, start1, end1); + String msg2 = Utilities.coordsStr(isPosOrient2, start2, end2); + + String coords = isQuery ? (L + msg1+""\n""+R+ msg2) : (L +msg2+ ""\n""+ R + msg1); + + return msg + ""\n\n"" + coords; + } + protected boolean isBlock() { return isBlock; } + protected boolean isCset() { return isCollinear; } + protected boolean isPopup() { return isPopup;} + public boolean is2Gene() { return (geneOlp==2); } + protected boolean is1Gene() { return (geneOlp==1); } + protected boolean is0Gene() { return (geneOlp==0); } + protected boolean isInv() { return isPosOrient1!=isPosOrient2;} // for TextShowInfo + protected boolean isBlkInv() { return isBlkInv;} // for SeqHits block# + + public void setIsPopup(boolean b) {// SeqHits, closeup.TextShowInfo + isPopup=b; + Sequence s1 = (Sequence) mapper.getTrack1();// highlight gene also + Sequence s2 = (Sequence) mapper.getTrack2(); + s1.setHighforHit(annot1_idx, annot2_idx, b); + s2.setHighforHit(annot1_idx, annot2_idx, b); + } + protected int getCollinearSet() {return collinearSet;} + + // for coloring hit line according to directions + protected String getOrients() { + String x = (isPosOrient1) ? ""+"" : ""-""; + String y = (isPosOrient2) ? ""+"" : ""-""; + return x+y; + } + + /* ***** g2xN methods ******** */ + protected boolean isHighG2xN() { return isHighG2xN;} + protected boolean isForceG2xN() { return isForceG2xN;} + + public void setHighForceG2xN(boolean b) {isHighG2xN = b; isForceG2xN=b;} + public void setForceG2xN(boolean b) {isForceG2xN=b;} + + public void setHighAnnoG2xN(boolean b) { // SeqPool.computeG2xn sets true, SeqHits.clearHighG2xN sets false + if (!b && !isHighG2xN) return; + + isHighG2xN = b; // highlights hit + + Sequence s1 = (Sequence) mapper.getTrack1(); + Sequence s2 = (Sequence) mapper.getTrack2(); + + s1.setAnnoG2xN(annot1_idx, annot2_idx, b); // highlights annotation for gene (either annot1 or annot2) + s2.setAnnoG2xN(annot1_idx, annot2_idx, b); + } + public void clearG2xN() { + if (isHighG2xN) setHighAnnoG2xN(false); + + isHighG2xN=isForceG2xN=false; + } + //////////////////////////////////////////// + + public boolean equals(Object obj) { + return (obj instanceof HitData && ((HitData)obj).idx == idx); + } + public static Comparator sortByStart2() { + return new Comparator() { + public int compare(HitData hd1, HitData hd2) { + int d = hd1.start2 - hd2.start2; + if (d == 0) d = hd1.end2 - hd2.end2; + return d; + } + }; + } + public String getName() { return ""Hit #"" + hitnum;} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/SumFrame.java",".java","29658","801","package symap.manager; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +import java.util.TreeSet; +import java.util.Vector; +import java.util.Arrays; +import java.sql.ResultSet; + +import database.DBconn2; +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Utilities; + +/********************************************************** + * Creates the Summary window from the Summary Button on the main panel + * The Summary is of the alignment from two different sequence projects + * CAS575 correct for self-synteny; remove old createBlock and createAnchor + */ + +public class SumFrame extends JDialog implements ActionListener { + private static final long serialVersionUID = 246739533083628235L; + private boolean bArgRedo=Globals.bRedoSum; // -s regenerate summary on display; + private boolean bRedo=false; + + private JButton btnHelp = null, btnOK = null; + private int pairIdx=0, proj1Idx=0, proj2Idx=0; + private int nHits=0; + private Mpair mp; + private DBconn2 dbc2; + + private Proj proj1=null, proj2=null; // contains idx and lengths of groups + private boolean isSelf=false; + + // Called from DoAlignSynPair to create + public SumFrame(DBconn2 dbc2, Mpair mp) { + this.mp = mp; + this.dbc2 = dbc2; + bRedo=true; // expects the summary to be regenerated if still exists + createSummary(false); + } + // do not need to regenerate summary with 'Number Pseudo' or NumHits, + // just add to end; keep current version as not major update; CAS579; CAS579c add action + public SumFrame(DBconn2 dbc2, Mpair mp, String action) { + this.mp = mp; + this.dbc2 = dbc2; + + try { + ResultSet rs = dbc2.executeQuery(""select summary from pairs where idx=""+ mp.getPairIdx()); + String sum = (rs.next()) ? rs.getString(1) : null; + if (sum==null) { + createSummary(true); + return; + } + if (sum.contains(action)) return; + sum += ""\n "" + action + "" "" + Utilities.getDateOnly(); // CAS579c add date + dbc2.executeUpdate(""update pairs set summary='"" + sum + ""' where idx="" + mp.getPairIdx()); + } + catch (Exception e) {ErrorReport.print(""Updating summary for pseudo""); } + } + // Called from the project manager to display + public SumFrame(String title, DBconn2 dbc2, Mpair mp, boolean isReadOnly) { + super(); + try { + setModal(false); + setTitle(title); + setResizable(true); + + this.mp = mp; + this.dbc2 = dbc2; + + String theInfo = createSummary(isReadOnly); + JTextArea messageArea = new JTextArea(theInfo); + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.PLAIN, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + btnOK = Jcomp.createButton(Jcomp.ok, ""Close window""); + btnOK.addActionListener(this); + btnHelp = Jcomp.createButton(""Explain"", ""Popup with explanation of statistics""); + btnHelp.addActionListener(this); + JPanel buttonPanel = new JPanel(); + + buttonPanel.add(btnHelp); buttonPanel.add(Box.createHorizontalStrut(20)); + buttonPanel.add(btnOK); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(sPane,BorderLayout.CENTER); + getContentPane().add(buttonPanel,BorderLayout.SOUTH); + pack(); + + setLocationRelativeTo(null); + setVisible(true); + } + catch(Exception e){ErrorReport.print(e, ""Create summary"");} + } + public void actionPerformed(ActionEvent e) { + if (e.getSource() == btnOK) setVisible(false); + else if (e.getSource() == btnHelp) util.Jhtml.showHTMLPage(null, ""Summary Help"", ""/html/SummaryHelp.html""); + } + /******************************************************************************* + * Create summary + ******************************************************************************/ + private String createSummary(boolean isReadOnly) { + try { + pairIdx = mp.getPairIdx(); + proj1Idx = mp.getProj1Idx(); + proj2Idx = mp.getProj2Idx(); + isSelf = proj1Idx==proj2Idx; + + ResultSet rs; + if (dbc2.tableColumnExists(""pairs"", ""summary"")) { // exist if called from Summary popup + rs = dbc2.executeQuery(""select summary from pairs where idx=""+ pairIdx); + String sum = (rs.next()) ? rs.getString(1) : null; + if (sum!=null && sum.length()>20 && !bArgRedo && !bRedo) return sum; + } + + proj1 = makeProjObj(proj1Idx); + proj2 = makeProjObj(proj2Idx); + + proj1.name = mp.getProj1().getDisplayName(); + proj2.name = mp.getProj2().getDisplayName(); + if (isReadOnly) System.out.println(""Create Summary for display...""); + else System.out.println(""Creating Summary for save to database... ""); + + String alignDate = null, syver=null, allParams=null; // CAS579c none were null, but was checking for null + rs = dbc2.executeQuery(""select aligndate, params, syver from pairs where idx="" + pairIdx); + if (rs.next()) { + alignDate = rs.getString(1); + allParams = rs.getString(2); // these are the params that were used for align + syver = rs.getString(3); + } + rs.close(); + + if (allParams==null) { // if MUMmer fails... + allParams = ""Align Unknown""; + } + else { + String [] x = allParams.split(""\n""); + allParams = """"; + for (int i=0; i0) { + sq = ""select count(distinct ph.idx) from pseudo_hits as ph "" + + ""join pseudo_hits_annot as pha on pha.hit_idx = ph.idx "" + + ""join pseudo_annot as pa on pa.idx = pha.annot_idx "" + + ""where pa.type='gene' and pair_idx="" + pairIdx; + + if (isSelf) sq += "" and ((grp1_idx>grp2_idx and refidx=0) or (grp1_idx=grp2_idx and start1>start2))""; + + hitGene1 = dbc2.executeInteger(sq + "" and ph.annot1_idx=pha.annot_idx""); + hitGene2 = dbc2.executeInteger(sq + "" and ph.annot2_idx=pha.annot_idx""); + } + else {// pseudos can have gene_overlap=1, so cannot this simpler query + sq = ""select count(distinct idx) from pseudo_hits where gene_overlap>0 and pair_idx="" + pairIdx; + + if (isSelf) sq += "" and ((grp1_idx>grp2_idx and refidx=0) or (grp1_idx=grp2_idx and start1>start2))""; + + hitGene1 = dbc2.executeInteger(sq + "" and annot1_idx>0""); + hitGene2 = dbc2.executeInteger(sq + "" and annot2_idx>0""); + } + + int hit2Gene = dbc2.executeInteger(""select count(*) from pseudo_hits where gene_overlap=2 and pair_idx="" + pairIdx); + int hit1Gene = dbc2.executeInteger(""select count(*) from pseudo_hits where gene_overlap=1 and pair_idx="" + pairIdx); + int hit0Gene = dbc2.executeInteger(""select count(*) from pseudo_hits where gene_overlap=0 and pair_idx="" + pairIdx); + + if (isSelf) {hit2Gene /=2; hit1Gene /= 2; hit0Gene /=2;} + +/* Coverage */ + ResultSet rs; + int totSh=0, totRev=0; + + /* Loop1: proj1 chrN **/ + long chCov1=0, shCov1=0; // Cov CH (Sh) + int cnt11=0, cnt12=0, cnt13=0, cnt14=0; // SH <100, etc + + for (int g1=0; g10) chCov1++; } + for (byte a : subArr) {if (a>0) shCov1++;} + clustArr=subArr=null; + } + if (isSelf) { + cnt11 /= 2; cnt12 /= 2; cnt13 /= 2; cnt14 /= 2; + chCov1 /= 2; shCov1 /= 2; + totRev /= 2; totSh /= 2; + } + /* Loop2: proj2 chrN **/ + long chCov2=0, shCov2=0; // got overflow on human self + int cnt21=0, cnt22=0, cnt23=0, cnt24=0; + for (int g2=0; g20) chCov2++;} + for (byte a : subArr) {if (a>0) shCov2++;} + clustArr=subArr=null; + } + if (isSelf) { + cnt21 /= 2; cnt22 /= 2; cnt23 /= 2; cnt24 /= 2; + chCov2 /= 2; shCov2 /=2; + } + String pGNwCH1 = pct((double)gene1Hit, (double) proj1.nGenes); + String pGNwCH2 = pct((double)gene2Hit, (double) proj2.nGenes); + String pCHwGN1 = pct((double)hitGene1, (double) nHits); + String pCHwGN2 = pct((double)hitGene2, (double) nHits); + + String pchCov1 = pct((double)chCov1, (double)proj1.genomeLen); + String pchCov2 = pct((double)chCov2, (double)proj2.genomeLen); + String pshCov1 = pct((double)shCov1, (double)proj1.genomeLen); + String pshCov2 = pct((double)shCov2, (double)proj2.genomeLen); + + int nInBlock = dbc2.executeInteger(""select count(*) "" + + ""from pseudo_hits as h "" + + ""join pseudo_block_hits as pbh on pbh.hit_idx=h.idx "" + + ""where pair_idx="" + pairIdx); // Query: block hits/all hits + if (isSelf) nInBlock /= 2; + String pInBlock = pct((double)nInBlock, (double)nHits); + + // make cluster only table; same for both sides + String [] field1 = {""#Clusters"", ""#Rev"", ""CHnBlock"", ""#CH"", ""g2"", ""g1"", ""g0"", "" "", ""#SubHits"", ""AvgNum""}; + int nCol1 = field1.length; + int [] justify1 = new int [nCol1]; + for (int i=0; i5kb""}; + int nCol = fields.length; + int [] justify = new int [nCol]; + justify[0]=1; + for (int i=1; i0) bcov1++; if (a>1) bdcov1++;} + arrB=null; + } + /* Proj2 **/ + for (int g2=0; g20) bcov2++; if (a>1) bdcov2++;} + arrB=null; + } + if (isSelf) { + nblks /= 2; ninv /= 2; bcov1 /= 2; bdcov1 /= 2; + b11 /= 2; b12 /= 2; b13 /= 2; b14 /= 2; + + bcov2 /= 2; bdcov2 /= 2; + b21 /= 2; b22 /= 2; b23 /= 2; b24 /= 2; + } + + String sbCov1 = pct((double)bcov1, (double)proj1.genomeLen); + String sbCov2 = pct((double)bcov2, (double)proj2.genomeLen); + String sb2xCov1 = pct((double)bdcov1,(double)proj1.genomeLen); + String sb2xCov2 = pct((double)bdcov2,(double)proj2.genomeLen); + + // make block table + String [] fields = {"""",""#Blocks"", ""Inv"",""GNwCHB"", "" Cover SB (2x)"",""<100kb"",""100kb-1Mb"",""1Mb-10Mb"","">10Mb""}; + int nCol= fields.length; + int [] justify = new int [nCol]; + justify[0]=1; + for (int i=1; i0 and pair_idx="" + pairIdx); + if (nSetsHits==0) return ""Collinear \n None\n""; + + int n2=0, n3=0, n4=0, n5=0, n6=0, n7=0, n8=0, n9=0, n14=0,n19=0,n20=0, nGenes=0; + + TreeSet setMap = new TreeSet (); + + String sq = ""select grp1_idx, grp2_idx, runnum, runsize from pseudo_hits where runnum>0 and pair_idx="" + pairIdx; + if (isSelf) { + sq += "" and ((grp1_idx>grp2_idx and refidx=0) or (grp1_idx=grp2_idx and start1>start2))""; + } + ResultSet rs = dbc2.executeQuery(sq); + while (rs.next()) { + int grp1 = rs.getInt(1); + int grp2 = rs.getInt(2); + int num = rs.getInt(3); + int sz = rs.getInt(4); + + String key = grp1+"".""+grp2+"".""+num; + if (setMap.contains(key)) continue; + setMap.add(key); + + nGenes += sz; + if (sz==2) n2++; + else if (sz==3) n3++; + else if (sz==4) n4++; + else if (sz==5) n5++; + else if (sz==6) n6++; + else if (sz==7) n7++; + else if (sz==8) n8++; + else if (sz==9) n9++; + else if (sz<=14) n14++; + else if (sz<=19) n19++; + else n20++; + } + rs.close(); + + String [] fields = {""Sets"","" =2"","" =3"","" =4"", "" =5"", "" =6"", "" =7"", "" =8"", "" =9"", ""10-14"", ""15-19"", "" >=20"", ""#Genes""}; + int [] justify = new int[fields.length]; + for (int i=0; i=1000000000) { + d = d/1000000.0; + return String.format(""%,dM"", (int) d); + } + else if (len>=1000000) { + d = d/1000.0; + return String.format(""%,dk"", (int) d); + } + return String.format(""%,d"", len); + } + + private String pct(double t, double b) { + String ret; + if (b==0) ret = ""n/a""; + else if (t==0) ret = ""0%""; + else { + double x = ((double)t/(double)b)*100.0; + if (x<0) Globals.tprt(String.format(""%,d %,d %.3f"", (long)t, (long)b, x)); + ret = String.format(""%4.1f%s"", x, ""%""); + } + return String.format(""%5s"", ret); + } + + /********************************************************************** + * Mproject does not have group lengths + */ + private Proj makeProjObj(int projIdx) { + try { + Proj p = new Proj(); + ResultSet rs = dbc2.executeQuery(""select x.idx, p.length "" + + "" from xgroups as x join pseudos as p on x.idx=p.grp_idx where x.proj_idx="" + projIdx); + while (rs.next()) { + p.grpIdx.add(rs.getInt(1)); + p.grpLen.add(rs.getInt(2)); + p.genomeLen += rs.getLong(2); + } + p.nGrp = p.grpIdx.size(); + return p; + } + catch (Exception e) {ErrorReport.print(e, ""Making grp map""); return null;} + } + private class Proj { + String name; + long genomeLen=0; + int nGenes=0, nGrp=0; + Vector grpIdx = new Vector (); + Vector grpLen = new Vector (); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/Report.java",".java","21097","607","package symap.manager; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.sql.ResultSet; +import java.util.ArrayList; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; + +import database.DBconn2; +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Utilities; + +/************************************************************** + * Block report from Manager + * CAS575 remove species column and put species name over species specific columns + */ +public class Report extends JDialog { + private static final long serialVersionUID = 1L; + private final int GENE=1, ONLY=2, SUM=3; + private final int IGN=1, NUM=2, FLOAT=3, LFLOAT=4; + private final String CHR=""Chr"", CCB = ""C1.C2.B"", CC = ""C1.C2""; + private final int PCCcol = 2; + + private boolean isTSV=false, isHTML, isPop=false, isSp1=true, isSp2, useComb=true, isSelf=false, isSum=false; + private int cntHtmlRow=0; // to determine whether to have a Goto top at bottom + + private DBconn2 tdbc2 = null; + private Mpair mp; + private Mproject [] mProjs; + private String dname1, dname2; + + protected Report(DBconn2 tdbc2, Mproject [] mProjs, Mpair mp) { + this.tdbc2 = tdbc2; + this.mProjs = mProjs; + this.mp = mp; + dname1 = mProjs[0].getDisplayName(); + dname2 = mProjs[1].getDisplayName(); + + isSelf = dname1.equals(dname2); + + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setTitle(""Block Report""); + + mainPanel = Jcomp.createPagePanel(); + createPanel(); + createOutput(); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + add(mainPanel); + + pack(); + setModal(true); // nothing else can happen until ok,cancel + toFront(); + setResizable(false); + setLocationRelativeTo(null); + setVisible(true); + } + /*****************************************************************/ + private void createPanel() { + + JPanel radPanel = Jcomp.createPagePanel(); + radBlocksPlus = Jcomp.createRadio(""Blocks plus"", ""Download all blocks with extra block info""); + radBlocksGenes = Jcomp.createRadio(""Blocks with gene info"", ""Download all blocks with gene info""); + radBlocksSum = Jcomp.createRadio(""Blocks summary"", ""Download block summary by chromosome pair""); + + ButtonGroup ba = new ButtonGroup(); + ba.add(radBlocksGenes);ba.add(radBlocksPlus);ba.add(radBlocksSum); + radBlocksPlus.setSelected(true); + + radPanel.add(radBlocksPlus); radPanel.add(Box.createVerticalStrut(5)); + radPanel.add(radBlocksGenes); radPanel.add(Box.createVerticalStrut(5)); + radPanel.add(radBlocksSum); radPanel.add(Box.createVerticalStrut(5)); + + /// Species + JPanel spRow = Jcomp.createRowPanel(); + spRow.add(Jcomp.createLabel(""Reference "")); + radSpecies = new JRadioButton[mProjs.length]; + ButtonGroup bg = new ButtonGroup(); + + for (int i=0; i row = new ArrayList (6); + if (useComb) {row.add(CC); } + else {row.add(CHR+""1""); row.add(CHR+""2""); } + row.add(""#Blocks""); row.add(""#Hits""); + + if (outFH==null) report+=joinHead(row, """"); + else outFH.println(joinHead(row, """")); + + String savChr1="""", savChr2=""""; + int cntBlocks=0, sumHits=0, totBlks=0; + + ResultSet rs = tdbc2.executeQuery(mkSQL(SUM)); + while (rs.next()){ + String n1="""", n2=""""; + int nhits; + if (useComb) { + n1 = rs.getString(1); + nhits = rs.getInt(3); + } + else { + n1 = rs.getString(1); + n2 = rs.getString(2); + nhits = rs.getInt(4); + } + if (!n1.equals(savChr1) || !n2.equals(savChr2)) { + if (cntBlocks>0) { // create row and print + int i=0; + if (useComb) {row.set(i++, savChr1); } + else {row.set(i++, savChr1); row.set(i++, savChr2);} + row.set(i++, Integer.toString(cntBlocks)); row.set(i++, Integer.toString(sumHits)); + + if (outFH==null) report+=joinRow(row); + else outFH.println(joinRow(row)); + } + savChr1 = n1; savChr2 = n2; + cntBlocks=sumHits=0; + } + cntBlocks++; totBlks++; + sumHits += nhits; + } + if (cntBlocks>0) { + int i=0; + if (useComb) {row.set(i++, savChr1); } + else {row.set(i++, savChr1); row.set(i++, savChr2); } + row.set(i++, Integer.toString(cntBlocks)); row.set(i++, Integer.toString(sumHits)); + + if (outFH==null) report+=joinRow(row); + else outFH.println(joinRow(row)); + } + if (isPop) { + report += htmlTail(totBlks); + util.Jhtml.showHtmlPanel(null, (""Block Summary""), report); + } + else endFile(outFH, totBlks); + } + catch(Exception e) {ErrorReport.print(e, ""Generate blocks summary"");} + } + /*****************************************************************/ + private void mkBlocksPlus() { + try { + PrintWriter outFH = null; + String report = """"; + + if (isPop) report = htmlHead(); + else { + outFH = startFile(""blocksPlus""); + if (outFH==null) return; + if (isTSV) tsvHead(outFH); + } + + ArrayList rowHead = new ArrayList(); + + if (useComb) {rowHead.add(CCB);} // combined in sql + else {rowHead.add(CHR+""1""); rowHead.add(CHR+""2""); rowHead.add(""Block""); } + rowHead.add(""#Hits""); rowHead.add(""PearsonR""); + rowHead.add(""AvgGap1""); rowHead.add(""AvgGap2""); + rowHead.add(""Length1""); rowHead.add(""Length2""); rowHead.add(""Start1""); rowHead.add(""Start2""); + + if (isTSV) { // only written once + outFH.println(joinHead(rowHead, """")); + } + + int ncol = rowHead.size(), totBlks=0; + String saveChr="""", chr=""""; + ArrayList row = new ArrayList(rowHead.size()); + for (int i=0; i rowHead = new ArrayList(); + if (useComb) {rowHead.add(CCB); }// combined in sql + else {rowHead.add(CHR+""1""); rowHead.add(CHR+""2""); rowHead.add(""Block""); } + + rowHead.add(""#Hits""); rowHead.add(""PearsonR""); + rowHead.add(""Start1""); rowHead.add(""End1""); rowHead.add(""Start2""); rowHead.add(""End2""); + rowHead.add(""#Genes1""); rowHead.add(""%Genes1""); rowHead.add(""#Genes2""); rowHead.add(""%Genes2""); + + if (isTSV) { // does not write every X rows and C.C.B does not contain ref chr# + outFH.println(joinHead(rowHead, """")); + } + int ncol = rowHead.size(), totBlks=0; + String saveChr="""", chr; + ArrayList row = new ArrayList(rowHead.size()); + for (int i=0; i0 or b.avgGap2>0)""; // mirrored are zero for these values; see SyntenyMain.RWdb + + if (isSp1) sql += "" order by g1.name asc, g2.name asc, b.blocknum asc""; // name is chrName + else sql += "" order by g2.name asc, g1.name asc, b.start2 asc""; // blocks will be out of order; CAS575 + + if (which==SUM) return sql; // summary done + //////////////////////////// + // create type vector + if (useComb) typeArr.add(IGN); + else {typeArr.add(IGN);typeArr.add(IGN);typeArr.add(IGN);} // name, name, blocknum + + typeArr.add(NUM); typeArr.add(FLOAT); // score, corr + + if (which==ONLY) { + if (hasGap) { + typeArr.add(NUM); typeArr.add(NUM); // avgGap + } + else { + typeArr.add(LFLOAT); typeArr.add(LFLOAT); // AvgGap computed + } + typeArr.add(NUM); typeArr.add(NUM); typeArr.add(NUM); typeArr.add(NUM); // len, start + } + else { + typeArr.add(NUM); typeArr.add(NUM); typeArr.add(NUM); typeArr.add(NUM); // start,end,start,end + typeArr.add(NUM); typeArr.add(FLOAT); typeArr.add(NUM); typeArr.add(FLOAT); // #gene, %gene + } + + return sql; + } + /////////////////////////////////////////////////// + private PrintWriter startFile(String filename) { + try { + filename += (isTSV) ? "".tsv"" : "".html""; + String dirname = Globals.getExport(); + JFileChooser chooser = new JFileChooser(dirname); + chooser.setSelectedFile(new File(filename)); + + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return null; + if (chooser.getSelectedFile() == null) return null; + + exFileName = chooser.getSelectedFile().getAbsolutePath(); + if (isTSV) { + if(!exFileName.endsWith("".tsv"")) exFileName += "".tsv""; + } + else { + if(!exFileName.endsWith("".html"")) exFileName += "".html""; + } + File f = new File(exFileName); + if (f.exists()) { + if (!util.Popup.showConfirm2(""File exists"",""File '"" + exFileName + ""' exists.\nOverwrite?"")) return null; + f.delete(); + } + + f.createNewFile(); + PrintWriter out = new PrintWriter(new FileWriter(exFileName)); + + if (isHTML) out.println(htmlHead()); + + return out; + } + catch (Exception e) {ErrorReport.print(e, ""Getting file handle for report""); return null;} + } + private void endFile(PrintWriter out, int totBlk) { + if (btnHTML.isSelected()) out.println(htmlTail(totBlk)); + + out.close(); + + System.out.println(""Wrote to "" + exFileName); + } + //////////////////////////////////////////////////// + private String getNames() { + if (isSelf) return dname1 + "" to self""; + return dname1 + "" and "" + dname2; + } + private void tsvHead(PrintWriter outFH) { + outFH.println(""### SyMAP synteny blocks for "" + getNames()); + + if (!isSelf) { + String m = ""Sorted by ""; + m += (isSp1) ? dname1 : dname2; + outFH.println(""###"" + m + "" chromosomes""); + } + } + private String htmlHead() { + String title1 = dname1 + ""-"" + dname2 + "" Blocks""; // This is for file html + if (isSelf) title1 = dname1 + ""-self Blocks""; + + String title2 = (isSum) ? ""SyMAP Synteny Blocks for
"" + getNames() : ""SyMAP Synteny Blocks for "" + getNames(); + + String head = ""\n"" + + ""\n"" + + """" + title1 + ""\n"" + + ""\n"" + + ""\n"" + + ""\n"" + + ""\n"" + + ""
"" + title2 + """" + + ""

""; + return head; + } + private String htmlTail(int totBlks) { + String tail=""
""; + if (isSelf) tail += String.format(""

%,d Total Blocks below diagonal"", totBlks); + else tail += String.format(""

%,d Total Blocks"", totBlks); + if (cntHtmlRow>100 && !isPop) tail += ""

Go to top\n""; + tail += ""

\n""; + return tail; + } + ////////////////////////////////////////// + private String joinRow(ArrayList list) { + String delimiter = (isTSV) ? ""\t"" : """"; + String buffer = (isTSV) ? """" : """"; + + for (String x : list) { + if (!buffer.equals("""")) buffer += delimiter; + buffer += x; + } + cntHtmlRow++; + + return buffer; + } + + // Reference is indicated in chromosome column only + // HTML has species over species-specific columns, TSV does not + private String joinHead(ArrayList colList, String chr) { + String delim = (isTSV) ? ""\t"" : """"; + String buffer = (isTSV) ? """" : """"; + + for (String oCol : colList) { + String col = oCol.trim(); + if (!buffer.equals("""")) buffer += delim; + boolean isCol1 = col.endsWith(""1""); + + if (col.startsWith(CHR)) { // Chr Chr Block columns + if (isHTML && col.startsWith(CHR) && !chr.equals("""")) { + if (isSp1 && isCol1) { + col = chr; + if (Utilities.getInt(chr) != -1) col = CHR + col; + } + else if (isSp2 && !isCol1) { + col = chr; + if (Utilities.getInt(chr) != -1) col = CHR + col; + } + else col = CHR + ""X""; + } + if ((isSp1 && isCol1) || (isSp2 && !isCol1)) { // add ref info + if (isTSV) col = col.toUpperCase(); + else col = """" + col + """"; + } + } + else if (col.equals(CCB) || col.equals(CC)) { // C.C.B one column + if (isHTML) { + if (col.equals(CCB)) { + if (isSp1) col = """" + chr + "".Cx.B""; + else col = ""Cx."" + chr + "".B""; + } + else { // Summary + if (isSp1) col = ""C1.C2""; + else col = ""C1.C2""; + } + } + else { //TSV has no ref info + if (isSp1) col = ""C1.c2.B""; + else col = ""c1.C2.B""; + } + } + else if (col.endsWith(""1"") || col.endsWith(""2"")) { + if(isHTML) { + String name = (isCol1) ? dname1 : dname2; + col = name+""
""+col; + } + } + if (isPop) buffer += """" + col + """"; // popup does not show lightgrey + else buffer += col; + } + cntHtmlRow++; + return buffer; + } + + private String df(int i, double d) { // Excel removes trailing zeros and leading + + String x = String.format(""%.3f"", d); + if (i==PCCcol && !x.startsWith(""-"")) x = ""+"" + x; + return x; + } + /********************************************************************/ + private String exFileName=""""; + private ArrayList typeArr = new ArrayList (); + private JPanel mainPanel; + private JCheckBox chkComb = null; + private JRadioButton [] radSpecies=null; + private JRadioButton radBlocksGenes, radBlocksPlus, radBlocksSum; + + private JRadioButton btnHTML, btnTSV, btnPop; + private JButton btnOK=null, btnCancel=null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/ProjParams.java",".java","30260","868","package symap.manager; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSeparator; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableColumn; + +import backend.Constants; +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Jhtml; +import util.Popup; +import util.FileDir; + +/******************************************* + * Displays the project parameter window and saves them to file + * This goes with Mproject. + */ +public class ProjParams extends JDialog { + private static final long serialVersionUID = -8007681805846455592L; + static public String lastSeqDir=null; + static protected String catUncat = ""Uncategorized""; // puts this as last if there are no occurrences + + private final int abbrevLen = Globals.abbrevLen; + private final int INITIAL_WIDTH = 610, INITIAL_HEIGHT = 660; + + private final String displayHead = ""Display""; + private final String loadProjectHead = ""Load project""; + private final String loadAnnoHead = ""Load annotation""; + + private int idxGrpPrefix=0; + private Mproject mProj; + private Vector mProjVec; + private String [] catArr; + private Pattern pat = Pattern.compile(""^[a-zA-Z0-9_\\.\\-]+$""); // category, display name, abbrev + private String patMsg = ""\nEntry can only contain letters, digit, '-', '_', '.'""; + + public ProjParams(Frame parentFrame, Mproject mProj, + Vector projVec, String [] catArr, boolean isLoaded, boolean existAlign) { + + super(parentFrame, Constants.seqDataDir + mProj.getDBName() + ""/params file""); // title + + this.mProj = mProj; + this.mProjVec = projVec; + this.catArr = catArr; + + theDBName = mProj.getDBName(); + savDname = mProj.getDisplayName(); + savAbbrev = mProj.getdbAbbrev(); + + bIsLoaded = isLoaded; + bExistAlign = existAlign; + + getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); + getContentPane().setBackground(Color.WHITE); + + theListener = new CaretListener() { + public void caretUpdate(CaretEvent arg0) {} + }; + createMainPanel(); + setFieldsFromProj(); + + setInitValues(); // Save initial values to see if they change + + setSize(INITIAL_WIDTH, INITIAL_HEIGHT); + setMinimumSize(new Dimension(INITIAL_WIDTH, INITIAL_HEIGHT)); + + setModal(true); + + setLocationRelativeTo(parentFrame); + } + public boolean wasSave() {return bWasSave;} // ManagerFrame.doReloadParams, doSetParamsNotLoaded + + private ProjParams getInstance() { return this; } + + /******************************************************* + * If any parameters are changed, change also in manager.Mproject + * NOTE: The descriptions, etc are in Mproject + */ + private void createMainPanel() { + int startAnno=0, startLoad=0, i=0; + boolean bReload=true, bReAlign=true; + + theFields = new Field[11]; // If change #fields, change! + theFields[i++] = new Field(mProj.sCategory, catArr, 1, !bReload, !bReAlign, true);// true -> add text field + + theFields[i++] = new Field(mProj.sDisplay, 1, !bReload, !bReAlign); + theFields[i++] = new Field(mProj.sAbbrev, 1, !bReload, !bReAlign); + theFields[i++] = new Field(mProj.sGrpType, 1, !bReload, !bReAlign); + theFields[i++] = new Field(mProj.sDesc, 2, !bReload, !bReAlign); // 2 is multiText + theFields[i++] = new Field(mProj.sANkeyCnt, 1, !bReload, !bReAlign); + + startLoad = i-1; + idxGrpPrefix = i; // used for saveGrpPrefix special message + theFields[i++] = new Field(mProj.lGrpPrefix, 1, !bReload, !bReAlign); + theFields[i++] = new Field(mProj.lMinLen, 1, bReload, bReAlign); + theFields[i++] = new Field(mProj.lSeqFile, bReload, bReAlign, false); + + startAnno=i-1; + theFields[i++] = new Field(mProj.lANkeyword, 1, bReload, !bReAlign); + theFields[i++] = new Field(mProj.lAnnoFile, bReload, !bReAlign, false); + + JPanel fieldPanel = Jcomp.createPagePanel(); + fieldPanel.add(Jcomp.createHtmlLabel(displayHead, ""Parameters that can be changed at any time"")); + + for(int x=0; x + } + else if (x==startLoad) { + fieldPanel.add(Box.createVerticalStrut(5)); + fieldPanel.add(new JSeparator()); + fieldPanel.add(Box.createVerticalStrut(5)); + fieldPanel.add(Jcomp.createHtmlLabel(loadProjectHead, ""Parameters changed for Load Project"")); + } + } + + JPanel mainPanel = Jcomp.createPagePanel(); + + mainPanel.add(fieldPanel); + mainPanel.add(Box.createVerticalStrut(10)); + + JPanel buttons = createButtonPanel(); + mainPanel.add(buttons); + + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setMaximumSize(fieldPanel.getPreferredSize()); + mainPanel.setAlignmentX(Component.CENTER_ALIGNMENT); + + getContentPane().add(mainPanel); + } + + /******************************************************************/ + private JPanel createButtonPanel() { + btnSave = Jcomp.createButton(""Save"", ""Save parameters to file""); + btnSave.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + bWasSave=true; + save(); + } + }); + btnCancel = Jcomp.createButton(""Cancel"", ""Exit window without saving any changes""); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bWasSave = false; + closeDialog(); + } + }); + + JButton btnInfo = Jcomp.createIconButton(""/images/info.png"", ""Quick Help"" ); + btnInfo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + popupHelp(); + } + }); + + JButton btnHelp = Jhtml.createHelpIconSysSm(Jhtml.SYS_HELP_URL, Jhtml.param1); + + JPanel buttonPanel = Jcomp.createRowPanel(); + + buttonPanel.add(btnSave); buttonPanel.add(Box.createHorizontalStrut(10)); + buttonPanel.add(btnCancel); buttonPanel.add(Box.createHorizontalStrut(20)); + buttonPanel.add(btnHelp); buttonPanel.add(Box.createHorizontalStrut(10)); + buttonPanel.add(btnInfo); + + buttonPanel.setBackground(Color.WHITE); + buttonPanel.setMaximumSize(buttonPanel.getPreferredSize()); + buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + JPanel row = Jcomp.createRowPanel(); + row.add(Box.createHorizontalGlue()); + row.add(buttonPanel); + row.add(Box.createHorizontalGlue()); + + return row; + } + + /********************************************************************** + * Get/Set fields + ***************************************************************/ + + private void setFieldsFromProj() { + HashMap pMap = mProj.getParams(); + for (String label : pMap.keySet()) { + setField(label, pMap.get(label)); + } + } + private boolean setField(String fieldName, String fieldValue) { + for (int x=0; x12 && !val.equals(savDname)) { + String xmsg = ""Display name '"" + val + ""' is greater than 12 characters.\n"" + + ""This is allowed, but is not recommended as it causes crowded displays.\n"" + + ""\nTip: Use Description for full information about the species.""; + if (!util.Popup.showContinue(""Display name"",xmsg)) return false; + savDname = val; + } + if (val.length() == 0) msg = lab + "" must have a value.""; + else { + Matcher m = pat.matcher(val); + if (!m.matches()) msg = lab + "" '"" + val + ""' is illegal."" + patMsg; + } + if (msg==null) { + String dir = mProj.getDBName(); + for (Mproject mp : mProjVec) {// works if check directory name, which can't change; CAS578 + if (!mp.getDBName().equalsIgnoreCase(dir) && val.equalsIgnoreCase(mp.getDisplayName())) { + msg = ""The display name '"" + val + ""' has been used by project: \n""; + String desc = (mp.getdbDesc().length()<50) ? mp.getdbDesc() : mp.getdbDesc().subSequence(0,48) + ""...""; + msg += String.format("" %-12s: %s\n %-12s: %s\n %-12s: %s\n %-12s: %s\n"", + ""Directory"", mp.getDBName(), ""Display"", mp.getDisplayName(), + ""Description"", desc, ""Abbreviation"", mp.getdbAbbrev()); + msg += ""\nDuplicate display names are not allows (these are case-insenitive).""; + break; + } + } + } + } + else if (index == mProj.sAbbrev) { + if (val.length()>abbrevLen) { + msg = lab + "" must be <= "" + abbrevLen + "" characters. Value '"" + val + ""' is "" + val.length() + "".""; + } + else { + Matcher m = pat.matcher(val); + if (!m.matches()) msg = lab + "" '"" + val + ""' is illegal."" + patMsg; + } + // since this is a warning, do not want to keep checking, so only check if changed + if (msg==null && !val.equals(savAbbrev)) { // works if check directory name, which can't change; CAS578 + String dir = mProj.getDBName(); + for (Mproject mp : mProjVec) { // also checked in QueryFrame + if (!mp.getDBName().equalsIgnoreCase(dir) && val.equalsIgnoreCase(mp.getdbAbbrev())) { + msg = ""The abbreviation '"" + val + ""' has been used by project: \n""; + msg += String.format("" %-12s: %s\n %-12s: %s\n %-12s: %s\n %-12s: %s\n"", + ""Directory"", mp.getDBName(), ""Display"", mp.getDisplayName(), + ""Category"", mp.getdbCat(), ""Abbreviation"", mp.getdbAbbrev()); + msg += ""\nDuplicate abbreviations are allowed, \n"" + + ""but Queries will not work between two projects with the same abbreviation.""; + util.Popup.showMonoWarning(this, msg); + msg=null; + break; + } + } + savAbbrev = val; + } + } + else if (index == mProj.sCategory) { + val = val.trim(); // getValue gets the text or drop-down value + Matcher m = pat.matcher(val); + if (!m.matches()) msg = lab + "" '"" + val + ""' is illegal."" + patMsg; + } + else if (index == mProj.sGrpType) { + if (val.length() == 0) msg = lab + "" must have a value.""; + } + else if (index == mProj.sDesc) { + if (!val.isEmpty() && val.contains(""/"") || val.contains(""#"") || val.contains(""\"""")) + msg = ""Description cannot contains backslash, quotes or #""; + } + else if (index == mProj.lMinLen) { + msg = checkInt(lab, val); + } + else if (index == mProj.sANkeyCnt) { + msg = checkInt(lab, val); + } + + // only shows the first warning - returns for user to fix, then test again + if (msg!=null) { + util.Popup.showMonoError(this, msg); + return false; + } + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Checking project parameters""); return false;} + } + private String checkInt(String lab, String ix) { + try { + if (ix.contains("","")) ix = ix.replace("","", """"); + int x = Integer.parseInt(ix); + if (x<0) return lab + "" must be >0.""; + return null; + } + catch (Exception e) {} + + try { + long x = Long.parseLong(ix); + return lab + "" value '"" + x + ""' is too large, maximum is "" + Integer.MAX_VALUE ; + } + catch (Exception e) {return lab + "" value '"" + ix + ""' is not an integer."";} + } + /** Check parameters for change; note that bExistAlign does not mean with project to be aligned with**/ + private boolean saveIsRequired() { + try { + if (!bIsLoaded) return true; // write to file only + + for(int x=0; x/params is created anyway for the parameters + */ + private void writeParamsFile() { + String dir = Constants.seqDataDir + theDBName; + FileDir.checkCreateDir(dir, true); + + File pfile = new File(dir,Constants.paramsFile); + if (!pfile.exists()) // should not happen here because written on startup in Mproject + System.out.println(""Create parameter file "" + dir + Constants.paramsFile); + + try { + PrintWriter out = new PrintWriter(pfile); + + out.println(""# Directory "" + theDBName + "" project parameter file""); + out.println(""# Note: changes MUST be made in SyMAP parameter window""); + out.println(""#""); + + for(int x=0; x 0) { + String v = val.replace('\n', ' '); + v = v.replace(""\"""", "" ""); + v = v.replace(""\'"", "" ""); + v = v.trim(); + out.println(label + "" = "" + v); + } + else { + out.println(label + "" = ""); // save empty ones too + } + } + out.close(); + } catch(Exception e) {ErrorReport.print(e, ""Creating params file"");} + } + + private void closeDialog() { + dispose(); + } + + private void popupHelp() { + String msg = ""Display: These parameters can be changed at anytime.\n\n""; + msg += ""Load Project: Use xToSymap to format your files for input into Symap.\n\n"" + + + "" If your sequences are all chromosomes, and the '>' line starts with 'Chr',\n"" + + "" enter that for 'Group prefix'. Otherwise, read the 'Load Project' section\n"" + + "" of 'Parameters and Interface' on-line document to determine how to set\n"" + + "" the 'Group Prefix' and 'Minimum Length'.\n\n"" + + +""View: Select this link for the Project Manager to check the results of the load.\n"" + + "" MUMmer can take a long time to run, so you want to have the input sequences\n"" + + "" correct before running it.""; + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + /*************************************************************** + * Each parameter has a field object + ************************************************************/ + public class Field extends JPanel{ + private static final long serialVersionUID = -6643140570421332451L; + + private static final int MODE_TEXT = 0, MODE_COMBO = 1, MODE_MULTI = 2, MODE_FILE = 3; + + private static final int LABEL_WIDTH = 150; + private static final int FIELD_LEN = 10; + + //Used for a Add file/directory + private Field(int index, boolean needsReload, boolean needsRealign, boolean b) { + this.index = index; + String label = mProj.getLab(index); + String desc = mProj.getDesc(index); // was getLab CAS578 + + bdoReload = needsReload; + bdoRealign = needsRealign; + + nMode = MODE_FILE; + + theComp = new FileTable(b); + theLabel = Jcomp.createLabel(label, desc); + + setLayout(); + } + // Used for plain text properties + private Field(int index, int numLines, boolean needsReload, boolean needsRealign) { + this.index = index; + String label = mProj.getLab(index); + String initValue = mProj.getDef(index); + String desc = mProj.getDesc(index); + + bdoReload = needsReload; + bdoRealign = needsRealign; + + if(numLines == 1) { + nMode = MODE_TEXT; + theComp = new JTextField(FIELD_LEN); + ((JTextField)theComp).setBorder(BorderFactory.createLineBorder(Color.BLACK)); + } + else { + nMode = MODE_MULTI; + theComp = new JTextArea(numLines, FIELD_LEN); + ((JTextArea)theComp).setBorder(BorderFactory.createLineBorder(Color.BLACK)); + ((JTextArea)theComp).setLineWrap(true); + ((JTextArea)theComp).setWrapStyleWord(true); + ((JTextArea)theComp).setMinimumSize(((JTextArea)theComp).getPreferredSize()); + } + theLabel = Jcomp.createLabel(label, desc); + setValue(initValue); + setLayout(); + } + + // Used for properties that require a combo box + private Field(int index, String [] options, int selection, + boolean needsReload, boolean needsRealign, boolean bHasText) { + this.index = index; + String label = mProj.getLab(index); + String desc = mProj.getDesc(index); + + bdoReload = needsReload; + bdoRealign = needsRealign; + + nMode = MODE_COMBO; + comboBox = new JComboBox (options); + comboBox.setSelectedIndex(selection); + comboBox.setBackground(Color.WHITE); + comboBox.setMinimumSize(comboBox.getPreferredSize()); + comboBox.setMaximumSize(comboBox.getPreferredSize()); + + theLabel = Jcomp.createLabel(label, desc); + theComp = (JComboBox ) comboBox; + + if (bHasText) { + theComboText = new JTextField(5); + ((JTextField)theComboText).setBorder(BorderFactory.createLineBorder(Color.BLACK)); + } + else theComboText=null; + + setLayout(); + } + + private String getLabel() { return theLabel.getText(); } + private String getValue() { + if( nMode == MODE_TEXT) return ((JTextField)theComp).getText(); + if (nMode == MODE_MULTI) return ((JTextArea) theComp).getText(); + if (nMode == MODE_FILE) return ((FileTable) theComp).getValue(); + if (nMode == MODE_COMBO) { + if (theComboText!=null) { + String val = ((JTextField)theComboText).getText(); + if (!val.trim().equals("""")) return val; + } + return (String) comboBox.getSelectedItem(); + } + return null; + } + + private void setValue(String value) { + if(nMode == MODE_TEXT) ((JTextField)theComp).setText(value); + else if(nMode == MODE_MULTI) ((JTextArea) theComp).setText(value); + else if(nMode == MODE_FILE) ((FileTable) theComp).setValue(value); + else { // MODE_COMBO + for (int i=0; i 0) + add(Box.createHorizontalStrut(LABEL_WIDTH - d.width)); + add(theComp); + + if (theComboText!=null) { + add(Box.createHorizontalStrut(3)); + add(theComboText); + } + } + + protected int index=0; + private JComponent theComp = null, theComboText = null; + private JComboBox comboBox = null; + private JLabel theLabel = null; + private boolean bdoReload = false, bdoRealign = false; + private int nMode = -1; + } // end Fields class + + /*******************************************************/ + private class FileTable extends JPanel { + private static final long serialVersionUID = 1L; + + private FileTable(boolean singleSelect) { + bSingleSelect = singleSelect; + + theTable = new JTable(); + theModel = new FileTableModel(); + + theTable.setAutoCreateColumnsFromModel( true ); + theTable.setColumnSelectionAllowed( false ); + theTable.setCellSelectionEnabled( false ); + theTable.setRowSelectionAllowed( true ); + theTable.setShowHorizontalLines( false ); + theTable.setShowVerticalLines( true ); + theTable.setIntercellSpacing ( new Dimension ( 1, 0 ) ); + theTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + theTable.setOpaque(true); + + theTable.setModel(theModel); + theTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { + public void valueChanged(ListSelectionEvent arg0) { + btnRemove.setEnabled(theTable.getSelectedRowCount() > 0); + if(bSingleSelect) + btnAddFile.setEnabled(theTable.getRowCount() == 0); + } + }); + theTable.getTableHeader().setBackground(Color.WHITE); + sPane = new JScrollPane(theTable); + sPane.getViewport().setBackground(Color.WHITE); + + TableColumn column = theTable.getColumnModel().getColumn(0); + column.setMaxWidth(column.getPreferredWidth()); + column.setMinWidth(column.getPreferredWidth()); + + btnAddFile = Jcomp.createButton(""Add File"", ""Add selected file""); + btnAddFile.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String path=null; + + String defaultDir = getDefaultDir(); + JFileChooser cf = new JFileChooser(); + cf.setMultiSelectionEnabled(false); + cf.setCurrentDirectory(new File(defaultDir)); + + if(cf.showOpenDialog(getInstance()) == JFileChooser.APPROVE_OPTION) { + path = cf.getSelectedFile().getAbsolutePath().trim(); + if (path.length() > 0) theModel.addRow(path); + theTable.setVisible(false); + theTable.setVisible(true); + setDefaultDir(path); + } + updateButtons(); + } + }); + + btnAddDir = Jcomp.createButton(""Add Directory"", ""Add selected directory""); + btnAddDir.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String path=null; + String defaultDir = getDefaultDir(); + + JFileChooser cf = new JFileChooser(); + cf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + cf.setMultiSelectionEnabled(false); + cf.setCurrentDirectory(new File(defaultDir)); + + if(cf.showOpenDialog(getInstance()) == JFileChooser.APPROVE_OPTION) { + path = cf.getSelectedFile().getAbsolutePath().trim(); + if (path.length() > 0) theModel.addRow(path + ""/""); + theTable.setVisible(false); + theTable.setVisible(true); + setDefaultDir(path); + } + updateButtons(); + } + }); + + btnRemove = Jcomp.createButton(""Remove"", ""Remove selected item""); + btnRemove.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + theModel.removeRow(theTable.getSelectedRow()); + theTable.getSelectionModel().clearSelection(); + theTable.setVisible(false); + theTable.setVisible(true); + } + }); + btnRemove.setEnabled(false); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBackground(Color.WHITE); + + JPanel buttonRow = Jcomp.createRowPanel(); + buttonRow.add(btnAddFile); buttonRow.add(Box.createHorizontalStrut(20)); + buttonRow.add(btnAddDir); buttonRow.add(Box.createHorizontalStrut(20)); + buttonRow.add(btnRemove); + + add(sPane); + add(buttonRow); + } + private String getDefaultDir() { + String defDir; + + if (lastSeqDir==null) { + defDir = Constants.seqDataDir; + if (FileDir.pathExists(defDir+theDBName)) defDir += theDBName; + } + else defDir=lastSeqDir; + return defDir; + } + private void setDefaultDir(String path) { + if (path==null || path.length()==0) return; + + String upPath = path; + int last = path.lastIndexOf(""/""); + if (last>1) + upPath = path.substring(0, last); + + lastSeqDir=upPath; + } + private String getValue() { + String retVal = """"; + if(theModel.getRowCount() > 0) + retVal = (String)theModel.getValueAt(0, 1); + + for(int x=1; x 0) + theModel.addRow(vals[x]); + } + } + private void updateButtons() { + if(bSingleSelect && theTable.getRowCount() > 0) { + btnAddFile.setEnabled(false); + btnAddDir.setEnabled(false); + } + else { + btnAddFile.setEnabled(true); + btnAddDir.setEnabled(true); + } + } + private JScrollPane sPane = null; + private JTable theTable = null; + private FileTableModel theModel = null; + private boolean bSingleSelect = false; + + private JButton btnAddFile = null, btnAddDir = null, btnRemove = null; + + /**********************************************************************/ + private class FileTableModel extends AbstractTableModel { + private static final long serialVersionUID = 1L; + private final static String FILE_HEADER = ""File name/directory""; + private final static String FILE_TYPE = ""Type""; + + public FileTableModel() { + theFiles = new Vector (); + } + + public int getColumnCount() { return 2; } + public int getRowCount() { return theFiles.size(); } + public Object getValueAt(int row, int col) { + if(col == 0) { + if(theFiles.get(row).endsWith(""/"")) + return ""Dir""; + return ""File""; + } + return theFiles.get(row); + } + + public void addRow(String filename) { theFiles.add(filename); } + public void removeRow(int row) { theFiles.remove(row); } + public void clearAll() { theFiles.clear(); } + public Class getColumnClass(int column) { return String.class; } + + public String getColumnName(int columnIndex) { + if(columnIndex == 0) return FILE_TYPE; + return FILE_HEADER; + } + public boolean isCellEditable (int row, int column) { return false; } + + private Vector theFiles = null; + } + } // end File class + + /**************************************************************************/ + private String savAbbrev = """", savDname = """"; // this can popup a warning, do not want to keep repeating if not changed + private String theDBName = """"; + + private boolean bIsLoaded = false, bExistAlign = false; + private boolean bChgGrpPrefix = false; + private boolean bWasSave = false; + private Field [] theFields; + private String [] prevArr = null; + private JButton btnSave = null, btnCancel = null; + private CaretListener theListener = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/PairParams.java",".java","28897","679","package symap.manager; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.HashMap; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButton; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; +import javax.swing.JTextField; + +import backend.Constants; +import util.Jcomp; +import util.Jhtml; +import util.Utilities; +import util.Popup; + +/********************************************** + * The parameter window for Alignment&Synteny + */ + +public class PairParams extends JDialog { + private static final long serialVersionUID = 1L; + protected static String [] mergeOpts = {""None"", ""Overlap"", ""Close""}; + + // ManagerFrame.alignSelectedPair and updateEnableButtons use similar text + private String opt0Alt = ""Align&Synteny""; // Manager button Selected Pair + private String[] actOptions = {""Clust&Synteny"", // Manager button Selected Redo + ""Synteny Only"",""Number Pseudo""}; // Manager button sets from mp.bSynOnly... + + // Order MUST be same in createMainPanel and setValue and getValue; defaults are in Mpair + // These are NOT in the order displayed, but do not change without changing access everywhere else + private String [] LABELS = { // Order must be same as createMainPanel + ""Min hits"", ""Strict"", ""Orient"", ""Merge:"", + ""None"", ""Order1"", ""Order2"", + ""Concat"", ""Mask1"", ""Mask2"", + ""NUCmer args"", ""PROmer args"", ""Self args"", ""NUCmer only"",""PROmer only"", // mummer: + ""Number pseudo"", + ""Algorithm 1 (modified original)"", ""Algorithm 2 (exon-intron)"", + ""Top N piles"", + ""Gene"", ""Exon"", ""Len"",""G0_Len"", + ""EE"", ""EI"", ""En"", ""II"", ""In"" + }; + + // if change, change in Mpair too; defaults are in Mpair; written to DB and file + // order the same as above; constant strings are repeated multiple times in MPair + private static final String [] SYMBOLS = { // Mpairs.paramKey + ""mindots"", ""strict_blocks"", ""same_orient"", ""merge_blocks"", + ""order_none"", ""order_proj1"", ""order_proj2"", // none, proj1, proj2 + ""concat"",""mask1"", ""mask2"", + ""nucmer_args"", ""promer_args"", ""self_args"", ""nucmer_only"",""promer_only"", + ""number_pseudo"", ""algo1"", ""algo2"", + ""topn"", + ""gene_scale"", ""exon_scale"", ""len_scale"",""g0_scale"", + ""EE_pile"", ""EI_pile"", ""En_pile"", ""II_pile"", ""In_pile"" + }; + + private Mpair mp = null; + private Mproject mProj1 = null, mProj2 = null; + private ManagerFrame manFrame=null; + private boolean isAlignDone; // Could be A or check; mp.hasSynteny() determines which + private boolean isSelf=false; + + protected PairParams(Mpair mp, ManagerFrame manFrame, boolean alignDone) { + this.mp = mp; + this.mProj1 = mp.mProj1; + this.mProj2 = mp.mProj2; + this.manFrame = manFrame; + this.isAlignDone = alignDone; + isSelf = mProj1.getIdx()==mProj2.getIdx(); + + createMainPanel(); + setInit(); + + setModal(true); + setTitle(mProj1.strDBName + Constants.projTo + mProj2.strDBName + Constants.paramsFile); + } + /*********************************************************************/ + private void createMainPanel() { + int numWidth = 2, decWidth = 2, textWidth = 15; + + for (int i=0; i"" + mProj2.getdbAbbrev(); + else if (LABELS[i].equals(""Order2"")) LABELS[i] = mProj2.getdbAbbrev() + ""->"" + mProj1.getdbAbbrev(); + } + mainPanel = Jcomp.createPagePanel(); + + int x=0; // SAME ORDER AS array + // synteny + lblMinDots = Jcomp.createLabel(LABELS[x++], ""Miniumum hits in a block""); + txtMinDots = Jcomp.createTextField(""7"", ""Miniumum hits in a block"", numWidth); + + chkStrictBlocks = Jcomp.createCheckBox(LABELS[x++], ""Smaller gaps allowed and stricter mixed blocks"", true); + chkSameOrient = Jcomp.createCheckBox(LABELS[x++], ""Blocks must have hits in same orientation"", false); + + lblMerge = Jcomp.createLabel(LABELS[x++], ""Merge overlapping and close blocks""); + cmbMergeBlocks = Jcomp.createComboBox(mergeOpts, ""Each option includes the previous"", 0); + + String tip1 = mProj1.strDisplayName + "" order against "" + mProj2.strDisplayName; + String tip2 = mProj2.strDisplayName + "" order against "" + mProj1.strDisplayName; + radOrdNone = Jcomp.createRadio(LABELS[x++], ""None""); + radOrdProj1 = Jcomp.createRadio(LABELS[x++], tip1); + radOrdProj2 = Jcomp.createRadio(LABELS[x++], tip2); + + ButtonGroup group = new ButtonGroup(); + group.add(radOrdNone); group.add(radOrdProj1); group.add(radOrdProj2); + radOrdNone.setSelected(true); + + // prepare + chkConcat = Jcomp.createCheckBox(LABELS[x++],""Concat 1st project sequences into one file"", false); + + String tipm1 = ""Gene mask sequence for "" + mProj1.strDisplayName + ""; there must be a .gff file""; + String tipm2 = ""Gene mask sequence for "" + mProj2.strDisplayName + ""; there must be a .gff file""; + chkMask1 = Jcomp.createCheckBox(LABELS[x++], tipm1, false); + if (!mProj1.hasGenes()) chkMask1.setEnabled(false); + chkMask2 = Jcomp.createCheckBox(LABELS[x++], tipm2, false); + if (!mProj2.hasGenes()) chkMask2.setEnabled(false); + + // mummer + lblNucMerArgs = Jcomp.createLabel(LABELS[x++], ""NUCmer parameters""); txtNucMerArgs = Jcomp.createTextField("""",textWidth); + lblProMerArgs = Jcomp.createLabel(LABELS[x++], ""PROmer parameters""); txtProMerArgs = Jcomp.createTextField("""",textWidth); + lblSelfArgs = Jcomp.createLabel(LABELS[x++], ""NUCmer parameters for self-chromosome""); txtSelfArgs = Jcomp.createTextField("""",textWidth); + chkNucOnly = Jcomp.createRadio(LABELS[x++], ""Use NUCmer for this alignment""); + chkProOnly = Jcomp.createRadio(LABELS[x++], ""Use PROmer for this alignment""); + chkDef = Jcomp.createRadio(""Defaults"", ""Use NUCmer for self-synteny, otherwise use PROmer""); // not saved + ButtonGroup sgroup = new ButtonGroup(); + sgroup.add(chkNucOnly); sgroup.add(chkProOnly); sgroup.add(chkDef); + chkDef.setSelected(true); + + // Cluster + chkPseudo = Jcomp.createCheckBox(LABELS[x++], ""Number pseudo genes (un-annotated hit)"", false); + + chkAlgo1 = Jcomp.createRadio(LABELS[x++], ""Use Algo1""); + chkAlgo2 = Jcomp.createRadio(LABELS[x++], ""Use Algo2""); + ButtonGroup agroup = new ButtonGroup(); + agroup.add(chkAlgo1); agroup.add(chkAlgo2); + chkAlgo2.setSelected(!isSelf); + chkAlgo2.setEnabled(!isSelf); + + lblTopN = Jcomp.createLabel(LABELS[x++]); txtTopN = Jcomp.createTextField(""2"", ""Retain the top N hits of a pile of overlapping hits"", numWidth); + + String lab; + lab = ""Scale gene coverage (larger N requires more coverage)""; + lblGene = Jcomp.createLabel(LABELS[x++],lab); + txtGene = Jcomp.createTextField(""1.0"", lab, decWidth); + + lab = ""Scale exon coverage (larger N requires more coverage)""; + lblExon = Jcomp.createLabel(LABELS[x++],lab); + txtExon = Jcomp.createTextField(""1.0"", lab, decWidth); + + lab = ""Scale G2 and G1 length (Nx"" + backend.anchor2.Arg.iPpMinGxLen + "")""; + lblLen = Jcomp.createLabel(LABELS[x++], lab); txtLen = + Jcomp.createTextField(""1.0"", lab, decWidth); + + lab = ""Scale G0 length (Nx"" + backend.anchor2.Arg.iPpMinG0Len + "")""; + lblNoGene = Jcomp.createLabel(LABELS[x++],lab); + txtNoGene = Jcomp.createTextField(""1.0"",lab, decWidth); + + chkEEpile = Jcomp.createCheckBox(LABELS[x++],""Keep EE piles"", true); + chkEIpile = Jcomp.createCheckBox(LABELS[x++],""Keep EI and IE piles"", true); + chkEnpile = Jcomp.createCheckBox(LABELS[x++],""Keep En and nE piles"", true); + chkIIpile = Jcomp.createCheckBox(LABELS[x++],""Keep II piles"", false); + chkInpile = Jcomp.createCheckBox(LABELS[x++],""Keep In and nI piles"", false); + + // bottom row + btnKeep = Jcomp.createButton(""Save"", ""Save parameters and exit""); + btnKeep.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + setSave(); + } + }); + btnLoadDef = Jcomp.createButton(""Defaults"", ""Set defaults""); + btnLoadDef.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + setDefaults(); + } + }); + btnDiscard = Jcomp.createButton(""Cancel"", ""Cancel changes and exit""); + btnDiscard.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + setCancel(); + } + }); + btnActPop = Jcomp.createButton(""tmp label"", ""Click button for menu of options; Must be 'Save' to take effect.""); + createPopup(); + + /*-------- Create Layout ------------------*/ + ////////////////////////////////////////////////////////////////////////// + JPanel row = Jcomp.createRowPanel(); + String plab = mProj1.strDisplayName + "" ("" + mProj1.getdbAbbrev() + "") & "" + + mProj2.strDisplayName + "" ("" + mProj2.getdbAbbrev() + "")""; + row.add(Jcomp.createLabel(plab)); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + // Alignment + row = Jcomp.createRowPanel(); + row.add(Jcomp.createHtmlLabel(""Alignment"")); row.add(Box.createVerticalStrut(5)); // vert puts icon at end of line + row.add(Jhtml.createHelpIconSysSm(Jhtml.SYS_HELP_URL, Jhtml.param2Align)); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(chkConcat); + row.add(Box.createHorizontalStrut(15)); + + row.add(chkMask1); row.add(Box.createHorizontalStrut(5)); + row.add(chkMask2); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + int colWidth = 100; + row = Jcomp.createRowPanel(); + row.add(lblProMerArgs); + if (lblProMerArgs.getPreferredSize().width < colWidth) row.add(Box.createHorizontalStrut(colWidth - lblProMerArgs.getPreferredSize().width)); + row.add(txtProMerArgs); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(lblNucMerArgs); + if (lblNucMerArgs.getPreferredSize().width < colWidth) row.add(Box.createHorizontalStrut(colWidth - lblNucMerArgs.getPreferredSize().width)); + row.add(txtNucMerArgs); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(lblSelfArgs); + if (lblSelfArgs.getPreferredSize().width < colWidth) row.add(Box.createHorizontalStrut(colWidth - lblSelfArgs.getPreferredSize().width)); + row.add(txtSelfArgs); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(chkProOnly); mainPanel.add(row);mainPanel.add(Box.createHorizontalStrut(20)); + row.add(chkNucOnly); mainPanel.add(row);mainPanel.add(Box.createHorizontalStrut(20)); + row.add(chkDef); mainPanel.add(row);mainPanel.add(Box.createVerticalStrut(5)); + + // Clusters + int indent=25; + mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(Jcomp.createHtmlLabel(""Cluster Hits"")); + row.add(Jhtml.createHelpIconSysSm(Jhtml.SYS_HELP_URL, Jhtml.param2Clust)); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(chkPseudo); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(chkAlgo1); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + chkAlgo1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + boolean b = chkAlgo1.isSelected(); + lblSelfArgs.setEnabled(b); + txtSelfArgs.setEnabled(b); + } + }); + + row = Jcomp.createRowPanel(); row.add(Box.createHorizontalStrut(indent)); + row.add(lblTopN); row.add(Box.createHorizontalStrut(5)); + row.add(txtTopN); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(chkAlgo2); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + chkAlgo2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + boolean b = chkAlgo2.isSelected(); + lblSelfArgs.setEnabled(!b); + txtSelfArgs.setEnabled(!b); + } + }); + + row = Jcomp.createRowPanel(); row.add(Box.createHorizontalStrut(indent)); + JLabel j = Jcomp.createLabel(""Scale:"", ""Increase scale creates less hits, decrease creates more hits""); + row.add(j); row.add(Box.createHorizontalStrut(8)); + row.add(lblGene); row.add(txtGene); row.add(Box.createHorizontalStrut(5)); + row.add(lblExon); row.add(txtExon); row.add(Box.createHorizontalStrut(5)); + row.add(lblLen); row.add(txtLen); row.add(Box.createHorizontalStrut(5)); + row.add(lblNoGene); row.add(txtNoGene); row.add(Box.createHorizontalStrut(5)); + if (!isSelf) {mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5));} + + row = Jcomp.createRowPanel(); row.add(Box.createHorizontalStrut(indent)); + row.add(new JLabel(""Keep piles:"")); + row.add(chkEEpile); row.add(Box.createHorizontalStrut(5)); + row.add(chkEIpile); row.add(Box.createHorizontalStrut(5)); + row.add(chkEnpile); row.add(Box.createHorizontalStrut(5)); + row.add(chkIIpile); row.add(Box.createHorizontalStrut(5)); + row.add(chkInpile); row.add(Box.createHorizontalStrut(5)); + if (!isSelf) {mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5));} + + // Synteny + mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(5)); + row = Jcomp.createRowPanel(); + row.add(Jcomp.createHtmlLabel(""Synteny Blocks"")); row.add(Box.createVerticalStrut(5)); + row.add(Jhtml.createHelpIconSysSm(Jhtml.SYS_HELP_URL, Jhtml.param2Syn)); + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + row.add(lblMinDots); row.add(Box.createHorizontalStrut(3)); + row.add(txtMinDots); row.add(Box.createHorizontalStrut(5)); + row.add(chkStrictBlocks); row.add(Box.createHorizontalStrut(5)); + row.add(chkSameOrient); row.add(Box.createHorizontalStrut(12)); + row.add(lblMerge); row.add(Box.createHorizontalStrut(2)); + row.add(cmbMergeBlocks); + + mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(3)); + + // order against + mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(3)); + row = Jcomp.createRowPanel(); + row.add(Jcomp.createLabel(""Order against: "", ""Order one project against another; the alignment does not need to be redone."")); + row.add(radOrdNone); row.add(Box.createHorizontalStrut(3)); + row.add(radOrdProj1); row.add(Box.createHorizontalStrut(2)); + row.add(radOrdProj2); + if (mProj1!=mProj2) {mainPanel.add(row); mainPanel.add(Box.createVerticalStrut(5));} + + // Buttons + mainPanel.add(new JSeparator()); mainPanel.add(Box.createVerticalStrut(5)); + + row = Jcomp.createRowPanel(); + JPanel buttonPanel = Jcomp.createRowPanel(); + buttonPanel.add(btnActPop); buttonPanel.add(Box.createHorizontalStrut(14)); + buttonPanel.add(btnKeep); buttonPanel.add(Box.createHorizontalStrut(3)); + buttonPanel.add(btnLoadDef); buttonPanel.add(Box.createHorizontalStrut(3)); + buttonPanel.add(btnDiscard); + + buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT); + + row.add(Box.createHorizontalGlue()); + row.add(buttonPanel); + row.add(Box.createHorizontalGlue()); + mainPanel.add(row); + + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setMaximumSize(mainPanel.getPreferredSize()); + mainPanel.setMinimumSize(mainPanel.getPreferredSize()); + + add(mainPanel); + pack(); + setResizable(false); + setLocationRelativeTo(null); + } + /******************************************************/ + private void createPopup() { + if (!isAlignDone) actOptions[0] = opt0Alt; + act0Radio = new JRadioButtonMenuItem(actOptions[0]); + act1Radio = new JRadioButtonMenuItem(actOptions[1]); + act2Radio = new JRadioButtonMenuItem(actOptions[2]); + + PopupListener listener = new PopupListener(); + act0Radio.addActionListener(listener); + act1Radio.addActionListener(listener); + act2Radio.addActionListener(listener); + + JPopupMenu popupMenu = new JPopupMenu(); + popupMenu.setBackground(symap.Globals.white); + + JMenuItem popupTitle = new JMenuItem(); + popupTitle.setText(""Select Task""); + popupTitle.setEnabled(false); + popupMenu.add(popupTitle); + popupMenu.addSeparator(); + + popupMenu.add(act0Radio); + popupMenu.add(act1Radio); + popupMenu.add(act2Radio); + + if (!mp.hasSynteny()) { + act1Radio.setEnabled(false); + act2Radio.setEnabled(false); + } + + ButtonGroup grp = new ButtonGroup(); + grp.add(act0Radio); grp.add(act1Radio); grp.add(act2Radio); + + btnActPop.setComponentPopupMenu(popupMenu); // zoomPopupButton create in main + btnActPop.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + popupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + }); + Dimension d = new Dimension(120, 30); // w,d + btnActPop.setPreferredSize(d); btnActPop.setMaximumSize(d); btnActPop.setMinimumSize(d); + + if (mp.bSynOnly) setPopup(act1Radio); + else if (mp.bPseudo) setPopup(act2Radio); + else setPopup(act0Radio); + } + /************************************************************************/ + private String getValue(String symbol) {// ORDER MUST BE SAME AS array + int x=0; + + if (symbol.equals(SYMBOLS[x++])) return txtMinDots.getText(); + else if (symbol.equals(SYMBOLS[x++])) return chkStrictBlocks.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkSameOrient.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return cmbMergeBlocks.getSelectedIndex() + """"; + + else if (symbol.equals(SYMBOLS[x++])) return radOrdNone.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return radOrdProj1.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return radOrdProj2.isSelected()?""1"":""0""; + + else if (symbol.equals(SYMBOLS[x++])) return chkConcat.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkMask1.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkMask2.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return txtNucMerArgs.getText(); + else if (symbol.equals(SYMBOLS[x++])) return txtProMerArgs.getText(); + else if (symbol.equals(SYMBOLS[x++])) return txtSelfArgs.getText(); + else if (symbol.equals(SYMBOLS[x++])) return chkNucOnly.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkProOnly.isSelected()?""1"":""0""; + + else if (symbol.equals(SYMBOLS[x++])) return chkPseudo.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkAlgo1.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkAlgo2.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return txtTopN.getText(); + + else if (symbol.equals(SYMBOLS[x++])) return txtGene.getText(); + else if (symbol.equals(SYMBOLS[x++])) return txtExon.getText(); + else if (symbol.equals(SYMBOLS[x++])) return txtLen.getText(); + else if (symbol.equals(SYMBOLS[x++])) return txtNoGene.getText(); + + else if (symbol.equals(SYMBOLS[x++])) return chkEEpile.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkEIpile.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkEnpile.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkIIpile.isSelected()?""1"":""0""; + else if (symbol.equals(SYMBOLS[x++])) return chkInpile.isSelected()?""1"":""0""; + else return """"; + } + private void setValue(String symbol, String value) {// ORDER MUST BE SAME AS array + int x=0; + + if (symbol.equals(SYMBOLS[x++])) txtMinDots.setText(value); + else if (symbol.equals(SYMBOLS[x++])) chkStrictBlocks.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkSameOrient.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) { + int idx = Utilities.getInt(value); + if (idx==-1) idx = 0; + cmbMergeBlocks.setSelectedIndex(idx); // number 0,1,2 + } + else if (symbol.equals(SYMBOLS[x++])) radOrdNone.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) radOrdProj1.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) radOrdProj2.setSelected(value.equals(""1"")); + + else if (symbol.equals(SYMBOLS[x++])) chkConcat.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkMask1.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkMask2.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) txtNucMerArgs.setText(value); + else if (symbol.equals(SYMBOLS[x++])) txtProMerArgs.setText(value); + else if (symbol.equals(SYMBOLS[x++])) txtSelfArgs.setText(value); + else if (symbol.equals(SYMBOLS[x++])) chkNucOnly.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkProOnly.setSelected(value.equals(""1"")); + + else if (symbol.equals(SYMBOLS[x++])) chkPseudo.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkAlgo1.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkAlgo2.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) txtTopN.setText(value); + + else if (symbol.equals(SYMBOLS[x++])) txtGene.setText(value); + else if (symbol.equals(SYMBOLS[x++])) txtExon.setText(value); + else if (symbol.equals(SYMBOLS[x++])) txtLen.setText(value); + else if (symbol.equals(SYMBOLS[x++])) txtNoGene.setText(value); + + else if (symbol.equals(SYMBOLS[x++])) chkEEpile.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkEIpile.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkEnpile.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkIIpile.setSelected(value.equals(""1"")); + else if (symbol.equals(SYMBOLS[x++])) chkInpile.setSelected(value.equals(""1"")); + } + /************************************************************************/ + + private void setInit() { + setParams(mp.getFileParams()); + + if (mp.bSynOnly) setPopup(act1Radio); + else if (mp.bPseudo) setPopup(act2Radio); + else setPopup(act0Radio); + } + private void setParams(HashMap valMap) { + for(int x=0; x fileMap = mp.getFileParams(); + + for (String key : SYMBOLS) fileMap.put(key, getValue(key)); + + mp.saveParamsToFile(fileMap); // saves to DB when run + + bSavPseudo = mp.bPseudo; bSavSynOnly = mp.bSynOnly; + manFrame.updateEnableButtons(); // update Selected pair label + + if (mp.bSynOnly) setSaveSynOnly(); + else if (mp.bPseudo) setSavePseudo(); + + setVisible(false); + } + private void setSavePseudo() { + setParams(mp.getDbParams()); + chkPseudo.setSelected(true); + } + private void setSaveSynOnly() { + boolean isOrient = chkSameOrient.isSelected(); + int isMerge = cmbMergeBlocks.getSelectedIndex(); + boolean isPrune = chkStrictBlocks.isSelected(); + String dot = txtMinDots.getText(); + int order=0; + if (radOrdProj1.isSelected()) order=1; + else if (radOrdProj2.isSelected()) order=2; + + setParams(mp.getDbParams()); // The wrong values will be in Summary if this is not done + + chkSameOrient.setSelected(isOrient); + cmbMergeBlocks.setSelectedIndex(isMerge); + chkStrictBlocks.setSelected(isPrune); + txtMinDots.setText(dot); + if (order==0) radOrdNone.setSelected(true); + else if (order==1) radOrdProj1.setSelected(true); + else if (order==2) radOrdProj2.setSelected(true); + } + /*********************************************/ + private boolean checkInt(String label, String x, int min) { + if (x.trim().equals("""")) x=""0""; + int i = Utilities.getInt(x.trim()); + if (min==0) { + if (i<0) { + Popup.showErrorMessage(label + ""="" + x + ""\nIs an incorrect integer ("" + x + ""). Must be >=0.""); + return false; + } + return true; + } + if (i==-1 || i==0) { + Popup.showErrorMessage(label + ""="" + x + ""\nIs an incorrect integer. Must be >0.""); + return false; + } + // warnings + if (label.startsWith(""Top"") && i>4) { + Popup.showContinue(""Top N piles"", ""Top N > 4 may produce worse results and take significantly longer.""); + } + + return true; + } + private boolean checkDouble(String label, String x, double min) { + if (x.trim().equals("""")) x=""0.0""; + double d = Utilities.getDouble(x.trim()); + if (min==0) { + if (d<0) { + Popup.showErrorMessage(label + ""="" + x + ""\nIs an incorrect decimal ("" + x + ""). Must be >=0.""); + return false; + } + return true; + } + if (d==-1 || d==0) { + Popup.showErrorMessage(label + ""="" + x + ""\nIs an incorrect decimal. Must be >0.""); + return false; + } + return true; + } + + /************************************************************************/ + private JPanel mainPanel = null; + + private JCheckBox chkConcat = null, chkMask1 = null, chkMask2 = null; + private JLabel lblNucMerArgs = null, lblProMerArgs = null, lblSelfArgs = null; + private JTextField txtNucMerArgs = null, txtSelfArgs = null, txtProMerArgs = null; + private JRadioButton chkNucOnly = null, chkProOnly = null, chkDef = null; + + private JRadioButton chkAlgo1, chkAlgo2; + + private JLabel lblTopN = null; + private JTextField txtTopN = null; + + private JLabel lblNoGene, lblGene, lblExon, lblLen; + private JTextField txtNoGene, txtGene, txtExon, txtLen; + private JCheckBox chkEEpile = null, chkEIpile = null, chkEnpile = null, chkIIpile = null, chkInpile = null; + + private JCheckBox chkPseudo = null; + + private JLabel lblMinDots = null; + private JTextField txtMinDots = null; + private JCheckBox chkSameOrient = null, chkStrictBlocks = null; + private JLabel lblMerge = null; + private JComboBox cmbMergeBlocks = null; + private JRadioButton radOrdNone=null, radOrdProj1=null, radOrdProj2=null; + + private JButton btnKeep = null, btnDiscard = null, btnLoadDef = null; + + private JButton btnActPop; + private JRadioButtonMenuItem act0Radio = null; + private JRadioButtonMenuItem act1Radio = null; + private JRadioButtonMenuItem act2Radio = null; + private boolean bSavPseudo=false, bSavSynOnly=false; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/RemoveProj.java",".java","7099","210","package symap.manager; + +import java.io.File; +import java.io.FileWriter; +import java.util.Vector; + +import backend.Constants; +import symap.Globals; +import util.ErrorReport; +import util.Utilities; +import util.Popup; +import util.FileDir; + +/*********************************************************** + * Methods for removing projects + */ +public class RemoveProj { + final static String sp= "" ""; + private FileWriter fw = null; + + protected RemoveProj(FileWriter fw) {this.fw = fw;} + private void close() { + try { + if (fw!=null) {fw.close(); fw=null;} + } + catch (Exception e){} + } + /*************************************************************** + * Remove project from database: Manager database link + */ + protected void removeProjectDB(Mproject pj) { + String msg = ""Remove "" + pj.getDisplayName() + "" from database""; + + if (Popup.showConfirm2(""Remove from database"",msg)) { + pj.removeProjectFromDB(); + try { + fw.append(""Remove project "" + pj.getDisplayName() + "" from database "" + Utilities.getDateTime()+ ""\n""); + } catch (Exception e) {} + } + close(); + } + + /************************************************************** + * Remove project from disk: Manager disk link + */ + protected void removeProjectDisk(Mproject pj) { + String path = Constants.seqDataDir + pj.getDBName(); + String title = ""Remove project""; + String msg = ""Remove project "" + pj.getDBName(); // getDBName is seq/directory + try { + int rc; + if (pj.hasExistingAlignments(false)) { // if directory exists, even if no /align + rc = Popup.showConfirm3(title,msg + + ""\n\nOnly: Remove alignment directories from disk"" + // may want to remove alignments and not project + ""\nAll: Remove alignments and project directory from disk""); + if (rc==0) {close(); return;} + + System.out.println(""Confirming removal of "" + pj.getDisplayName() + "" alignments directories from disk....""); + removeAllAlignFromDisk(pj, true); // remove top directory; prints removals + + if (rc!=2) {close(); return;} + } + // project directory + if (!Popup.showConfirm2(title,msg + ""\n\nRemove from disk:\n "" + path)) {close(); return;} + + System.out.println(""Remove project from disk: "" + path); + File f = new File(path); + FileDir.deleteDir(f); + if (f.exists()) f.delete();// not removing topdir on Linux, so try again + + close(); + } + catch (Exception e) {ErrorReport.print(e, ""Remove project from disk"");} + } + /********************************************************** + * Reload project: ManagerFrame link + */ + protected boolean reloadProject(Mproject pj) { + try { + String msg = ""Reload project "" + pj.getDisplayName(); + if (!pj.hasExistingAlignments(true)) { // only care if there is a /align + if (!Popup.showConfirm2(""Reload project"",msg)) {close(); return false;} + } + else { + int rc = Popup.showConfirm3(""Reload project"",msg + + ""\n\nOnly: Reload project only"" + + ""\nAll: Reload project and remove alignments from disk""); + if (rc==0) {close(); return false;} + + if (rc==2) { + System.out.println(""Confirming removals of "" + pj.getDisplayName() + "" alignments from disk....""); + removeAllAlignFromDisk(pj, false); // do not remove topDir + } + } + pj.removeProjectFromDB(); // do not need finish method because starts loading after this + close(); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""reload project""); return false;} + } + /****************************************************************** + * Clear pair button + **********************************/ + protected void removeClearPair(Mproject p1, Mproject p2, Mpair mp) {// does use fw + String msg = ""Clear pair "" + p1.getDBName() + "" to "" + p2.getDBName(); + int rc = 2; + if (mp.isPairInDB()) { + rc = Popup.showConfirm3(""Clear pair"", msg + + ""\n\nOnly: remove synteny from database"" + + ""\nAll: remove synteny and alignments from disk for this pair""); + } + else { + if (!Popup.showConfirm2(""Clear alignments"",msg + + ""\nRemove alignments for this pair from disk"")) {close(); return;} + } + if (rc==0) {close(); return;} + + try { + if (rc==2) { + String path = Constants.getNameResultsDir(p1.getDBName(), p2.getDBName()); + msg = ""Remove MUMmer files in:\n "" + path; + if (!Popup.showConfirm2(""Remove from disk"", msg)) { + System.out.println(sp + ""cancel removal of "" + path); + return; + } + + Globals.prt(""Remove alignments from "" + path); + removeAlignFromDir(new File(path)); + } + if (mp.isPairInDB()) { + mp.removePairFromDB(true); // True = redo numHits; + Globals.prt(""Removed from database "" + p1.getDBName() + "" to "" + p2.getDBName()); + } + + close(); + } + catch (Exception e) {ErrorReport.print(e, ""Clearing alignment"");} + } + /****************************************************************** + * Remove Project From Disk (true); + * Reload Project (false) + */ + private boolean removeAllAlignFromDisk(Mproject p, boolean rmTopDir) { + try { + File top = new File(Constants.getNameResultsDir()); // check seq_results + + if (top == null || !top.exists()) return true; + + Vector alignDirs = new Vector(); + String pStart = p.getDBName() + Constants.projTo, pEnd = Constants.projTo + p.getDBName(); + + for (File f : top.listFiles()) { + if (f.isDirectory()) { + if (f.getName().startsWith(pStart) || f.getName().endsWith(pEnd)) { + alignDirs.add(f); + } + } + } + if (alignDirs.size() == 0) return true; + + for (File f : alignDirs) { + String msg = (rmTopDir) ? ""Remove directory: "" : ""Remove MUMmer files in: ""; + msg += ""\n "" + Constants.seqRunDir + f.getName(); + + if (!Popup.showConfirm2(""Remove from disk"", msg)) { + System.out.println(sp + ""cancel removal of "" + f.getName()); + continue; + } + if (rmTopDir) { + System.out.println(sp + ""remove "" + f.getName()); + fw.append(""Remove align directory "" + f.getName() + "" "" + Utilities.getDateTime()+ ""\n""); + + FileDir.deleteDir(f); + if (f.exists()) f.delete(); + } + else { + System.out.println(sp + ""remove MUMmer files from: "" + f.getName()); // not printed for clear + removeAlignFromDir(f); + } + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Remove all alignment files""); return false;} + } + + /****************************************************************** + * Remove /align, /results and params_align_used + * --removeAllAlignFromDisk for Reload Project + * --Clear pair + */ + private void removeAlignFromDir(File f) { + try { + File f1 = new File(f.getAbsoluteFile() + ""/"" + Constants.alignDir); + if (f1.exists()) { + FileDir.deleteDir(f1); + if (f1.exists()) f1.delete(); + } + else System.out.println(sp + ""MUMmer files "" + f.getName() + "" already deleted""); + + File f2 = new File(f.getAbsoluteFile() + ""/"" + Constants.finalDir); + FileDir.deleteDir(f2); + if (f2.exists()) f2.delete(); + + File f3 = new File(f.getAbsoluteFile() + ""/"" + Constants.usedFile); + if (f3.exists()) f3.delete(); + } + catch (Exception e) {ErrorReport.print(e, ""\nRemove alignment files""); } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/ManagerFrame.java",".java","65450","1806","package symap.manager; + +import java.sql.ResultSet; +import java.util.Collections; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; +import java.util.Comparator; +import java.util.Set; +import java.io.File; +import java.io.FileWriter; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.table.*; +import javax.swing.event.*; + +import backend.Constants; +import backend.Utils; +import backend.DoLoadProj; +import backend.DoAlignSynPair; + +import blockview.BlockViewFrame; +import circview.CircFrame; +import dotplot.DotPlotFrame; +import props.PropertiesReader; + +import symap.Globals; +import symap.frame.ChrExpInit; +import symapQuery.QueryFrame; + +import database.DBconn2; +import database.Version; + +import util.ErrorReport; +import util.Utilities; +import util.FileDir; +import util.Popup; +import util.Jhtml; +import util.Jcomp; +import util.LinkLabel; + +/***************************************************** + * The manager main frame that displays the projects on the left and the pair table on the right + * + * Mprojects - have proj_idx numbered in the order they are loaded + * The left side and pair table has them alphanumerically ordered by Display Name + * Mpair - have proj1_idx and proj2_idx ordered according to how they were first entered into DB as a pair + * hence, getMpair has to check the key=proj1_idx:proj2_idx or proj2_idx:proj1_idx + * Note that the Display name can change along with the order; that does not change the DB pairs record. + */ +@SuppressWarnings(""serial"") // Prevent compiler warning for missing serialVersionUID +public class ManagerFrame extends JFrame implements ComponentListener { + /************************************************ + * Command line arguments; set in symapCE.SyMAPmanager main + */ + protected static boolean inReadOnlyMode = false;// set from viewSymap script with -r + + // On ManagerFrame panel + public static int maxCPU=-1; // SyMAPmanager -p; used in mummer and symapQuery + + private final String DB_ERROR_MSG = ""A database error occurred, please see the Troubleshooting Guide at:\n"" + Jhtml.TROUBLE_GUIDE_URL; + private final String DATA_PATH = Constants.dataDir; + private final int MIN_CWIDTH = 825, MIN_CHEIGHT = 900; // Circle; (same as 2D) + private final int MIN_WIDTH = 850, MIN_HEIGHT = 600; // Manager + private final int MIN_DIVIDER_LOC = 220; + private final int LEFT_PANEL = 450; + private final int TOP_PANEL = 300; + + private static final String HTML = ""/html/ProjMgrInstruct.html""; + + private final Color cellColor = new Color(0,170,0,85); // pale green; for selected box + private final Color textColor = new Color(0,100,0,255); // dark green for ""Select a Pair..."" + + // If changed - don't make one a substring of another!! + private final String TBL_DONE = ""\u2713"", TBL_ADONE = ""A"", TBL_QDONE = ""?""; + private final String symapLegend = ""Table Legend:\n"" + + TBL_DONE + "" : synteny has been computed, ready to view.\n"" + + TBL_ADONE + "" : alignment is done, synteny needs to be computed.\n"" + + TBL_QDONE + "" : alignment is partially done.""; + private final String selectPairText = ""Select a Pair by clicking\ntheir shared table cell."";// Click a lower diagonal cell to select the project pair. + + private final String pseudoOnly = ""Pseudo Only""; + + protected String frameTitle=""SyMAP "" + Globals.VERSION; // all frames use same title + protected DBconn2 dbc2 = null; // master, used for local loads, and used as template for processes + + // See initProjects + private Vector projVec = new Vector (); // projects on db and disk (!viewSymap) + private HashMap projObjMap = new HashMap (); // displayName, same set as projVec + private HashMap projNameMap = new HashMap (); // DBname to displayName + + protected Vector selectedProjVec = new Vector(); + + private HashMap pairObjMap = new HashMap (); // proj1_idx:proj2_idx is key + + private PairParams ppFrame = null; // only !null if opened + private PropertiesReader dbProps; + private String dbName = null; // append to LOAD.log + + private int totalCPUs=0; + + private JButton btnAllChrExp, btnSelDotplot, btnAllDotplot, btnSelClearPair, + btnSelBlockView, btnSelCircView, btnAllQueryView, btnSelReports, + btnAddProject = null, btnSelAlign, btnPairParams; + + private JSplitPane splitPane; + private JComponent instructionsPanel; + private JTable pairTable; + + private AddProjectPanel addProjectPanel = null; + + private JTextField txtCPUs =null; + private JCheckBox checkVB=null; + + /*****************************************************************/ + public ManagerFrame() { + super(""SyMAP "" + Globals.VERSION); + + // Add window handler to kill mysqld on clean exit + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) { + shutdown(); + System.exit(0); // sometimes this is needed + } + }); + + // Add shutdown handler to kill mysqld on CTRL-C + Runtime.getRuntime().addShutdownHook( new MyShutdown() ); + + initProjects(Globals.bMySQL); + + instructionsPanel = Jhtml.createInstructionsPanel(this.getClass().getResourceAsStream(HTML), getBackground()); + JPanel projPanel = createProjectPanel(); + + splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, projPanel, instructionsPanel ); + splitPane.setDividerLocation(MIN_DIVIDER_LOC); + + add(splitPane); + + setSize(MIN_WIDTH, MIN_HEIGHT); + setLocationRelativeTo(null); + + addComponentListener(this); // hack to enforce minimum frame size + } + + /*********************************************************************** + * Called at startup and refreshMenu (after any project changes) + */ + private void initProjects(boolean bSQL) { + try { + if (dbc2 == null) { // 1st init mysql + dbc2 = makeDBconn(); + + new Version(dbc2).check(); // check was made separate + + if (bSQL) dbc2.checkVariables(true); + } + Jhtml.setResClass(this.getClass()); + Jhtml.setHelpParentFrame(this); + + /*****************************************************/ + loadProjectsFromDB(); + loadPairsFromDB(); // used results of loadProjectsFromDB + + if (!inReadOnlyMode) { // read remaining projects from disk + String strDataPath = Constants.dataDir; + + if (FileDir.dirExists(strDataPath)) { + FileDir.checkCreateDir(Constants.logDir,true/*bPrt*/); + + loadProjectsFromDisk(strDataPath, Constants.seqType); // must come after loadFromDB + } + } + sortProjDisplay(projVec); + + Vector newSelectedProjects = new Vector(); + for (Mproject p1 : selectedProjVec) { + for (Mproject p2 : projVec) { + if (p1.equals(p2)) { + newSelectedProjects.add(p2); + break; + } + } + } + selectedProjVec = newSelectedProjects; + } + catch (Exception e) {ErrorReport.die(e, DB_ERROR_MSG);} + } + + private static boolean isShutdown = false; + private synchronized void shutdown() { + if (!isShutdown) { + if (dbc2!=null) dbc2.shutdown(); // Shutdown mysqld + isShutdown = true; + } + } + private class MyShutdown extends Thread { // runs at program exit + public void run() { + shutdown(); + } + } + /*******************************************************************/ + public void refreshMenu() { + Jcomp.setCursorBusy(this, true); + + initProjects(false); // recreates project lists on every refresh; easier then modifing projVec etc + + splitPane.setLeftComponent( createProjectPanel() ); + if (selectedProjVec.size() > 0) + splitPane.setRightComponent( createSelectedPanel() ); + else + splitPane.setRightComponent( instructionsPanel ); + + Jcomp.setCursorBusy(this, false); + } + + /** Left Panel of all projects **************************************************************/ + private JPanel createProjectPanel() { + JPanel panel = new JPanel(); + panel.setLayout( new BoxLayout ( panel, BoxLayout.Y_AXIS ) ); + panel.setBorder( BorderFactory.createEmptyBorder(10, 5, 10, 5) ); + + JPanel projPanel = new JPanel(); + projPanel.setLayout(new BoxLayout( projPanel, BoxLayout.LINE_AXIS)); + projPanel.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel lblTitle = Jcomp.createLabel(""Projects"", Font.BOLD, 18); + lblTitle.setAlignmentX(Component.CENTER_ALIGNMENT); + projPanel.add(lblTitle); + panel.add(projPanel); + panel.add(Box.createVerticalStrut(10)); + + JPanel subPanel = new JPanel(); + subPanel.setLayout( new BoxLayout ( subPanel, BoxLayout.Y_AXIS ) ); + subPanel.setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 0) ); + subPanel.setBackground(Color.white); + + // TreeSet so alphabetical display + TreeMap> cat2Proj = new TreeMap>(); + for (Mproject p : projVec) { + String category = p.getdbCat(); + if (category == null || category.length() == 0) category = ProjParams.catUncat; + if (!cat2Proj.containsKey(category)) cat2Proj.put(category, new TreeSet()); + cat2Proj.get(category).add(p); + } + + // Figure out what to show + Set categories = cat2Proj.keySet(); + TreeMap showMap = new TreeMap (); + for (String cat : categories) { + for (Mproject p : cat2Proj.get(cat)) { + if (inReadOnlyMode && p.getCntSyntenyStr().equals("""")) continue; // nothing to view + + if (showMap.containsKey(cat)) showMap.put(cat, showMap.get(cat)+1); + else showMap.put(cat, 1); + } + } + for (String cat : showMap.keySet()) { + if (showMap.get(cat)==0) continue; + + subPanel.add( new JLabel(cat) ); + + for (Mproject p : cat2Proj.get(cat)) { + if (inReadOnlyMode && p.getCntSyntenyStr().equals("""")) continue; // nothing to view + + ProjectCheckBox cb = null; + String name = p.getDisplayName(); + boolean bLoaded = (p.getStatus() != Mproject.STATUS_ON_DISK); + if (bLoaded) + name += "" ("" + p.getLoadDate() + "") "" + p.getCntSyntenyStr(); + cb = new ProjectCheckBox( name, p ); + Font f = new Font(cb.getFont().getName(), Font.PLAIN, cb.getFont().getSize()); + cb.setFont(f); + subPanel.add( cb ); + } + subPanel.add( Box.createVerticalStrut(5) ); + } + + JScrollPane scroller = new JScrollPane(subPanel, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + scroller.getVerticalScrollBar().setUnitIncrement(10); + scroller.setAlignmentX(Component.CENTER_ALIGNMENT); + + panel.add( scroller ); + panel.add(Box.createVerticalStrut(10)); + + JPanel addPanel = new JPanel(); + addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.LINE_AXIS)); + addPanel.setAlignmentX(Component.CENTER_ALIGNMENT); + + btnAddProject = new JButton(""Add Project""); + btnAddProject.setAlignmentX(Component.CENTER_ALIGNMENT); + btnAddProject.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + addProjectPanel = new AddProjectPanel(); + addProjectPanel.reset(); + addProjectPanel.setVisible(true); + } + }); + if (!inReadOnlyMode) addPanel.add(btnAddProject); + + panel.add(addPanel); + + panel.setMinimumSize( new Dimension(MIN_DIVIDER_LOC-20, MIN_HEIGHT) ); + + return panel; + } + /***** Right panel of selected projects ***********************************************/ + private JPanel createSelectedPanel() { + JPanel mainPanel = new JPanel(); + mainPanel.setLayout( new BoxLayout ( mainPanel, BoxLayout.Y_AXIS ) ); + mainPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0)); + + // Top area + JLabel lblTitle = Jcomp.createLabel(""Selected"", Font.BOLD, 18); + JButton btnHelp; + if (!inReadOnlyMode)btnHelp = Jhtml.createHelpIconSysSm(Jhtml.SYS_HELP_URL, Jhtml.build); + else btnHelp = Jhtml.createHelpIconUserSm(Jhtml.view); + mainPanel.add( Jcomp.createHorizPanel( new Component[] { lblTitle,btnHelp}, LEFT_PANEL, 0)); + + // Add individual project summaries + JPanel subPanel = new JPanel(); + subPanel.setLayout( new BoxLayout ( subPanel, BoxLayout.Y_AXIS ) ); + subPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + subPanel.add( Box.createVerticalStrut(5) ); + + int nUnloaded = 0; + for (Mproject p : selectedProjVec) { + if (p.getStatus() == Mproject.STATUS_ON_DISK) nUnloaded++; + } + if (nUnloaded > 0) { + LinkLabel btnLoadAllProj = new LinkLabel(""Load All Projects"", Color.blue, Color.blue.darker()); + btnLoadAllProj.addMouseListener( doLoadAllProj ); + subPanel.add(btnLoadAllProj ); + subPanel.add( Box.createVerticalStrut(10) ); + } + for (Mproject mProj : selectedProjVec) { + lblTitle = Jcomp.createLabel( mProj.getDisplayName(), Font.BOLD, 15 ); + + JPanel textPanel = new JPanel(); + textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.PAGE_AXIS)); + textPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + // line 1 + String label1 = ""Directory: "" + mProj.getDBName() + "" Abbrev: "" + mProj.getdbAbbrev(); + + textPanel.add(new JLabel(label1)); + + // line 2 + String d = mProj.getdbDesc(); + if(d != null && d.length()>0) textPanel.add(new JLabel(""Description: "" + d)); + + // rest of lines + if(mProj.getStatus() == Mproject.STATUS_ON_DISK) { + String x = mProj.notLoadedInfo(); + textPanel.add(new JLabel(x)); + } + else { + String group = mProj.getdbGrpName(); + if (Utilities.isEmpty(group)) group = ""Chromosome""; + String label2 = String.format(""%s: %d Bases: %,d %s"", + group, mProj.getNumGroups(), mProj.getLength(), mProj.getAnnoStr()); + + textPanel.add(new JLabel(label2)); + } + textPanel.setMaximumSize(textPanel.getPreferredSize()); + + ProjectLinkLabel btnRemoveFromDisk = null, btnLoadOrRemove = null; + ProjectLinkLabel btnReloadAnnot = null, btnReloadSeq = null; + ProjectLinkLabel btnReloadParams = null, btnView = null; + + if (mProj.getStatus() == Mproject.STATUS_ON_DISK) { + btnRemoveFromDisk = new ProjectLinkLabel(""Remove from disk"", mProj, Color.red); + btnRemoveFromDisk.addMouseListener( doRemoveProjDisk ); + + btnLoadOrRemove = new ProjectLinkLabel(""Load project"", mProj, Color.red); + btnLoadOrRemove.addMouseListener( doLoad ); + + btnReloadParams = new ProjectLinkLabel(""Parameters"", mProj, Color.blue); + btnReloadParams.addMouseListener( doSetParamsNotLoaded ); + } + else { + btnLoadOrRemove = new ProjectLinkLabel(""Remove from database"", mProj, Color.blue); + btnLoadOrRemove.addMouseListener( doRemoveProjDB ); + + btnReloadSeq = new ProjectLinkLabel(""Reload project"", mProj, Color.blue); + btnReloadSeq.addMouseListener( doReloadSeq ); + + btnReloadAnnot = new ProjectLinkLabel(""Reload annotation"", mProj, Color.blue); + btnReloadAnnot.addMouseListener( doReloadAnnot ); + + btnReloadParams = new ProjectLinkLabel(""Parameters"", mProj, Color.blue); + btnReloadParams.addMouseListener( doReloadParams ); + + btnView = new ProjectLinkLabel(""View"", mProj, Color.blue); + btnView.addMouseListener( doViewProj ); + } + if (mProj.getStatus() == Mproject.STATUS_ON_DISK) { + if (!inReadOnlyMode) + subPanel.add( Jcomp.createHorizPanel( new Component[] + { lblTitle, btnRemoveFromDisk, btnLoadOrRemove, btnReloadParams }, 15, 0 ) ); + } + else { + if (!inReadOnlyMode) { + subPanel.add( Jcomp.createHorizPanel( new Component[] + { lblTitle, btnLoadOrRemove, btnReloadSeq, btnReloadAnnot, btnReloadParams, btnView}, 10, 0 ) ); + } + else { + subPanel.add( Jcomp.createHorizPanel( new Component[] { lblTitle, btnView}, 15, 0)); + } + } + subPanel.add( textPanel ); + subPanel.add( Box.createVerticalStrut(10) ); + } + + subPanel.setMaximumSize( subPanel.getPreferredSize() ); + JScrollPane subScroller = new JScrollPane(subPanel, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + subScroller.setAlignmentX(Component.LEFT_ALIGNMENT); + subScroller.getVerticalScrollBar().setUnitIncrement(10); + subScroller.setBorder(null); + // PreferredSize keeps it big and spread out; MinimumSize makes it really weird - maybe subPanel? + subScroller.setMaximumSize(new Dimension(MIN_WIDTH, TOP_PANEL)); + mainPanel.add( subScroller ); + + // Add alignment table; lower part + JComponent tableScroll = createPairTable(); + if (tableScroll != null) { + lblTitle = Jcomp.createLabel(""Available Syntenies"", Font.BOLD, 16); + + JTextArea text1 = new JTextArea(symapLegend, 4, 1); + + text1.setBackground( getBackground() ); + text1.setEditable(false); + text1.setLineWrap(false); + text1.setAlignmentX(Component.LEFT_ALIGNMENT); + + JTextArea text2 = new JTextArea(selectPairText,2,1); + text2.setBackground( getBackground() ); + text2.setEditable(false); + text2.setLineWrap(false); + text2.setAlignmentX(Component.LEFT_ALIGNMENT); + text2.setForeground(textColor); + + btnSelAlign = Jcomp.createButtonGray(""Selected Pair"", ""Run Align/Clust/Synteny on the selected pair""); + btnSelAlign.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + alignSelectedPair(); + } + } ); + btnSelClearPair = Jcomp.createButtonGray(""Clear Pair"", ""Remove from database, and optionally, remove MUMmer results""); + btnSelClearPair.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + btnSelClearPair.setEnabled(false);// (wheel does not stay) + Jcomp.setCursorBusy(getInstance(), true); + + removeClearPair(); + + Jcomp.setCursorBusy(getInstance(), false); + btnSelClearPair.setEnabled(true); + } + } ); + + // CAS578 removed; gives diff results and not worth it; btnAllPairs = Jcomp.createButtonGray(""All Pairs"", ""Run Align/Clust/Synteny on all pairs""); + btnSelDotplot = Jcomp.createButtonGray(""Dot Plot"", ""Display Dot Plot for selected pair""); + btnSelDotplot.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + showDotplot(); + } + }); + btnSelBlockView = Jcomp.createButtonGray(""Blocks"", ""Display Blocks View for selected pair""); + btnSelBlockView.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + showBlockView(); + } + }); + btnSelCircView = Jcomp.createButtonGray(""Circle"", ""Display Circle View for selected pair""); + btnSelCircView.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + showCircleView(); + } + }); + + btnSelReports = Jcomp.createButtonGray(""Reports..."", ""Select 'Summary' or 'Block Report'""); + showReports(); + + btnAllChrExp = Jcomp.createButtonGray(""Chromosome Explorer"", ""Select chromosomes from all pairs for the 2D display""); + btnAllChrExp.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + showChrExp(); + } + }); + btnAllDotplot = Jcomp.createButtonGray(""Dot Plot"", ""Display Dot Plot for all pairs""); + btnAllDotplot.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + showAllDotPlot(); + } + }); + btnAllQueryView = Jcomp.createButtonGray(""Queries"", ""Query all pairs""); + btnAllQueryView.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + showQuery(); + } + }); + + JPanel titleText = new JPanel(); + titleText.setLayout(new BoxLayout ( titleText, BoxLayout.Y_AXIS ) ); + titleText.add(lblTitle); + titleText.add( Box.createRigidArea(new Dimension(0,5)) ); + titleText.add(text2); + + JPanel instructText = new JPanel(); + instructText.setLayout(new BoxLayout ( instructText, BoxLayout.X_AXIS ) ); + instructText.setAlignmentX(Component.LEFT_ALIGNMENT); + instructText.add(titleText); + instructText.add(Box.createRigidArea(new Dimension(20,0))); + instructText.add(new JSeparator(SwingConstants.VERTICAL)); // + instructText.add(Box.createRigidArea(new Dimension(20,0))); + instructText.add(text1); + instructText.add(Box.createHorizontalGlue()); + instructText.setMaximumSize(instructText.getPreferredSize()); + + JLabel lbl1 = new JLabel(""Align & Synteny""); + JLabel lbl2 = new JLabel(""Selected Pair ""); + JLabel lbl3 = new JLabel(""All "" + TBL_DONE + "" Pairs""); + JLabel lbl4 = new JLabel("" ""); + Dimension d = lbl1.getPreferredSize(); + lbl2.setPreferredSize(d); lbl3.setPreferredSize(d); lbl4.setPreferredSize(d); + + totalCPUs = Runtime.getRuntime().availableProcessors(); + if (maxCPU<1) maxCPU = totalCPUs; + + txtCPUs = new JTextField(2); + txtCPUs.setMaximumSize(txtCPUs.getPreferredSize()); + txtCPUs.setMinimumSize(txtCPUs.getPreferredSize()); + txtCPUs.setText("""" + maxCPU); + + checkVB = Jcomp.createCheckBoxGray(""Verbose"",""For A&S, Verbose output to symap.log & terminal.""); // not saved + checkVB.setSelected(Constants.VERBOSE); + checkVB.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + Constants.VERBOSE = checkVB.isSelected(); + } + }); + + mainPanel.add( new JSeparator() ); + mainPanel.add( Box.createVerticalStrut(15) ); + mainPanel.add(instructText); + mainPanel.add( Box.createVerticalStrut(15) ); + + int sp=8, ex=24; + if (!inReadOnlyMode) { + Component cpu = Jcomp.createHorizPanel( new Component[] + { tableScroll, new JLabel("" CPUs:""), txtCPUs, new JLabel("" ""), checkVB}, sp, ex ); + mainPanel.add(cpu); + } + else { + mainPanel.add( Jcomp.createHorizPanel( new Component[] { tableScroll, new JLabel("" "")}, sp, ex )); + } + btnPairParams = Jcomp.createButtonGray(""Parameters"", ""Set parameters for Align&Synteny""); + btnPairParams.addActionListener(showPairProps); + + if (!inReadOnlyMode) { + mainPanel.add( Box.createRigidArea(new Dimension(0,15)) ); + mainPanel.add( Jcomp.createHorizPanel( new Component[] { lbl1, + btnSelAlign, btnSelClearPair, btnPairParams}, sp, ex) ); + } + mainPanel.add( Box.createRigidArea(new Dimension(0,15)) ); + mainPanel.add( Jcomp.createHorizPanel( new Component[] {lbl2, + btnSelCircView, btnSelDotplot, btnSelBlockView, null, btnSelReports }, sp, ex) ); + + mainPanel.add( Box.createRigidArea(new Dimension(0,15)) ); + mainPanel.add( Jcomp.createHorizPanel( new Component[] {lbl3, + btnAllChrExp, btnAllDotplot, null, btnAllQueryView }, sp, ex) ); + + mainPanel.add( Box.createRigidArea(new Dimension(0,15)) ); + mainPanel.add( Jcomp.createHorizPanel( new Component[] {lbl4 }, sp, ex) ); + } else { + mainPanel.add( Box.createVerticalGlue() ); + mainPanel.add( Jcomp.createTextArea("""",getBackground(), false) ); // kludge to fix layout problem + } + + updateEnableButtons(); + + return mainPanel; + } + + private JComponent createPairTable() { + if (pairTable != null) {// Clear previous table, disable listeners + pairTable.getSelectionModel().removeListSelectionListener(tableRowListener); + pairTable.getColumnModel().removeColumnModelListener( tableColumnListener ); + pairTable = null; + } + // Create table contents + sortProjDisplay(selectedProjVec); // sort by Display name + Vector columnNames = new Vector(); + Vector> rowData = new Vector>(); + + int maxProjName = 0; + for (Mproject p1 : selectedProjVec) { + maxProjName = Math.max(p1.getDisplayName().length(), maxProjName ); + } + String blank = """"; + for(int q = 1; q <= maxProjName + 20; q++) blank += "" ""; + + columnNames.add(blank); + + for (Mproject p1 : selectedProjVec) { + if (p1.getStatus() == Mproject.STATUS_ON_DISK) continue; // skip if not in DB + + int id1 = p1.getIdx(); + columnNames.add( p1.getDisplayName() ); + + Vector row = new Vector(); + row.add( p1.getDisplayName() ); + + for (Mproject p2 : selectedProjVec) { + if (p2.getStatus() == Mproject.STATUS_ON_DISK) continue; // skip if not in DB + int id2 = p2.getIdx(); + + Mproject[] ordP = orderProjName(p1,p2); // order indices according to DB pairs table + String resultDir = Constants.getNameAlignDir(ordP[0].getDBName(), ordP[1].getDBName()); + + boolean isDone=false; + + Mpair mp = getMpair(id1, id2); + if (mp!=null && mp.pairIdx>0) { + row.add(TBL_DONE); + isDone=true; + } + else if (Utils.checkDoneFile(resultDir)) { + row.add(TBL_ADONE); + } + else if (Utils.checkDoneMaybe(resultDir)>0) { + row.add( TBL_QDONE); + } + else row.add(null); + + if (!isDone) { // cannot do anything without an mpair + String key = ordP[0].getIdx() + "":"" + ordP[1].getIdx(); + if (!pairObjMap.containsKey(key)) { + mp = new Mpair(dbc2, -1, ordP[0], ordP[1], inReadOnlyMode); + pairObjMap.put(key, mp); + } + } + } + rowData.add( row ); + } + + if (rowData.size() == 0) return null; + + // Make table + pairTable = new MyTable(rowData, columnNames); + pairTable.setGridColor(Color.BLACK); + pairTable.setShowHorizontalLines(true); + pairTable.setShowVerticalLines(true); + pairTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + pairTable.setSelectionBackground(cellColor); // this is the only place this seems to matter + pairTable.setSelectionForeground(Color.BLACK); + pairTable.setCellSelectionEnabled( true ); + pairTable.setModel( new ReadOnlyTableModel(rowData, columnNames) ); + + DefaultTableCellRenderer tcr = new MyTableCellRenderer(); + tcr.setHorizontalAlignment(JLabel.CENTER); + pairTable.setDefaultRenderer( Object.class, tcr); + + TableColumn col = pairTable.getColumnModel().getColumn(0); + DefaultTableCellRenderer tcr2 = new MyTableCellRenderer(); + tcr2.setHorizontalAlignment(JLabel.LEFT); + col.setCellRenderer(tcr2); + + pairTable.getSelectionModel().addListSelectionListener( tableRowListener ); + pairTable.getColumnModel().addColumnModelListener( tableColumnListener ); + pairTable.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) {} + }); + autofitColumns(pairTable); + + // A scroll pane is needed or the column names aren't shown + JScrollPane scroller = new JScrollPane( pairTable, + JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scroller.setAlignmentX(Component.LEFT_ALIGNMENT); + Dimension tableSize = new Dimension( + (int)pairTable.getPreferredSize().getWidth(), + (int)pairTable.getPreferredSize().getHeight() + + (int)pairTable.getTableHeader().getPreferredSize().getHeight() + 2); + scroller.setPreferredSize( tableSize ); + scroller.setMaximumSize( tableSize ); + scroller.setMinimumSize( tableSize ); + scroller.setBorder( null ); + + return scroller; + } + + /*********************************************************** + * Enable function buttons; + */ + protected void updateEnableButtons() { // PairParams calls this too to update the ""Selected Pair"" button + if (pairTable == null) return; + + Mproject[] projects = getSelectedPair(); // null if nothing selected + btnPairParams.setEnabled(projects!=null); + + int numDone = getNumCompleted(false); // !ignore isSelf; + btnAllChrExp.setEnabled(numDone>0); + btnAllQueryView.setEnabled(numDone>0); // allow for isSelf + + numDone = getNumCompleted(true); // ignore isSelfs + btnAllDotplot.setEnabled(numDone>0); // this does not work for isSelf + + if ((projects!=null)) { + int nRow = pairTable.getSelectedRow(); + int nCol = pairTable.getSelectedColumn(); + String val = (String)pairTable.getValueAt(nRow, nCol); + + boolean allDone = (val!=null && val.contains(TBL_DONE)); + boolean partDone = (val!=null && (!val.contains(TBL_ADONE) || !val.contains(TBL_QDONE))); + + if (allDone) { // Similar labels in PairParams + btnSelAlign.setText(""Selected Redo""); + Mpair mp = getMpair(projects[0].getIdx(), projects[1].getIdx()); + if (mp!=null) { + if (mp.bSynOnly) btnSelAlign.setText(""Synteny Redo""); + else if (mp.bPseudo) btnSelAlign.setText(pseudoOnly); + + if (Constants.CoSET_ONLY) btnSelAlign.setText(""Collinear""); + if (Constants.NUMHITS_ONLY) btnSelAlign.setText(""NumHits""); + } + } + else { + Constants.CoSET_ONLY = Constants.NUMHITS_ONLY = false; + btnSelAlign.setText(""Selected Pair""); + } + + btnSelAlign.setEnabled(true); + btnSelClearPair.setEnabled(allDone || partDone); + btnSelDotplot.setEnabled( allDone ); + btnSelCircView.setEnabled(allDone); + btnSelReports.setEnabled(allDone); + btnSelBlockView.setEnabled(allDone); + } + else { + btnSelAlign.setEnabled(false); + btnSelClearPair.setEnabled(false); + btnSelDotplot.setEnabled(false); + btnSelCircView.setEnabled(false); + btnSelReports.setEnabled(false); + btnSelBlockView.setEnabled(false); + } + } + + // how many are done; first column is project names + private int getNumCompleted(boolean ignSelf) { + int count = 0; + for (int row = 0; row < pairTable.getRowCount(); row++) { + for (int col = 0; col < pairTable.getColumnCount(); col++) { + if (col > (row+1)) continue; + if (ignSelf && (row+1)==col) continue; + + String val = (String)pairTable.getValueAt(row, col); + if (val != null && val.contains(TBL_DONE)) count++; + } + } + return count; + } + + /***************************************************************** + * Create projVec, projObjMap, projNameMap - from DB and disk + */ + private void loadProjectsFromDB() { + try { + projVec.clear(); + projObjMap.clear(); + projNameMap.clear(); + + ResultSet rs = dbc2.executeQuery(""SELECT idx, name, annotdate FROM projects""); + while ( rs.next() ) { + int nIdx = rs.getInt(1); + String dbName = rs.getString(2); + String strDate = rs.getString(3); + + Mproject mp = new Mproject(dbc2, nIdx, dbName, strDate); + projVec.add(mp); + } + rs.close(); + + for (Mproject mp : projVec) { + mp.loadParamsFromDB(); // load from DB and then overwrites from file + mp.loadDataFromDB(); + projObjMap.put(mp.strDisplayName, mp); + projNameMap.put(mp.strDBName, mp.strDisplayName); + } + } + catch (Exception e) {ErrorReport.print(e,""Load projects""); } + } + private void loadProjectsFromDisk(String strDataPath, String dirName) { + File root = new File(strDataPath + dirName); + if (root == null || !root.isDirectory()) return; + + for (File f : root.listFiles()) { + if (f.isDirectory() && !f.getName().startsWith(""."")) { + String dbname = f.getName(); + if (projNameMap.containsKey(dbname)) continue; // loaded project; this is not case-sensitive + + Mproject mp = new Mproject(dbc2, -1, dbname, """"); + mp.loadParamsFromDisk(f); + + if (!projObjMap.containsKey(mp.strDisplayName)) { + projVec.add(mp); + projObjMap.put(mp.strDisplayName, mp); + projNameMap.put(mp.strDBName, mp.strDisplayName); + } + else { // e.g. dbname=Arab, and there is dbname=zarab with Display name = Arab + String msg= dbname + "": Display name '"" + mp.strDisplayName + ""' exists; cannot display""; + Mproject ex = projObjMap.get(mp.strDisplayName); + msg += ""\n Existing project with display name: Directory "" + ex.getDBName(); + + Popup.showWarningMessage(msg); + } + } + } + } + private void loadPairsFromDB() { + try { + pairObjMap.clear(); + + HashMap pairs = new HashMap (); + + // aligned is always 1; pair is not in database until Synteny step; to see if alignment is one, check file all.done + ResultSet rs = dbc2.executeQuery(""SELECT idx, proj1_idx, proj2_idx FROM pairs where aligned=1""); + + while (rs.next()) { + int pairIdx = rs.getInt(1); + int proj1Idx = rs.getInt(2); + int proj2Idx = rs.getInt(3); + + pairs.put(pairIdx, proj1Idx + "":"" + proj2Idx); + } + rs.close(); + + for (int pidx : pairs.keySet()) { + String [] tmp = pairs.get(pidx).split("":""); + int proj1Idx = Utilities.getInt(tmp[0]); + int proj2Idx = Utilities.getInt(tmp[1]); + + Mproject mp1=null, mp2=null; + for (Mproject mp : projVec) { + if (mp.getIdx() == proj1Idx) mp1 = mp; + if (mp.getIdx() == proj2Idx) mp2 = mp; + } + if (mp1==null || mp2==null) System.out.println(""SYMAP error: no "" + pidx + "" projects""); + else { + Mpair mp = new Mpair(dbc2, pidx, mp1, mp2, inReadOnlyMode); // reads database + pairObjMap.put(proj1Idx + "":"" + proj2Idx, mp); // do not know if proj1Idx>proj2Idx or proj1Idx catSet = new TreeSet (); + for (Mproject mp : projVec) { + if (mp.hasCat()) { + String cat = mp.getdbCat(); + if (!catSet.contains(cat)) catSet.add(cat); + } + } + int len = (!catSet.contains(ProjParams.catUncat)) ? catSet.size()+1 : catSet.size(); + String [] catArr = new String [len]; + int i=0; + for (String cat : catSet) catArr[i++] = cat; + if (!catSet.contains(ProjParams.catUncat)) catArr[i] = ProjParams.catUncat; // default + + return catArr; + } + private boolean isAlignDone(Mproject[] projects) { + if (projects==null) return false; + + int nRow = pairTable.getSelectedRow(); + int nCol = pairTable.getSelectedColumn(); + String val = (String)pairTable.getValueAt(nRow, nCol); + + return (val!=null && (val.contains(TBL_ADONE) || val.contains(TBL_DONE))); + } + // Get Mpair from two projects; self-synteny will have idx1=idx2; Also used by QueryFrame + public Mpair getMpair(int idx1, int idx2) { // projIdx + String key = idx1 + "":"" + idx2; + if (pairObjMap.containsKey(key)) return pairObjMap.get(key); + + key = idx2 + "":"" + idx1; // order can be either + if (pairObjMap.containsKey(key)) return pairObjMap.get(key); + + return null; // it is okay to be null; n1 and n2 do not have pair in database + } + + private Mproject[] getSelectedPair() { + if (pairTable == null) return null; + + int nRow=-1, nCol=-1; + try { + nRow = pairTable.getSelectedRow(); // Row is >=0 Col is >=1 + nCol = pairTable.getSelectedColumn(); + + // If none selected, automatically select one if 1 or 2 rows; works for isSelf + if (nRow < 0 || nCol <= 0) { + int n = pairTable.getRowCount(); + if (n!=1 && n!=2) return null; + + nCol=1; + if (n==1) nRow=0; + else nRow=1; + pairTable.setRowSelectionInterval(nRow, nRow); + pairTable.setColumnSelectionInterval(nCol, nCol); + } + + String strRowProjName = pairTable.getValueAt(nRow, 0).toString(); + String strColProjName = pairTable.getValueAt(nCol-1, 0).toString(); + + Mproject p1 = projObjMap.get(strRowProjName); + Mproject p2 = projObjMap.get(strColProjName); + + if (p1==null || p1.getIdx()==-1) { + System.out.println(strRowProjName + "": Inconsistency with the Display Name; try save project params""); + if (p1!=null) p1.prtInfo(); + return null; + } + if (p2==null || p2.getIdx()==-1) { + System.out.println(strColProjName + "": Inconsistency with the Display Name; try save project params""); + if (p2!=null) p2.prtInfo(); + return null; + } + return orderProjName(p1,p2); + } + catch (Exception e) {ErrorReport.print(e, ""Could not get row "" + nRow + "" and column "" + nCol); return null;} + } + + // XXX sort for getting pair indices in right order + private Mproject[] orderProjName(Mproject p1, Mproject p2){ + if (p1.strDBName.compareToIgnoreCase(p2.strDBName) > 0) // make alphabetic + return new Mproject[] { p2, p1 }; + else + return new Mproject[] { p1, p2 }; + } + // Order shown on manager by display name + private void sortProjDisplay(Vector projVec) { + Collections.sort( projVec, new Comparator() { + public int compare(Mproject p1, Mproject p2) { + return p1.strDisplayName.compareTo( p2.strDisplayName ); + } + }); + } + /***************************************************************/ + // log file for load + private boolean first=true; + private FileWriter openLoadLog() { + FileWriter ret = null; + try { + String name = dbName + ""_"" + Constants.loadLog; + + File pd = new File(Constants.logDir); + if (!pd.isDirectory()) pd.mkdir(); + + File lf = new File(pd,name); + if (!lf.exists()) + System.out.println(""Create log file: "" + Constants.logDir + name); + else if (first) { + System.out.println(""Append to log file: "" + Constants.logDir + name + + "" (Length: "" + Utilities.kMText(lf.length()) + "")""); + first=false; + } + ret = new FileWriter(lf, true); + } + catch (Exception e) {ErrorReport.print(e, ""Creating log file"");} + return ret; + } + + private ManagerFrame getInstance() { return this; } + + + /*********************************************************************** + **************************************************/ + private DBconn2 makeDBconn() { + // Check variables + String paramsfile = Globals.MAIN_PARAMS; + + dbProps = new PropertiesReader(new File(paramsfile)); // already checked in SyMAPmanager + + String db_server = dbProps.getProperty(""db_server""); + String db_name = dbProps.getProperty(""db_name""); + String db_adminuser = dbProps.getProperty(""db_adminuser""); // note: user needs write access + String db_adminpasswd = dbProps.getProperty(""db_adminpasswd""); + String db_clientuser = dbProps.getProperty(""db_clientuser""); + String db_clientpasswd = dbProps.getProperty(""db_clientpasswd""); + String cpus = dbProps.getProperty(""nCPUs""); + + if (db_server != null) db_server = db_server.trim(); + if (db_name != null) db_name = db_name.trim(); + if (db_adminuser != null) db_adminuser = db_adminuser.trim(); + if (db_adminpasswd != null) db_adminpasswd = db_adminpasswd.trim(); + if (db_clientuser != null) db_clientuser = db_clientuser.trim(); + if (db_clientpasswd != null) db_clientpasswd = db_clientpasswd.trim(); + + if (Utilities.isEmpty(db_server)) db_server = ""localhost""; + if (Utilities.isEmpty(db_name)) db_name = ""symap""; + + dbName = db_name; + frameTitle += "" - "" + db_name; + setTitle(frameTitle); + System.out.println("" SyMAP database: "" + db_name); // comes after Configuration file printed in SyMAPmanager.setArch + + try { + if (inReadOnlyMode) { + if (Utilities.isEmpty(db_clientuser)) { + if (Utilities.isEmpty(db_adminuser)) ErrorReport.die(""No db_adminuser or db_clientuser in "" + paramsfile); + else db_clientuser = db_adminuser; + } + if (Utilities.isEmpty(db_clientpasswd)) { + if (Utilities.isEmpty(db_adminpasswd)) ErrorReport.die(""No db_adminpasswd or db_clientpasswd in "" + paramsfile); + else db_clientpasswd = db_adminpasswd; + } + } + else { + if (Utilities.isEmpty(db_adminuser)) ErrorReport.die(""No db_adminuser defined in "" + paramsfile); + if (Utilities.isEmpty(db_adminpasswd)) ErrorReport.die(""No db_adminpasswd defined in "" + paramsfile); + } + + if (cpus!=null && maxCPU<=0) { // -p takes precedence + try { + maxCPU = Integer.parseInt(cpus.trim()); + totalCPUs = Runtime.getRuntime().availableProcessors(); + System.out.println("" Max CPUs: "" + maxCPU + "" (out of "" + totalCPUs + "" available)""); + } + catch (Exception e){ System.err.println(""nCPUs: "" + cpus + "" is not an integer. Ignoring."");} + } + + // Check database exists or create + int rc=1; // 0 create, 1 exists + if (inReadOnlyMode) { + if (!DBconn2.existDatabase(db_server, db_name, db_clientuser, db_clientpasswd)) + ErrorReport.die(""*** Database '"" + db_name + ""' does not exist""); + } + else { + rc = DBconn2.createDatabase(db_server, db_name, db_adminuser, db_adminpasswd); + if (rc == -1) ErrorReport.die(DB_ERROR_MSG); + } + + String user = (inReadOnlyMode ? db_clientuser : db_adminuser); + String pw = (inReadOnlyMode ? db_clientpasswd : db_adminpasswd); + + DBconn2 dbc = new DBconn2(""Manager"", db_server, db_name, user, pw); + if (rc==0) dbc.checkVariables(true); + + return dbc; + } + catch (Exception e) {ErrorReport.die(""Error getting connection""); } + return null; + } + + /***********************************************************************/ + private void showChrExp() { + Jcomp.setCursorBusy(this, true); + try { + ChrExpInit symapExp = new ChrExpInit(frameTitle + "" - ChrExp"", dbc2, selectedProjVec); + + symapExp.getExpFrame().setVisible(true); + } + catch (Exception err) {ErrorReport.print(err, ""Show SyMAP graphical window"");} + finally { + Jcomp.setCursorBusy(this, false); + } + } + /*********************************************************************/ + private void showQuery() { + Jcomp.setCursorBusy(this, true); + try { + Vector pVec = new Vector (); + for (Mproject p : selectedProjVec) + if (p.hasSynteny()) pVec.add(p); + + boolean isSelf = (selectedProjVec.size()==1 && pVec.size()==1);// self synteny + if (isSelf) pVec.add(pVec.get(0)); // this makes the following loop work for counts + + boolean useAlgo2=true; // used for Exon/Gene Olap column + int cntUsePseudo=0; // Instructions; + int hasSynteny=0; + Vector synVec = new Vector (); // should end up the same as pVec + + for (int i=0; i 1) projYIdx = p[1].getID(); + + DotPlotFrame frame = new DotPlotFrame(frameTitle+ "" - Dot Plot"", dbc2, projXIdx, projYIdx); + frame.setSize( new Dimension(MIN_WIDTH, MIN_HEIGHT) ); + frame.setVisible(true); + + Jcomp.setCursorBusy(this, false); + } + /*****************************************************************/ + private void showBlockView() { + Jcomp.setCursorBusy(this, true); + + Mproject[] p = getSelectedPair(); + if (p==null) return; + + Mproject p1=p[0]; + Mproject p2 = (p.length>1) ? p[1] : p[0]; + + try{ + BlockViewFrame frame = new BlockViewFrame(frameTitle + "" - Block"", dbc2, p1.getIdx(), p2.getIdx()); + frame.setMinimumSize( new Dimension(MIN_WIDTH, MIN_HEIGHT) ); + frame.setVisible(true); + } + catch (Exception e) {ErrorReport.die(e, ""Show block view""); + } + + Jcomp.setCursorBusy(this, false); + } + /*****************************************************************/ + private void showReports() { + JPopupMenu popup = new JPopupMenu(); + + JMenuItem popupTitle = new JMenuItem(); + popupTitle.setText(""Select Report""); + popupTitle.setEnabled(false); + popup.add(popupTitle); + popup.addSeparator(); + + JMenuItem menuItem1 = new JMenuItem(""Summary""); + JMenuItem menuItem2 = new JMenuItem(""Block Report""); + JMenuItem menuItem3 = new JMenuItem(""Cancel""); + + popup.add(menuItem1); popup.addSeparator(); + popup.add(menuItem2); popup.addSeparator(); + popup.add(menuItem3); + + menuItem1.addActionListener(e -> { + showSummary(); + }); + menuItem2.addActionListener(e -> { + showReport(); + }); + menuItem3.addActionListener(e -> { + + }); + + btnSelReports.setComponentPopupMenu(popup); + btnSelReports.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + popup.show(e.getComponent(), e.getX(), e.getY()); + } + }); + } + private void showSummary(){ + Jcomp.setCursorBusy(this, true); + + Mproject[] p = getSelectedPair(); + if (p==null) return; + + int projXIdx = p[0].getIdx(); + int projYIdx = (p.length>1) ? p[1].getIdx() : projXIdx; + + Mpair mp = getMpair(projXIdx, projYIdx); + if (mp==null) return; + + new SumFrame(frameTitle + "" - Summary"", dbc2, mp, inReadOnlyMode); // dialog made visible in SumFrame; + + Jcomp.setCursorBusy(this, false); + } + private void showReport(){ + Jcomp.setCursorBusy(this, true); + + Mproject[] p = getSelectedPair(); + if (p==null) return; + + int projXIdx = p[0].getIdx(); + int projYIdx = (p.length>1) ? p[1].getIdx() : projXIdx; + + Mpair mp = getMpair(projXIdx, projYIdx); + if (mp==null) return; + + new Report(dbc2, p, mp); // dialog made visible in Report; + + Jcomp.setCursorBusy(this, false); + } + /*****************************************************************/ + private void showCircleView() { + Jcomp.setCursorBusy(this, true); + + Mproject[] p = getSelectedPair(); + if (p==null) return; + + int projXIdx = p[0].getID(); + int projYIdx = (p.length > 1) ? p[1].getID() : projXIdx; // 2-align : self-align + boolean hasSelf = (p[0].hasSelf() || p[1].hasSelf()); + + if (projYIdx == projXIdx) projYIdx = 0; + + CircFrame frame = new CircFrame(frameTitle + "" - Circle"", dbc2, projXIdx, projYIdx, hasSelf); + frame.setSize( new Dimension(MIN_CWIDTH, MIN_CHEIGHT) ); + frame.setVisible(true); + + Jcomp.setCursorBusy(this, false); + } + /*****************************************************************/ + private void showAllDotPlot() { + int nProj = 0; + for (Mproject p : selectedProjVec) { + if (p.getStatus() != Mproject.STATUS_ON_DISK) { + nProj++; + } + } + int[] pids = new int[nProj]; + int i = 0; + for (Mproject p : selectedProjVec) { + if (p.getStatus() != Mproject.STATUS_ON_DISK) { + pids[i] = p.getID(); + i++; + } + } + DotPlotFrame frame = new DotPlotFrame(frameTitle + "" - Dot Plot"", dbc2, pids, null, null, null, true); + frame.setSize( new Dimension(MIN_WIDTH, MIN_HEIGHT) ); + frame.setVisible(true); + } + + /************* XXX Listeners ********************/ + private ItemListener checkboxListener = new ItemListener() { // left panel change + public void itemStateChanged(ItemEvent e) { + ProjectCheckBox cb = (ProjectCheckBox)e.getSource(); + Mproject p = cb.getProject(); + boolean changed = false; + + if ( e.getStateChange() == ItemEvent.SELECTED ) { + if ( !selectedProjVec.contains(p) ) selectedProjVec.add(p); + cb.setBackground(cellColor); // highlight + changed = true; + } + else if ( e.getStateChange() == ItemEvent.DESELECTED ) { + selectedProjVec.remove(p); + cb.setBackground(Color.white); // un-highlight + changed = true; + } + + if (changed) { + sortProjDisplay( selectedProjVec ); + if (pairTable != null) pairTable.clearSelection(); + + // Note: recreating each time thrashes heap, but probably negligible performance impact + if ( selectedProjVec.size() > 0 ) + splitPane.setRightComponent( createSelectedPanel() ); // regenerate since changed + else + splitPane.setRightComponent( instructionsPanel ); + } + } + }; + private ActionListener showPairProps = new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + Mproject[] sel = getSelectedPair(); + + Mpair p = getMpair(sel[0].getIdx(), sel[1].getIdx()); + if (p!=null) { + boolean algDone = isAlignDone(sel); + ppFrame = new PairParams(p, getInstance(), algDone); + ppFrame.setVisible(true); + } + else Globals.eprt(""SyMAP error: cannot get pair "" + sel[0].getIdx() + "" "" + sel[1].getIdx() ); + } + }; + /*************************************************************** + * Project links + */ + private MouseListener doRemoveProjDB = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mp = ((ProjectLinkLabel)e.getSource()).getProject(); + new RemoveProj(openLoadLog()).removeProjectDB(mp); + refreshMenu(); + } + }; + private MouseListener doRemoveProjDisk = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mp = ((ProjectLinkLabel)e.getSource()).getProject(); + new RemoveProj(openLoadLog()).removeProjectDisk(mp); + refreshMenu(); + } + }; + + private MouseListener doLoadAllProj = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + loadAllProjects(); + } + }; + private MouseListener doLoad = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mproj = ((ProjectLinkLabel)e.getSource()).getProject(); + loadProject(mproj); + } + }; + private MouseListener doReloadSeq = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mproj = ((ProjectLinkLabel)e.getSource()).getProject(); + reloadProject(mproj); + } + }; + private MouseListener doReloadAnnot = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mproj = ((ProjectLinkLabel)e.getSource()).getProject(); + reloadAnno(mproj); + } + }; + + private MouseListener doReloadParams = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mProj = ((ProjectLinkLabel)e.getSource()).getProject(); + + ProjParams propFrame = new ProjParams(getInstance(), mProj, projVec, getCatArr(), + true, mProj.hasExistingAlignments(true)); // only exist true if /align + propFrame.setVisible(true); + + if (propFrame.wasSave()) refreshMenu(); + } + }; + private MouseListener doSetParamsNotLoaded = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject mProj = ((ProjectLinkLabel)e.getSource()).getProject(); + + ProjParams propFrame = new ProjParams(getInstance(), mProj, projVec, getCatArr(), + false, mProj.hasExistingAlignments(true)); // only exist true if /align + propFrame.setVisible(true); + + if (propFrame.wasSave()) refreshMenu(); + } + }; + + private MouseListener doViewProj = new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + Mproject theProject = ((ProjectLinkLabel)e.getSource()).getProject(); + String info = theProject.loadProjectForView(); + + Popup.displayInfoMonoSpace(getInstance(), ""View "" + theProject.getDisplayName(), info, false); + } + }; + private void removeClearPair() { + Mproject[] mprojs = getSelectedPair(); + if (mprojs==null) return; + + Mpair mp = getMpair(mprojs[0].getIdx(),mprojs[1].getIdx()); + RemoveProj rpObj = new RemoveProj(openLoadLog()); + rpObj.removeClearPair(mprojs[0], mprojs[1], mp); + + refreshMenu(); + } + /*****************************************************************/ + /*************************************************************** + * XXX LoadProj: + */ + private void loadAllProjects() { + try { + DoLoadProj lpObj = new DoLoadProj(this, dbc2, openLoadLog()); + lpObj.loadAllProjects(selectedProjVec); // All + + new Version(dbc2).updateReplaceProp(); + refreshMenu(); + } + catch (Exception e) {ErrorReport.print(e, ""load all project"");} + } + private void loadProject(Mproject mProj) { + try { + DoLoadProj lpObj = new DoLoadProj(this, dbc2, openLoadLog()); + lpObj.loadProject(mProj); // just this one + + new Version(dbc2).updateReplaceProp(); + refreshMenu(); + } + catch (Exception e) {ErrorReport.print(e, ""load project"");} + } + private void reloadProject(Mproject mProj) { + try { + RemoveProj rpObj = new RemoveProj(openLoadLog()); + if (!rpObj.reloadProject(mProj)) return; + + DoLoadProj lpObj= new DoLoadProj(this, dbc2, openLoadLog()); + lpObj.loadProject(mProj); + + new Version(dbc2).updateReplaceProp(); + refreshMenu(); + } + catch (Exception e) {ErrorReport.print(e, ""reload project"");} + } + // Reload + private void reloadAnno(Mproject mProj) { + try { + String msg = ""Reload annotation "" + mProj.getDisplayName(); + + if (!Popup.showConfirm2(""Reload annotation"", msg + + ""\n\nYou will need to re-run the synteny computations for this project,"" + + ""\nany existing alignment files will be used."")) return; + + System.out.println(""Removing "" + mProj.getDisplayName() + "" annotation from database....""); + mProj.removeAnnoFromDB(); + + DoLoadProj lpObj= new DoLoadProj(this, dbc2, openLoadLog()); + lpObj.reloadAnno(mProj); + + new Version(dbc2).updateReplaceProp(); + refreshMenu(); + } + catch (Exception e) {ErrorReport.print(e, ""reload project"");} + } + + /***************************************************** + * Align selected pair + */ + private void alignSelectedPair( ) { + Mproject[] selProjs = getSelectedPair(); + if (selProjs==null) return; + + int nCPU = getCPUs(); + if (nCPU == -1) return; // it says to enter valid number in getCPU; + if (!alignCheckProjDir()) return; // error written in calling routine + + Mpair mp = getMpair(selProjs[0].getIdx(), selProjs[1].getIdx()); + if (mp==null) return; // shouldn't happen + + String title; + if (selProjs[0].getIdx()==selProjs[1].getIdx()) { // isSelf + title = selProjs[0].getDisplayName() + "" to itself""; + if (mp.isAlgo2(Mpair.FILE)) { // is disabled, but could get changed in file + Popup.showInfoMessage(title, ""Please select Algorithm 1 from Parameters""); + return; + } + } + else title = selProjs[0].getDisplayName() + "" and "" + selProjs[1].getDisplayName(); // Pair + + // Special cases + if (mp.bPseudo) { + if (!Popup.showConfirm2(title, ""Pseudo only"")) return; + + new DoAlignSynPair().run(getInstance(), dbc2, mp, false, nCPU, true); // align has been done + new Version(dbc2).updateReplaceProp(); + return; + } + if (!alignCheckOrderAgainst(mp)) return; + + // Compose confirm popup + boolean bAlignDone = isAlignDone(selProjs); + + String msg; + if (mp.bSynOnly) msg = ""Synteny Only"" + ""\n"" + mp.getChgSynteny(Mpair.FILE) + ""\n""; + else if (bAlignDone) { // must check command line only if all done + if (Constants.CoSET_ONLY) msg = ""Collinear Only\n""; // For v5.7.7, flag -cs; CAS577 + else if (Constants.NUMHITS_ONLY) msg = ""NumHits Only\n""; // For v5.7.9c,flag -nh; CAS579c + else msg = ""Clust&Synteny""+ ""\n"" + mp.getChgClustSyn(Mpair.FILE) + ""\n""; + } + else msg = ""Align&Synteny""+ ""\n"" + mp.getChgAllParams(Mpair.FILE) + ""\n""; + + if (!bAlignDone) msg += ""CPUs "" + nCPU + ""; ""; + + if (Constants.VERBOSE) msg += ""Verbose On""; else msg += ""Verbose Off""; + + if (!Popup.showConfirm2(title, msg)) return; + + /*--- Do Alignment, Clustering, Synteny (alignments will not happen if exists) ----*/ + + new DoAlignSynPair().run(getInstance(), dbc2, mp, false, nCPU, bAlignDone); + + new Version(dbc2).updateReplaceProp(); + } + + private int getCPUs() { + try { maxCPU = Integer.parseInt(txtCPUs.getText()); } + catch (Exception e) { + Popup.showErrorMessage(""Please enter a valid value for number of CPUs to use.""); + return -1; + } + if (maxCPU <= 0) maxCPU = 1; + return maxCPU; + } + // Create directories if alignment is initiated; + // An alignment may be in the database, yet no /data directory. The files will be rewritten, so the directories are needed. + private boolean alignCheckProjDir() { + try { + FileDir.checkCreateDir(DATA_PATH, true); + FileDir.checkCreateDir(Constants.seqRunDir, true); + FileDir.checkCreateDir(Constants.seqDataDir, true); + + return true; + } + catch (Exception e){return false;} + } + // Checks before starting order against project; + private boolean alignCheckOrderAgainst(Mpair mp) { + if (!mp.isOrder1(Mpair.FILE) && !mp.isOrder2(Mpair.FILE)) return true; + + try { + String ordProjName = Constants.getOrderDir(mp); + if (ordProjName==null) return true; + + String ordDirName = Constants.seqDataDir + ordProjName; + File ordDir = new File(ordDirName); + + if (ordDir.exists()) { + String msg = ""Directory exists: "" + ordDirName + ""\nIt will be over-written.\n""; + if (!Popup.showContinue(""Order against"", msg)) return false; + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Checking order against""); return false;} + } + + /**************************************************************************/ +// *** Begin table customizations ****************************************** + public void autofitColumns(JTable tbl) { + TableModel model = tbl.getModel(); + TableColumn column; + Component comp; + int headerWidth; + int cellWidth; + TableCellRenderer headerRenderer = tbl.getTableHeader().getDefaultRenderer(); + + for (int i = 0; i < tbl.getModel().getColumnCount(); i++) { // for each column + column = tbl.getColumnModel().getColumn(i); + + comp = headerRenderer.getTableCellRendererComponent( + tbl, column.getHeaderValue(), false, false, 0, i); + + headerWidth = comp.getPreferredSize().width + 10; + + cellWidth = 0; + for (int j = 0; j < tbl.getModel().getRowCount(); j++) { // for each row + comp = tbl.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent( + tbl, model.getValueAt(j, i), + false, false, j, i); + cellWidth = Math.max(cellWidth, comp.getPreferredSize().width); + if(model.getColumnClass(i) == String.class) cellWidth += 5; //Strings need to be adjusted + if (j > 100) break; // only check beginning rows, for performance reasons + } + + column.setPreferredWidth(Math.min(Math.max(headerWidth, cellWidth), 200)); + } + } + private class MyTable extends JTable { + public MyTable(Vector > rowData, Vector columnNames) { + super(rowData, columnNames); + } + + public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) { + if (columnIndex > 0 && columnIndex <= rowIndex + 1) + super.changeSelection(rowIndex, columnIndex, toggle, extend); + } + } + private ListSelectionListener tableRowListener = new ListSelectionListener() { // called before tableColumnListener + public void valueChanged(ListSelectionEvent e) { + if (!e.getValueIsAdjusting()) + updateEnableButtons(); + } + }; + private TableColumnModelListener tableColumnListener = new TableColumnModelListener() { // called after tableRowListener + public void columnAdded(TableColumnModelEvent e) { } + public void columnMarginChanged(ChangeEvent e) { } + public void columnMoved(TableColumnModelEvent e) { } + public void columnRemoved(TableColumnModelEvent e) { } + public void columnSelectionChanged(ListSelectionEvent e) { + if (!e.getValueIsAdjusting()) + updateEnableButtons(); + } + + }; + private class ReadOnlyTableModel extends DefaultTableModel { + public ReadOnlyTableModel(Vector> rowData, Vector columnNames) { super(rowData, columnNames); } + public boolean isCellEditable(int row, int column) { return false; } + } + + private class MyTableCellRenderer extends DefaultTableCellRenderer { + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, int row, int column) + { + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + + if (column == 0 ) { + setBackground( UIManager.getColor(""TableHeader.background"") ); + } + else if (column > row + 1) { + setBackground(new Color(217,217,217)); + } + else if (!isSelected) + setBackground(null); + return this; + } + } + public void componentResized(ComponentEvent e) { + int width = getWidth(); + int height = getHeight(); + if (width < MIN_WIDTH) width = MIN_WIDTH; + if (height < MIN_HEIGHT) height = MIN_HEIGHT; + setSize(width, height); + } + public void componentMoved(ComponentEvent e) { } + public void componentShown(ComponentEvent e) { } + public void componentHidden(ComponentEvent e) { } + + // *** End table customizations ******************************************** + + /************** Classes *************************************/ + /** Add a project **/ + private class AddProjectPanel extends JDialog { + public AddProjectPanel() { + setModal(true); + setResizable(false); + getContentPane().setBackground(Color.WHITE); + setTitle(""Add Project""); + + pnlMainPanel = new JPanel(); + pnlMainPanel.setLayout(new BoxLayout(pnlMainPanel, BoxLayout.PAGE_AXIS)); + pnlMainPanel.setBackground(Color.WHITE); + + projName = new JTextField(15); + projName.setAlignmentX(Component.LEFT_ALIGNMENT); + projName.setMaximumSize(projName.getPreferredSize()); + projName.setMinimumSize(projName.getPreferredSize()); + + btnAdd = new JButton(""Add""); + btnAdd.setBackground(Color.WHITE); + btnAdd.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (isAddValid()) + dispose(); + } + }); + btnAdd.setEnabled(true); + + btnCancel = new JButton(""Cancel""); + btnCancel.setBackground(Color.WHITE); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + projName.setText(""""); + dispose(); + } + }); + btnAdd.setPreferredSize(btnCancel.getPreferredSize()); + btnAdd.setMinimumSize(btnCancel.getPreferredSize()); + btnAdd.setMaximumSize(btnCancel.getPreferredSize()); + + JButton btnHelp = Jhtml.createHelpIconSysSm(Jhtml.SYS_GUIDE_URL, Jhtml.create); + + JPanel tempRow = new JPanel(); + tempRow.setLayout(new BoxLayout(tempRow, BoxLayout.LINE_AXIS)); + tempRow.setAlignmentX(Component.CENTER_ALIGNMENT); + tempRow.setBackground(Color.WHITE); + + tempRow.add(new JLabel(""Name:"")); + tempRow.add(Box.createHorizontalStrut(5)); + tempRow.add(projName); + + tempRow.setMaximumSize(tempRow.getPreferredSize()); + + pnlMainPanel.add(Box.createVerticalStrut(10)); + pnlMainPanel.add(tempRow); + + tempRow = new JPanel(); + tempRow.setLayout(new BoxLayout(tempRow, BoxLayout.LINE_AXIS)); + tempRow.setAlignmentX(Component.CENTER_ALIGNMENT); + tempRow.setBackground(Color.WHITE); + + tempRow.add(btnAdd); + tempRow.add(Box.createHorizontalStrut(20)); + tempRow.add(btnCancel); + tempRow.add(Box.createHorizontalStrut(20)); + tempRow.add(btnHelp); + + pnlMainPanel.add(Box.createVerticalStrut(30)); + pnlMainPanel.add(tempRow); + + pnlMainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + pnlMainPanel.setMaximumSize(pnlMainPanel.getPreferredSize()); + pnlMainPanel.setMinimumSize(pnlMainPanel.getPreferredSize()); + + add(pnlMainPanel); + + pack(); + } + + private void reset() { + projName.setText(""""); + btnAdd.setEnabled(true); + } + + private boolean isAddValid() { + String name = projName.getText().trim(); + if (name.length()==0) { + Popup.showErrorMsg(""Must enter a name""); + return false; + } + if (!name.matches(""^[\\w]+$"")) { + Popup.showErrorMsg(""Name must be characters, numbers or underscore""); + return false; + } + String dir = Constants.seqDataDir + name; + if (FileDir.dirExists(dir)) { + Popup.showErrorMsg(""Directory exists: "" + name); + return false; + } + // linux is case-insensitive - so the above check passes for foobar and FooBar + for (String dirx : projNameMap.keySet()) {// projNameMap.containsKey() is case-insensitive + if (name.equalsIgnoreCase(dirx)) { + Popup.showWarningMessage(""Project with directory '"" + name + ""' exists""); + return false; + } + } + + // Create /data in case it does not exist + String strDataPath = DATA_PATH; + FileDir.checkCreateDir(strDataPath, true); + FileDir.checkCreateDir(Constants.seqDataDir, true /* bPrt */); + FileDir.checkCreateDir(Constants.seqRunDir, true); + + // CAS578 was adding even if illegal or blank; + // was being done in a listener elsewhere in the code, and a separate method + FileDir.checkCreateDir(dir, true); + refreshMenu(); + + return true; + } + private JButton btnAdd = null, btnCancel = null; + private JTextField projName = null; + private JPanel pnlMainPanel = null; + } + + private class ProjectLinkLabel extends LinkLabel { + private Mproject project; // associated project + + public ProjectLinkLabel(String text, Mproject project, Color c) { + super(text, c.darker().darker(), c); + this.project = project; + } + + public Mproject getProject() { return project; } + } + + private class ProjectCheckBox extends JCheckBox { + private Mproject project = null; // associated project + + public ProjectCheckBox(String text, Mproject p) { + super(text); + project = p; + setFocusPainted(false); + if (selectedProjVec.contains(p)) { + setSelected(true); + setBackground( cellColor); // this doesn't seem to do anything, see createPairTable + } + else + setBackground( Color.white ); + addItemListener( checkboxListener ); + } + public Mproject getProject() { return project; } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/Mpair.java",".java","21434","538","package symap.manager; + +import java.io.File; +import java.io.PrintWriter; +import java.sql.ResultSet; +import java.util.HashMap; + +import backend.AnchorMain; +import backend.Constants; +import backend.Utils; +import backend.anchor1.Group; +import database.DBconn2; +import props.PropertiesReader; +import symap.Globals; +import util.ErrorReport; +import util.Utilities; +import util.FileDir; + +/********************************************************* + * this is mainly used in backend + * 1. created when enter the selectedPairTable in ManagerFrame + * 2. if new, create directory and params file; else read params file + * 3. if previously A&S, read pair_props + * 4. PairParams save - save all to file + * 5. AlignProj save - save all to db + * 6. Show file params on PairParams + * 7. Show db params on Summary + */ +public class Mpair { + public static final int FILE = 0; + public static final int DB = 1; + // sections + private static final String ALIGN = "" Align""; + private static final String ALGO1 = "" Cluster Algo1 (modified original)""; + private static final String ALGO2 = "" Cluster Algo2 (exon-intron)""; + private static final String SYNORIG = "" Synteny Original""; + private static final String SYNSTRI = "" Synteny Strict""; + private static final String spp = "" ""; // space to go before parameters; + + public Mproject mProj1, mProj2; + protected int pairIdx=-1; // accessed in ManagerFrame; + private int proj1Idx=-1, proj2Idx=-1; + private DBconn2 dbc2; + private String syVer=""""; + public boolean bPseudo=false, bSynOnly=false; // set in PairParams and read in ManagerFrame + + private String resultDir; + private HashMap fileMap = new HashMap (); + private HashMap dbMap = new HashMap (); + private HashMap defMap = new HashMap (); + private boolean isSelf=false; + + // These must be in same order as PairParam.SYMBOLS arrays; the order isn't needed anywhere else in this file + private static final String [] paramKey = { // repeated in PairParams and below + ""mindots"", ""strict_blocks"", ""same_orient"", ""merge_blocks"", + ""order_none"", ""order_proj1"", ""order_proj2"", + ""concat"", ""mask1"", ""mask2"", + ""nucmer_args"", ""promer_args"", ""self_args"", ""nucmer_only"",""promer_only"", + ""number_pseudo"",""algo1"", ""algo2"", + ""topn"", + ""gene_scale"", ""exon_scale"",""len_scale"",""g0_scale"", + ""EE_pile"", ""EI_pile"", ""En_pile"", ""II_pile"", ""In_pile"" + }; + // defMap value; not static because specific to pair, e.g. self-synteny, order, regular; CAS576 + private final int defStrict = 1, defAlgo = 16; // if annotated, [16]=0, [17]=1 + private String [] paramDef = { + ""7"", ""1"", ""0"", ""0"", // synteny: hits, strict, orient, merge; strict is default except for when there are many contigs + ""1"", ""0"", ""0"", // order against: none, proj1->proj2, proj2->proj1 + ""1"", ""0"", ""0"", // align: concat, mask1, mask2 + """", """", """", ""0"", ""0"", // nucmer, promer, self, only, only + ""0"", ""1"", ""0"", // cluster: number pseudo, 1st is algo1, 2nd is algo2 + ""2"", // topn + ""1.0"", ""1.0"", ""1.0"", ""1.0"", // gene, exon, Len, G0_Len + ""1"", ""1"", ""1"", ""0"", ""0"" // EE, EI, En, II, In + }; + + public Mpair(DBconn2 dbc2, int pairIdx, Mproject p1, Mproject p2, boolean isReadOnly) { + this.dbc2 = dbc2; + this.mProj1 = p1; // order is based on pairs table, or either can come first + this.mProj2 = p2; + this.pairIdx = pairIdx; + + proj1Idx = mProj1.getIdx(); + proj2Idx = mProj2.getIdx(); + isSelf = proj1Idx==proj2Idx; + + if (!isSelf && p1.hasGenes() && p2.hasGenes()) { // if annotated, algo2 is default + paramDef[defAlgo]=""0""; paramDef[defAlgo+1]=""1""; + } + else { + paramDef[defAlgo]=""1""; paramDef[defAlgo+1]=""0""; + } + if (p1.getNumDraft()>25 || p2.getNumDraft()>25) { // strict is not good with many small contigs, i.e. ordering + paramDef[defStrict] = ""0""; + } + String x = Constants.orderDelim; // .. also does not work welll with ordered contigs + if ((mProj1.getDBName().contains(x) || mProj2.getDBName().contains(x))) { + paramDef[defStrict] = ""0""; + } + + resultDir = ""./"" + Constants.getNameResultsDir(p1.strDBName, p2.strDBName); + + makeParams(); + if (!isReadOnly) loadFromFile(); // loads into FileMap + if (pairIdx!= -1) loadFromDB(); // loads into dbMap + + loadSyVer(); + } + + /************************************************************************************/ + // ManagerFrame.alignSelectPair popop when need align; DoAlignSynPair terminal, dialog, symap.log + public String getChgAllParams(int type) { + String amsg = getChgAlign(type, false); + String cmsg = getChgCluster(type); + String smsg = getChgSynteny(type); + + return amsg + ""\n"" + cmsg + ""\n"" + smsg; // none are empty + } + // ManagerFrame.alignSelectedPair popup when no align; DoAlignSynPair terminal, dialog, symap.log + public String getChgClustSyn(int type) { + String cmsg = getChgCluster(type); + String smsg = getChgSynteny(type); + + return cmsg + ""\n"" + smsg; + } + + public String getChgAlign(int type, boolean forSum) { + String msg=""""; + if (isChg(type,""concat"")) msg = pjoin(msg, ""No concat""); + if (isChg(type,""mask1"")) msg = pjoin(msg, ""Mask "" + mProj1.getDisplayName()); + if (isChg(type,""mask2"")) msg = pjoin(msg, ""Mask "" + mProj2.getDisplayName()); + + if (isChg(type,""promer_only"")) msg = pjoin(msg, ""PROmer only ""); + else if (isChg(type,""nucmer_only"")) msg = pjoin(msg, ""NUCmer only ""); + + if (isChg(type,""self_args"")) msg = pjoin(msg, ""Self args: "" + getSelfArgs(type)); + else if (isChg(type,""promer_args"")) msg = pjoin(msg, ""PROmer args: "" + getPromerArgs(type)); + else if (isChg(type,""nucmer_args"")) msg = pjoin(msg, ""NUCmer args: "" + getNucmerArgs(type)); + + if (!forSum && Constants.MUM_NO_RM) msg = pjoin(msg, ""Keep MUMmer .delta file""); + + if (!msg.equals("""")) { + if (msg.contains(""PROmer"") || msg.contains(""NUCmer"")) return ALIGN + ""\n"" + msg; + else if (isSelf) return ALIGN + "" NUCmer"" + ""\n"" + msg; + else return ALIGN + "" PROmer"" + ""\n"" + msg; + } + if (isSelf) return ALIGN + "" NUCmer"" ; // always remind what is being used + return ALIGN + "" PROmer""; + } + + private String getChgCluster(int type) { + String msg=""""; + if (isAlgo2(type)) { + if (isChg(type,""exon_scale"")) msg = pjoin(msg, ""Exon scale = "" + getExonScale(type)); + if (isChg(type,""gene_scale"")) msg = pjoin(msg, ""Gene scale = "" + getGeneScale(type)); + if (isChg(type,""len_scale"")) msg = pjoin(msg, ""Length scale = "" + getLenScale(type)); + if (isChg(type,""g0_scale"")) msg = pjoin(msg, ""G0 length scale = "" + getG0Scale(type)); + + if (isChg(type,""EE_pile"")) msg = pjoin(msg, ""Limit Exon-Exon piles""); + if (isChg(type,""EI_pile"")) msg = pjoin(msg, ""Limit Exon-Intron piles""); + if (isChg(type,""En_pile"")) msg = pjoin(msg, ""Limit Exon-intergenic piles""); + if (isChg(type,""II_pile"")) msg = pjoin(msg, ""Allow Intron-Intron piles""); + if (isChg(type,""In_pile"")) msg = pjoin(msg, ""Allow Intron-intergenic piles""); + if (isChg(type,""topn"")) msg = pjoin(msg, ""Top N piles = "" + getTopN(type)); + if (isChg(type,""number_pseudo"")) msg = pjoin(msg, ""Number pseudo""); + + if (msg.equals("""")) msg = ALGO2; + else msg = ALGO2 + ""\n"" + msg; + } + else if (isAlgo1(type)) { + if (isChg(type,""topn"")) msg = pjoin(msg,""Top N piles ="" + getTopN(type)); + if (Group.bSplitGene) msg = pjoin(msg,""Split gene""); + if (isChg(type,""number_pseudo"")) msg = pjoin(msg, ""Number pseudo""); // algo will come after + + if (msg.equals("""")) msg = ALGO1; + else msg = ALGO1 + ""\n"" + msg; + } + return msg; + } + // Called for A&S, C&S, and SynOnly (directly) + protected String getChgSynteny(int type) { + String msg="""", smsg=""""; + + if (isStrict(type)) smsg = SYNSTRI; + else smsg = SYNORIG; + + if (isChg(type,""mindots"")) msg = pjoin(msg, ""Min hits="" + getMinDots(type)); + if (isChg(type,""same_orient"")) msg = pjoin(msg, ""Same orient""); + if (isChg(type,""merge_blocks"")) {// has a choice of 3 where 0 is default + String idx = (type==FILE) ? fileMap.get(""merge_blocks"") : dbMap.get(""merge_blocks""); + int ix = Utilities.getInt(idx); + msg = pjoin(msg, ""Merge blocks: "" + PairParams.mergeOpts[ix]); + } + + if (isChg(type, ""order_proj1"")) msg = pjoin(msg, ""Order "" + mProj1.getDisplayName() + ""->"" + mProj2.getDisplayName()); + if (isChg(type, ""order_proj2"")) msg = pjoin(msg, ""Order "" + mProj2.getDisplayName() + ""->"" + mProj1.getDisplayName()); + + if (msg.equals("""")) return smsg; + return smsg + ""\n"" + msg; + } + + private boolean isChg(int type, String field) { + String db = (type==FILE) ? fileMap.get(field) : dbMap.get(field); + if (db==null) { + Globals.prt(""No parameter in database: "" + field); + return false; + } + String def = defMap.get(field); + if (def==null) return false; + return !db.contentEquals(def); + } + private String pjoin(String m1, String m2) { + if (!m1.equals("""") && !m1.startsWith(spp)) m1 = spp + m1; + if (!m2.equals("""") && !m2.startsWith(spp)) m2 = spp + m2; + if (m1.equals("""")) return m2; + if (m2.equals("""")) return m1; + return m1 + ""\n"" + m2; + } + /************************************************************************************/ + public int getPairIdx() {return pairIdx;} + public int getProj1Idx() { return mProj1.getIdx();} + public int getProj2Idx() { return mProj2.getIdx();} + + public Mproject getProj1() {return mProj1;} + public Mproject getProj2() {return mProj2;} + + protected boolean isPairInDB() {return pairIdx>0;} + public boolean hasSynteny() {return pairIdx>0;} // if A&S fails, it will not be in database + + public boolean isNumPseudo(int type) { + String x = (type==FILE) ? fileMap.get(""number_pseudo"") : dbMap.get(""number_pseudo""); + return x.contentEquals(""1""); + } + public boolean isAlgo1(int type) { + String x = (type==FILE) ? fileMap.get(""algo1"") : dbMap.get(""algo1""); + return x.contentEquals(""1""); + } + public int getTopN(int type) { + String x = (type==FILE) ? fileMap.get(""topn"") : dbMap.get(""topn""); + return Utilities.getInt(x); + } + public boolean isAlgo2(int type) { + String x = (type==FILE) ? fileMap.get(""algo2"") : dbMap.get(""algo2""); + return x.contentEquals(""1""); + } + public double getG0Scale(int type) { + String x = (type==FILE) ? fileMap.get(""g0_scale"") : dbMap.get(""g0_scale""); + return Utilities.getDouble(x); + } + public double getExonScale(int type) { + String x = (type==FILE) ? fileMap.get(""exon_scale"") : dbMap.get(""exon_scale""); + return Utilities.getDouble(x); + } + public double getGeneScale(int type) { + String x = (type==FILE) ? fileMap.get(""gene_scale"") : dbMap.get(""gene_scale""); + return Utilities.getDouble(x); + } + public double getLenScale(int type) { + String x = (type==FILE) ? fileMap.get(""len_scale"") : dbMap.get(""len_scale""); + return Utilities.getDouble(x); + } + public boolean isEEpile(int type) { + String x = (type==FILE) ? fileMap.get(""EE_pile"") : dbMap.get(""EE_pile""); + return x.contentEquals(""1""); + } + public boolean isEIpile(int type) { + String x = (type==FILE) ? fileMap.get(""EI_pile"") : dbMap.get(""EI_pile""); + return x.contentEquals(""1""); + } + public boolean isEnpile(int type) { + String x = (type==FILE) ? fileMap.get(""En_pile"") : dbMap.get(""En_pile""); + return x.contentEquals(""1""); + } + public boolean isIIpile(int type) { + String x = (type==FILE) ? fileMap.get(""II_pile"") : dbMap.get(""II_pile""); + return x.contentEquals(""1""); + } + public boolean isInpile(int type) { + String x = (type==FILE) ? fileMap.get(""In_pile"") : dbMap.get(""In_pile""); + return x.contentEquals(""1""); + } + public boolean isConcat(int type) { + String x = (type==FILE) ? fileMap.get( ""concat"") : dbMap.get( ""concat""); + return x.contentEquals(""1""); + } + public boolean isMask1(int type) { + String x = (type==FILE) ? fileMap.get( ""mask1"") : dbMap.get( ""mask1""); + return x.contentEquals(""1""); + } + public boolean isMask2(int type) { + String x = (type==FILE) ? fileMap.get( ""mask2"") : dbMap.get( ""mask2""); + return x.contentEquals(""1""); + } + public boolean isNucmer(int type) { + String x = (type==FILE) ? fileMap.get( ""nucmer_only"") : dbMap.get( ""nucmer_only""); + return x.contentEquals(""1""); + } + public boolean isPromer(int type) { + String x = (type==FILE) ? fileMap.get( ""promer_only"") : dbMap.get(""promer_only""); + return x.contentEquals(""1""); + } + public String getNucmerArgs(int type) { + String x = (type==FILE) ? fileMap.get( ""nucmer_args"") : dbMap.get(""nucmer_args""); + return x; + } + public String getPromerArgs(int type) { + String x = (type==FILE) ? fileMap.get( ""promer_args"") : dbMap.get(""promer_args""); + return x; + } + public String getSelfArgs(int type) { + String x = (type==FILE) ? fileMap.get( ""self_args"") : dbMap.get(""self_args""); + return x; + } + public int getMinDots(int type) { + String x = (type==FILE) ? fileMap.get(""mindots"") : dbMap.get(""mindots""); + return Utilities.getInt(x); + } + public String getMergeIndex(int type) {// 3 options + String x = (type==FILE) ? fileMap.get(""merge_blocks"") : dbMap.get(""merge_blocks""); + return x; + } + public boolean isOrient(int type) { + String x = (type==FILE) ? fileMap.get(""same_orient"") : dbMap.get(""same_orient""); + return x.contentEquals(""1""); + } + public boolean isStrict(int type) { + String x = (type==FILE) ? fileMap.get(""strict_blocks"") : dbMap.get(""strict_blocks""); + return x!=null && x.contentEquals(""1""); + } + public boolean isOrder1(int type) { + String x = (type==FILE) ? fileMap.get(""order_proj1"") : dbMap.get(""order_proj1""); + return x.contentEquals(""1""); + } + public boolean isOrder2(int type) { + String x = (type==FILE) ? fileMap.get(""order_proj2"") : dbMap.get(""order_proj2""); + return x.contentEquals(""1""); + } + /************************************************************************************/ + public HashMap getFileParams() { return fileMap;} + public HashMap getDbParams() { return dbMap;} // for PairParams Pseudo + + public String getFileParamsStr() { + String msg=""""; + for (String x : fileMap.keySet()) { + msg += String.format(""%15s %s\n"", x, fileMap.get(x)); + } + return msg; + } + public HashMap getDefaults() { return defMap;} + + // ManagerFrame alignAll and alignSelected; remove existing and restart + public int renewIdx() { + removePairFromDB(false); // False; do not redo numHits, interrupt does not clear it + + try { + dbc2.executeUpdate(""INSERT INTO pairs (proj1_idx,proj2_idx) "" + + "" VALUES('"" + proj1Idx + ""','"" + proj2Idx + ""')""); + + pairIdx = dbc2.getIdx(""SELECT idx FROM pairs "" + + ""WHERE proj1_idx="" + proj1Idx + "" AND proj2_idx="" + proj2Idx); + + return pairIdx; + } + catch (Exception e) {ErrorReport.die(e, ""SyMAP error getting pair idx"");return -1;} + } + /************************************************************ + * Above (!bHitCnt), removeProj (bHitCnt), Cancel (bHitCnt) + */ + public int removePairFromDB(boolean bHitCnt) { + try { + int x = dbc2.getIdx(""select idx from pairs where proj1_idx="" + proj1Idx + "" and proj2_idx="" + proj2Idx); + if (x!= -1) { + AnchorMain ancObj = new AnchorMain(dbc2, null, this); + ancObj.removePseudo(); // Remove pseudo where numhits=-pair_idx; do before saveAnno; + + Globals.prt(""Start remove pair from database, please be patient.....""); + dbc2.executeUpdate(""DELETE from pairs WHERE idx=""+ x); + dbc2.resetAllIdx(); // check all, even though some are not relevant + + if (bHitCnt) ancObj.saveAnnoHitCnt(false); // Redo numhits for this pair; false is to not print + } + pairIdx = -1; + } + catch (Exception e) {ErrorReport.print(e, ""Error removing pair from database - you may need to Clear Pair (leave alignments)"");} + return -1; + } + public boolean removeSyntenyFromDB() { // for synteny only + try { + if (pairIdx==-1) return false; + dbc2.executeUpdate(""DELETE from blocks WHERE pair_idx=""+ pairIdx); + dbc2.resetIdx(""idx"", ""blocks""); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Error removing pair from database"");} + return false; + } + /********** called by PairParams on save; write all ***********/ + public void saveParamsToFile(HashMap valMap) { + FileDir.checkCreateDir(Constants.dataDir, true); + FileDir.checkCreateDir(Constants.seqRunDir, true); + FileDir.checkCreateDir(resultDir, true); + + File pfile = new File(resultDir,Constants.paramsFile); + try { + PrintWriter out = new PrintWriter(pfile); + out.println(""#""); + out.println(""# Pairs parameter file ""); + out.println(""# Created "" + ErrorReport.getDate()); + out.println(""# Note: changes MUST be made in SyMAP parameter window""); + + for (int i=0; i547 + public boolean isPostVn(int v) { //v546 had bug that added bad pseudo_hit_annot, which only shows up in Every+ + try { + if (syVer.equals("""")) return false; + + String x = syVer.substring(1, syVer.length()); + x = x.replaceAll(""\\."", """"); + int y = Utilities.getInt(x); + if (y>v) return true; + + return false; + } + catch (Exception e) {ErrorReport.print(e, ""post v546""); return false;} + } + public String toString() {return mProj1.strDisplayName + ""-"" + mProj2.strDisplayName + "" pair"";} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symap/manager/Mproject.java",".java","29432","801","package symap.manager; + +import java.awt.Color; +import java.io.File; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.sql.ResultSet; + +import util.ErrorReport; +import util.Utilities; +import util.FileDir; +import database.DBconn2; +import props.PropertiesReader; +import symap.Globals; +import backend.AnchorMain; +import backend.Constants; +import backend.Utils; + +/**************************************************** + * This is used by most backend and display stuff. Has project parameters, and loads basic data + * All load/align classes get info from here. + * However, project stuff is still all over the place for displays + * + * Keeps track of changes to file versus what is in database for previous load/align + * The load/align parameters are only loaded to DB when the corresponding task is executed + * ProjParams show file, View shows DB + * + * All Mproject obj are recreated on every refresh + * if !viewSymap, the file values have precedence over DB for projVal + */ + +public class Mproject implements Comparable { + private final int abbrevLen = Globals.abbrevLen; + public String strDBName; // This is SQL project.name, and seq/dirName + public String strDisplayName; + + private int projIdx; // unique database index + private String strDate=""""; + private DBconn2 dbc2; + + private int numExon = 0, numGene = 0, numGap = 0, numGroups=0, numSynteny=0, numDraft=0; // numDraft to see !strict by default + private long length=0; // genome length - must be long + + private TreeMap grpIdx2FullName = new TreeMap (); // full name, e.g. chr01 + private TreeMap grpIdx2Name = new TreeMap (); // name, e.g. 01 + private TreeMap grpName2Idx = new TreeMap (); // full name and name + private Pattern namePat; + private boolean bHasSelf=false; + + private HashMap pLabelMap = new HashMap (); + private HashMap pKeysMap = new HashMap (); + + private Color color; + private short nStatus = STATUS_IN_DB; + public static final short STATUS_ON_DISK = 0x0001; + public static final short STATUS_IN_DB = 0x0002; + + private boolean bStart=true; + + // ManagerFrame, ChrExpInit, DotPlot.Project; one is created for each project shown on Manager left panel + public Mproject(DBconn2 dbc, int nIdx, String strName, String annotdate) { + this.projIdx = nIdx; + this.strDBName = strName; + this.strDate = annotdate; + this.dbc2 = dbc; + + makeParams(); + + if (nIdx == -1) { + nStatus = STATUS_ON_DISK; + finishParams(); + } + else { + nStatus = STATUS_IN_DB; + if (annotdate!="""") { + strDate = Utilities.reformatAnnotDate(annotdate); + if (strDate.contentEquals(""???"")) + System.out.println(""Warning: "" + strName + "" interrupted on load - reload""); + } + } + bStart = false; + } + public Mproject() { // for display packages querying proj_props + makeParams(); + } + public Mproject copyForQuery() { // for isSelf + try { + Mproject p = new Mproject(dbc2, projIdx, strDBName, """"); + p.loadDataFromDB(); + p.loadParamsFromDB(); + p.finishParams(); + return p; + } + catch (Exception e) {ErrorReport.print(e, ""copyForQuery""); return null;} + } + public int compareTo(Mproject b) { + return strDisplayName.compareTo(b.strDisplayName); + } + public boolean equals(Object o) { + if (o instanceof Mproject) { + Mproject p = (Mproject)o; + return (strDBName != null && strDBName.equals(p.getDBName())); + } + return false; + } + + public String getAnnoStr() { + String msg= """"; + if (numGene>0) msg += String.format(""Genes: %,d "", numGene); + if (numExon>0) msg += String.format(""Exons: %,d "", numExon); + if (numGap>0) msg += String.format(""Gaps: %,d"", numGap); + + return msg; + } + public String getCntSyntenyStr() { + if (numSynteny==0) return """"; + else return ""["" + numSynteny + ""]""; + } + public boolean hasSynteny() {return numSynteny>0;} + public boolean hasGenes() {return numGene>0;} + public boolean hasSelf() {return bHasSelf;} + + public boolean hasCat() {return !Utilities.isEmpty(getDBVal(sCategory));} + public long getLength() {return length;} + public Color getColor() {return color; } + public void setColor(Color c) {color = c; } + + public int getIdx() { return projIdx; } + public int getID() { return projIdx; } + public String getDBName() { return strDBName; } + public String getDisplayName() { return strDisplayName; } + public int getGeneCnt() { return numGene;} // for Query Instructions + public String getLoadDate() {return strDate;} + public int getNumGroups() { return numGroups; } + public int getNumDraft() { return numDraft; } // # <1000000 + + public short getStatus() {return nStatus; } + public boolean isLoaded() {return (nStatus==STATUS_IN_DB);} + + public String getdbDesc() { return getDBVal(sDesc); } + public String getdbGrpName() { return getDBVal(sGrpType);} + public String getdbCat() { return getDBVal(sCategory); } + public String getdbAbbrev() { return getDBVal(sAbbrev); } + + public void setIsSelf(String display, String abbrev) { // for isSelf + setProjVal(sDisplay, display); strDisplayName = display; + setProjVal(sAbbrev, abbrev); + } + + public int getdbMinKey() {return Utilities.getInt(getDBVal(sANkeyCnt));} + + public String getSequenceFile() { return getProjVal(lSeqFile); } + public String getAnnoFile() { return getProjVal(lAnnoFile); } + + public int getMinSize() + { String val = getProjVal(lMinLen); + if (val.contains("","")) val = val.replace("","",""""); + return Utilities.getInt(val); + } + public String getKeywords() { return getProjVal(lANkeyword); } + public String getAnnoType() { return """";} + + public String getGrpPrefix() { return getProjVal(lGrpPrefix);} + public int getGrpSize() { return grpIdx2Name.size();} + public TreeMap getGrpIdxMap() {return grpIdx2Name;} + + public String getGrpFullNameFromIdx(int idx) { + if (grpIdx2FullName.containsKey(idx)) return grpIdx2FullName.get(idx); + return (""Unk"" + idx); + } + public String getGrpNameFromIdx(int idx) { + if (grpIdx2Name.containsKey(idx)) return grpIdx2Name.get(idx); + return (""Unk"" + idx); + } + public int getGrpIdxFromFullName(String name) {// can be full or short + if (grpName2Idx.containsKey(name)) return grpName2Idx.get(name); + return getGrpIdxRmPrefix(name); + } + + public int getGrpIdxRmPrefix(String name) { // grpName2Idx has both w/o prefix + String s = name; + + Matcher m = namePat.matcher(name); + if (m.matches()) s = m.group(2); + if (grpName2Idx.containsKey(s)) return grpName2Idx.get(s); + return -1; + } + public String getValidGroup() { // AnnotLoadMain; + String msg= grpName2Idx.size()+"": ""; + int cnt=0; + for (String x : grpName2Idx.keySet()) { + msg += x + "";""; + cnt++; + if (cnt>50) { + msg += ""...""; + break; + } + } + return msg; + } + /////////////////////// + public String notLoadedInfo() { + String msg=""Parameters: ""; + if (getProjVal(lSeqFile).contentEquals("""")) msg += ""Default file locations; ""; + else msg += ""User file locations; ""; + + msg += "" Min len "" + getProjVal(lMinLen) + ""; ""; + + String prefix = getProjVal(lGrpPrefix); + prefix = (Utilities.isEmpty(prefix)) ? ""None"" : prefix; + msg += "" Prefix "" + prefix + ""; ""; + + String annotKeywords = getProjVal(lANkeyword); + if (annotKeywords.equals("""")) msg += "" All anno keywords ""; + else msg += "" Keywords "" + annotKeywords; + + return msg; + } + // false: cnt all; true: only cnt if have /align; + // used for all project related links (not pair) + public boolean hasExistingAlignments(boolean bCheckAlign) { + try { + File top = new File(Constants.getNameResultsDir()); + + if (top == null || !top.exists()) return false; // may not have /data/seq_results directory + + // e.g. for brap; arab_to_brap or brap_to_cabb + String pStart = strDBName + Constants.projTo, pEnd = Constants.projTo + strDBName; + int cnt=0; + for (File f : top.listFiles()) { + if (!f.isDirectory()) continue; + + String dir = f.getName(); + if (!dir.startsWith(pStart) && !dir.endsWith(pEnd)) continue; + + if (bCheckAlign) { + String alignDir = f.getAbsolutePath() + Constants.alignDir; + File d = new File(alignDir); + if (d.exists()) cnt++; + } + else cnt++; + } + return (cnt>0); + } + catch (Exception e) {ErrorReport.print(e, ""Check existing alignment files""); return false;} + } + + /********************************************************* + * Special method to remove GrpPrefix + */ + public void updateGrpPrefix() { + try { + Vector idxSet = new Vector (); + Vector nameSet = new Vector (); + + String prefix= getProjVal(lGrpPrefix); + + ResultSet rs = dbc2.executeQuery(""select idx, name from xgroups where proj_idx="" + projIdx); + while (rs.next()) { + int ix = rs.getInt(1); + String name = rs.getString(2); + if (name.startsWith(prefix)) { + name = name.substring(prefix.length()); + idxSet.add(ix); + nameSet.add(name); + } + } + rs.close(); + + System.err.println(""Change "" + idxSet.size() + "" group names to remove '"" + prefix + ""'"" ); + + for (int i=0; i chrNameMap = new TreeMap (); // name, idx + TreeMap chrLenMap = new TreeMap ();// idx, chrName + + // get chrs and lengths + ResultSet rs = dbc2.executeQuery(""select xgroups.idx, xgroups.fullname, pseudos.length from pseudos "" + + "" join xgroups on xgroups.idx=pseudos.grp_idx "" + + "" where xgroups.proj_idx="" + projIdx); + while (rs.next()) { + int idx = rs.getInt(1); + String name = rs.getString(2); + int len = rs.getInt(3); + chrNameMap.put(name, idx); + chrLenMap.put(idx, len); + } + String desc = dbc2.executeString(""select value from proj_props "" + + ""where name='description' and proj_idx="" + projIdx); + + String info=""Project "" + strDisplayName + ""\n""; + if (!Utilities.isEmpty(desc)) info += desc + ""\n""; + info += ""\n""; + + String [] fields = {""Chr"", ""Length"", "" "",""#Genes"", ""AvgLen"", "" "", ""#Exons"", ""AvgLen"", "" "", ""Gaps""}; + int [] justify = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int nRow = chrNameMap.size()+1; + int nCol= fields.length; + String [][] rows = new String[nRow][nCol]; + int r=0, c=0; + int totGenes=0, totExons=0, totGaps=0; + long totLen=0; + float totAvgGenes=0, totAvgExons=0; + + for (String name : chrNameMap.keySet()) { + int idx = chrNameMap.get(name); + rs = dbc2.executeQuery(""select count(*) from pseudo_annot where type='gene' and grp_idx="" + idx); + int geneCnt = (rs.next()) ? rs.getInt(1) : 0; + + rs = dbc2.executeQuery(""select count(*) from pseudo_annot where type='exon' and grp_idx="" + idx); + int exonCnt = (rs.next()) ? rs.getInt(1) : 0; + + rs = dbc2.executeQuery(""select count(*) from pseudo_annot where type='gap' and grp_idx="" + idx); + int gapCnt = (rs.next()) ? rs.getInt(1) : 0; + + rs = dbc2.executeQuery(""select AVG(end-start+1) from pseudo_annot where type='gene' and grp_idx="" + idx); + double avgglen = (rs.next()) ? rs.getDouble(1) : 0.0; + + rs = dbc2.executeQuery(""select AVG(end-start+1) from pseudo_annot where type='exon' and grp_idx="" + idx); + double avgelen = (rs.next()) ? rs.getDouble(1) : 0.0; + + rows[r][c++] = name; + rows[r][c++] = String.format(""%,d"",chrLenMap.get(idx)); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",geneCnt); + rows[r][c++] = String.format(""%,d"",(int) avgglen); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",exonCnt); + rows[r][c++] = String.format(""%,d"",(int) avgelen); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",gapCnt); + r++; c=0; + + totLen += chrLenMap.get(idx); + totGenes += geneCnt; + totExons += exonCnt; + totAvgGenes += avgglen; + totAvgExons += avgelen; + totGaps += gapCnt; + } + totAvgGenes /= r; + totAvgExons /= r; + rows[r][c++] = ""Totals""; + rows[r][c++] = String.format(""%,d"",totLen); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",totGenes); + rows[r][c++] = String.format(""%,d"",(int) totAvgGenes); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",totExons); + rows[r][c++] = String.format(""%,d"",(int) totAvgExons); + rows[r][c++] = "" ""; + rows[r][c++] = String.format(""%,d"",totGaps); + r++; + + if (totGaps==0) nCol -= 2; + info += Utilities.makeTable(nCol, nRow, fields, justify, rows); + + // these are saved in proj_props + String file="""", fdate=null; + String sql = ""SELECT value FROM proj_props WHERE proj_idx='"" + projIdx; + + rs = dbc2.executeQuery(sql + ""' AND name='proj_seq_dir'""); + file = (rs.next()) ? rs.getString(1) : """"; + + rs = dbc2.executeQuery(sql + ""' AND name='proj_seq_date'""); + fdate = (rs.next()) ? rs.getString(1) : """"; + if (!file.trim().contentEquals("""")) info += ""\nSeq: "" + file + ""\nDate: "" + fdate + ""\n""; + + file=""""; + rs = dbc2.executeQuery(sql + ""' AND name='proj_anno_dir'""); + file = (rs.next()) ? rs.getString(1) : """"; + + rs = dbc2.executeQuery(sql + ""' AND name='proj_anno_date'""); + fdate = (rs.next()) ? rs.getString(1) : """"; + if (!file.trim().contentEquals("""")) info += ""\nAnno: "" + file + ""\nDate: "" + fdate + ""\n""; + rs.close(); + + Params paramObj = getParams(lMinLen); + if (!paramObj.isDBvalDef() && !paramObj.dbVal.contentEquals("""")) { + String strN = paramObj.dbVal; + if (!strN.contains("","")) { + try { + int n = Integer.parseInt(strN); + strN = String.format(""%,d"", n); + } catch (Exception e) {} + } + info += ""\n"" + paramObj.label + "": "" + strN; + } + + return info; + } + catch (Exception e) {ErrorReport.print(e, ""Load Project for view""); return ""Error"";} + } + + /******************************************************************* + * On params write: update Mproject but leave DB in case they do not load/A&S + */ + public void saveParams(int type) { + if (projIdx == -1) return; // not loaded yet + try { + if (type==xLoad) { + dbc2.executeUpdate(""update projects set hasannot=1,"" + + "" annotdate=NOW(), syver='"" + Globals.VERSION + ""' where idx="" + projIdx); + } + + for (Params p : pKeysMap.values()) { + boolean b=false; + if (p.isSum) b=true; + else if (p.isLoad && type==xLoad) b = true; + + if (b) { + dbc2.executeUpdate(""delete from proj_props where proj_idx=""+ projIdx + + "" and name='"" + p.key + ""'""); + + dbc2.executeUpdate(""insert into proj_props (proj_idx,name,value) "" + + "" values("" + projIdx + "",'"" + p.key + ""','"" + p.projVal + ""')""); + + pKeysMap.get(p.key).dbVal = p.projVal; + } + if (type==xLoad) nStatus=STATUS_IN_DB; + } + finishParams(); + } + catch (Exception e){ErrorReport.print(e, ""Failed to update load parameters "");} + } + + // the following are saved: ""proj_seq_dir"", ""proj_seq_date"", ""proj_anno_dir"", ""proj_anno_date"" + public void saveProjParam(String name, String val) throws Exception{ + try { + dbc2.executeUpdate(""delete from proj_props where name='"" + name + ""' and proj_idx="" + projIdx); + dbc2.executeUpdate(""insert into proj_props (name, value, proj_idx) values('"" + name + ""','"" + val + ""','"" + projIdx + ""')""); + } + catch (Exception e) {ErrorReport.print(e, ""Save project param "" + name + "" "" + val); } + } + + /**********************************************************/ + public void createProject() throws Exception { + try { + projIdx = dbc2.getIdx(""select idx from projects where name='"" + strDBName + ""'""); + + if (projIdx == -1) { + dbc2.executeUpdate(""INSERT INTO projects (name,type,loaddate, syver) "" + + ""VALUES('"" + strDBName + ""','pseudo',NOW(),'"" + Globals.VERSION + ""')""); + projIdx = dbc2.getIdx(""select idx from projects where name='"" + strDBName + ""'""); + + System.out.println(""Create project in database - "" + strDBName); + } + else System.out.println(""SyMAP warning: project "" + strDBName + "" exists""); + } + catch (Exception e) {ErrorReport.print(e, ""Createproject from DB""); } + } + + public void removeAnnoFromDB() { + try { + dbc2.executeUpdate(""DELETE FROM pseudo_annot USING pseudo_annot, xgroups "" + + "" WHERE xgroups.proj_idx='"" + projIdx + + ""' AND pseudo_annot.grp_idx=xgroups.idx""); + + dbc2.executeUpdate(""delete from pairs "" + + "" where proj1_idx="" + projIdx + "" or proj2_idx="" + projIdx); + + dbc2.resetAllIdx(); + } + catch (Exception e) {ErrorReport.print(e, ""Remove annotations""); } + } + public void removeProjectFromDB() { + try { + Globals.rprt(""Removing "" + strDisplayName + "" from database...""); + // Setup for update numhits for single Query + Vector proj2Idx = new Vector (); + ResultSet rs = dbc2.executeQuery(""select proj1_idx, proj2_idx from pairs where proj1_idx="" + projIdx + "" or proj2_idx="" + projIdx); + while (rs.next()) { + int idx1 = rs.getInt(1), idx2 = rs.getInt(2); + if (idx1==projIdx) proj2Idx.add(idx2); + else proj2Idx.add(idx1); + } + + /* Main Delete */ + dbc2.executeUpdate(""DELETE from projects WHERE name='""+ strDBName+""'""); + dbc2.resetAllIdx(); + + nStatus = STATUS_ON_DISK; + projIdx = -1; + + // update numhits + Globals.rprt(""Update "" + strDisplayName + "" numHits...""); + AnchorMain ancObj = new AnchorMain(dbc2, null, null); + for (int idx : proj2Idx) { + Vector gidxList = new Vector (); + rs = dbc2.executeQuery(""select idx from xgroups where proj_idx="" + idx); + while (rs.next()) gidxList.add(rs.getInt(1)); + + for (int gidx : gidxList) ancObj.saveAnnotHitCnt(gidx,""""); // get ResultClose error if not put in vector + } + Globals.rclear(); + } + catch (Exception e) {ErrorReport.print(e, ""Remove project from DB""); } + } + public void removeProjectAnnoFromDB() { + try { + dbc2.executeUpdate(""DELETE pseudo_annot.* from pseudo_annot, xgroups where pseudo_annot.grp_idx=xgroups.idx and xgroups.proj_idx="" + projIdx); + dbc2.resetIdx(""idx"", ""pseudo_annot""); + } + catch (Exception e) {ErrorReport.print(e, ""Remove annotation from DB""); } + } + /********************************************************* + * ManagerFrame: every time it is re-initilized on refresh; the following are called in this order + * loadParamsFromDB + * loadDataFromDB + * loadParamsFromDisk (if !viewSymap) + */ + public void loadParamsFromDB() { + try { + ResultSet rs = dbc2.executeQuery(""SELECT name, value FROM proj_props WHERE proj_idx="" + projIdx); + while (rs.next()) { + String key = rs.getString(1); + String val = rs.getString(2); + if (pKeysMap.containsKey(key)) { // there are entries, e.g. proj_anno_date, that are not param + pKeysMap.get(key).dbVal = val; + pKeysMap.get(key).projVal = val; + } + } + rs = dbc2.executeQuery(""select idx from pairs where proj1_idx="" + projIdx + "" and proj2_idx="" + projIdx); + bHasSelf = (rs.next()) ? true : false; + rs.close(); + + loadParamsFromDisk(); + } + catch (Exception e) {ErrorReport.print(e,""Load projects properties""); } + } + protected void loadParamsFromDisk() { + if (!FileDir.dirExists(Constants.dataDir)) { + finishParams(); + return; + } + String dir = Constants.seqDataDir + strDBName; + loadParamsFromDisk(dir); + } + protected void loadParamsFromDisk(File dir) { + loadParamsFromDisk(dir.getAbsolutePath()); + } + + private void loadParamsFromDisk(String dir){ + File pfile = Utils.getParamsFile(dir,Constants.paramsFile); + if (pfile==null) { // If user created, no params file + finishParams(); + if (!ManagerFrame.inReadOnlyMode) writeNewParamsFile(); + return; + } + + String msg = """"; + PropertiesReader props = new PropertiesReader( pfile); + for (int i=0; i0 && !p.projVal.equals(fprop)) { + msg += String.format(""%-20s DB: %-20s File: %-20s\n"", p.label, p.projVal, fprop); + } + p.projVal = fprop; // overwrite from DB + } + } + // uses params from file; display params can be changed when another database is shown + if (msg.length()>0 && nStatus == STATUS_IN_DB && bStart) {// bStart only do when this object is created + if (Globals.TRACE) Globals.prt(strDBName + "" updating in DataBase:\n"" + msg); + saveParams(xUpdate); + } + finishParams(); + } + + private void finishParams() { // DisplayName, Abbrev + strDisplayName = getDBVal(sDisplay).trim(); + if (Utilities.isEmpty(strDisplayName)) { + strDisplayName = getProjVal(sDisplay).trim(); + + if (Utilities.isEmpty(strDisplayName)) { + strDisplayName = strDBName; + setProjVal(sDisplay, strDisplayName); + } + } + String abbrev = getDBVal(sAbbrev).trim(); + if (Utilities.isEmpty(abbrev)) { + abbrev = getProjVal(sAbbrev).trim(); + + if (Utilities.isEmpty(abbrev)) { // could get duplicate for new project, but checked in Param Save and QueryFrame + int len = strDisplayName.length(); + if (len>abbrevLen) abbrev = strDisplayName.substring(0, abbrevLen);// 1st char (was last CAS578) + else abbrev = strDisplayName; + setProjVal(sAbbrev, abbrev); + } + } + String regx = ""("" + getProjVal(lGrpPrefix) + "")?(\\w+).*""; + namePat = Pattern.compile(regx,Pattern.CASE_INSENSITIVE); + } + + public void loadDataFromDB() throws Exception { + ResultSet rs = dbc2.executeQuery(""select idx, fullname, name from xgroups where proj_idx="" + projIdx); + while (rs.next()) { + int idx = rs.getInt(1); + String full = rs.getString(2); + String name = rs.getString(3); + + grpName2Idx.put(full, idx); + grpName2Idx.put(name, idx); + grpIdx2Name.put(idx, name); + grpIdx2FullName.put(idx, full); + } + rs.close(); + + numGroups = dbc2.executeCount(""SELECT count(*) FROM xgroups WHERE proj_idx="" + projIdx); + + numExon = dbc2.executeCount(""select count(*) from pseudo_annot as pa "" + + "" join xgroups as g on g.idx=pa.grp_idx "" + + "" where g.proj_idx="" + projIdx + "" and type='exon'""); + + numGene = dbc2.executeCount(""select count(*) from pseudo_annot as pa "" + + "" join xgroups as g on g.idx=pa.grp_idx "" + + "" where g.proj_idx="" + projIdx + "" and type='gene'""); + + numGap = dbc2.executeCount(""select count(*) from pseudo_annot as pa "" + + "" join xgroups as g on g.idx=pa.grp_idx "" + + "" where g.proj_idx="" + projIdx + "" and type='gap'""); + + length = dbc2.executeLong(""select sum(length) from pseudos "" + + ""join xgroups on xgroups.idx=pseudos.grp_idx "" + + ""where xgroups.proj_idx="" + projIdx); + + numDraft = dbc2.executeCount(""select count(length<1000000) from pseudos "" + + ""join xgroups on xgroups.idx=pseudos.grp_idx "" + + ""where xgroups.proj_idx="" + projIdx); + + numSynteny = dbc2.executeCount(""select count(*) from pairs where proj1_idx="" + projIdx + + "" or proj2_idx="" + projIdx); + } + // The writeParamsFile is in ProjParams; this is for new projects + private void writeNewParamsFile() { + if (Utilities.isEmpty(strDBName)) return; // OrderAgainst writes the file, but not with Mproject + String dir = Constants.seqDataDir + strDBName; + FileDir.checkCreateDir(dir, true); + + File pfile = new File(dir,Constants.paramsFile); + if (!pfile.exists()) + System.out.println(""Create parameter file "" + dir + Constants.paramsFile); + + try { + PrintWriter out = new PrintWriter(pfile); + out.println(""# Directory "" + strDBName + "" project parameter file""); + out.println(""# Note: changes MUST be made in SyMAP parameter window""); + out.println(""#""); + out.println(getKey(sDisplay) + "" = "" + strDisplayName); + out.println(getKey(sAbbrev) + "" = "" + getProjVal(sAbbrev)); + out.println(getKey(sDesc) + "" = New project""); + out.close(); + } + catch (Exception e) {ErrorReport.print(e, ""Wrie new params file"");} + } + public String toString() { return strDBName + "":"" + projIdx; } + + public void prtInfo() {// public for testing query + Globals.prt(String.format("" %-20s %s index %d"", ""DBname"", strDBName, projIdx)); + String key = paramLabel[sCategory]; + Globals.prt(String.format("" %-20s %s"", key, pLabelMap.get(key).projVal)); + key = paramLabel[sDisplay]; + Globals.prt(String.format("" %-20s %s"", key, pLabelMap.get(key).projVal)); + key = paramLabel[sAbbrev]; + Globals.prt(String.format("" %-20s %s"", key, pLabelMap.get(key).projVal)); + } + /*********************************************************** + * ProjParams interface + */ + public String getLab(int iLabel) {return paramLabel[iLabel];} + public String getKey(int iLabel) {return paramKey[iLabel];} // used by non mProj packages to get keyword + public String getDef(int iLabel) {return paramDef[iLabel];} + public String getDesc(int iLabel) {return paramDesc[iLabel];} + + public HashMap getParams() { + HashMap pMap = new HashMap (); + for (String key : pLabelMap.keySet()) { + pMap.put(key, pLabelMap.get(key).projVal); + } + return pMap; + } + public String getParam(String label) { + if (!pLabelMap.containsKey(label)) return null; + return pLabelMap.get(label).key; + } + /*******************************************************************/ + private String getProjVal(int idx) { + String key = paramKey[idx]; + String val = pKeysMap.get(key).projVal; + if (val==null) val=""""; + return val; + } + + private void setProjVal(int idx, String value) { + String key = paramKey[idx]; + pKeysMap.get(key).projVal = value; + pKeysMap.get(key).dbVal = value; // for Query self-synteny + } + + private String getDBVal(int idx) { + String key = paramKey[idx]; + String val = (isLoaded()) ? pKeysMap.get(key).dbVal : pKeysMap.get(key).projVal; + return val; + } + + private Params getParams(int idx) { + String key = paramKey[idx]; + return pKeysMap.get(key); + } + private void makeParams() { + for (int i=0; i %Identity""); // %identity + pctidSlider = new JSlider(id, 100, id); + pctidSlider.setMajorTickSpacing(10); + pctidSlider.setMinorTickSpacing(5); + pctidSlider.setPaintTicks(true); + pctidSlider.addChangeListener(listener); + listener.stateChanged(new ChangeEvent(pctidSlider)); + + dotSizeSlider = new JSlider(1, 5, 1); // min, max, init + dotSizeSlider.setMajorTickSpacing(1); + dotSizeSlider.setPaintTicks(true); + dotSizeLabel = Jcomp.createLabelGray(dotLabel + ""1"", ""Scale dots""); + dotSizeSlider.addChangeListener(listener); + listener.stateChanged(new ChangeEvent(dotSizeSlider)); + + bPctScale = Jcomp.createRadioGray(""%Id"", ""Scale hits by %Identity""); + bPctScale.addItemListener(listener); + + bLenScale = Jcomp.createRadioGray(""Length"", ""Scale hits by length (shown as rectangles)""); + bLenScale.addItemListener(listener); + + bNoScale = Jcomp.createRadioGray(""None"", ""All hits the same size""); + bNoScale.addItemListener(listener); + + ButtonGroup sgroup = new ButtonGroup(); + sgroup.add(bPctScale); + sgroup.add(bLenScale); + sgroup.add(bNoScale); + bLenScale.setSelected(true); + + bAllHits = Jcomp.createRadioGray(""All"", ""Show all hits the same size""); + + bAllHits.addItemListener(listener); + + bMixHits = Jcomp.createRadioGray(""Mix"", ""Block hits are scale, all others are dots""); + bMixHits.addItemListener(listener); + + bBlockHits = Jcomp.createRadioGray(""Block"", ""Only show block hits""); + bBlockHits.addItemListener(listener); + + ButtonGroup group = new ButtonGroup(); + group.add(bAllHits); + group.add(bMixHits); + group.add(bBlockHits); + bAllHits.setSelected(true); + + bGeneHits = Jcomp.createRadioGray(""Ignore"", ""Show all hits""); + bGeneHits.addItemListener(listener); + + b2GeneHits = Jcomp.createRadioGray(""Both"", ""Only show hits to two genes""); + b2GeneHits.addItemListener(listener); + + b1GeneHits = Jcomp.createRadioGray(""One"", ""Only show hits to one gene""); + b1GeneHits.addItemListener(listener); + + b0GeneHits = Jcomp.createRadioGray(""None"", ""Only show hits to no genes""); + b0GeneHits.addItemListener(listener); + + ButtonGroup group2 = new ButtonGroup(); + group2.add(bGeneHits); + group2.add(b2GeneHits); + group2.add(b1GeneHits); + group2.add(b0GeneHits); + bGeneHits.setSelected(true); + + showBlkNumBox = Jcomp.createCheckBoxGray(""Number"", ""Show block number""); + showBlkNumBox.addItemListener(listener); + + showBlocksBox = Jcomp.createCheckBoxGray(""Boundary"", ""Show boundary of block""); + showBlocksBox.addItemListener(listener); + + showEmptyBox = Jcomp.createCheckBoxGray(""Show Empty Regions"", ""Show regions with no hits""); + showEmptyBox.addItemListener(listener); + + Container cp = getContentPane(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + cp.setLayout(gbl); + gbc.fill = 2; + gbc.gridheight = 1; + gbc.ipadx = 5; + gbc.ipady = 8; + int rem = GridBagConstraints.REMAINDER; + + addToGrid(cp,gbl,gbc,pctidLabel, 1); + addToGrid(cp,gbl,gbc,pctidSlider, rem); + + addToGrid(cp,gbl,gbc,dotSizeLabel, 1); + addToGrid(cp,gbl,gbc,dotSizeSlider, rem); + + addToGrid(cp,gbl,gbc,new JLabel("" Scale dot by hit""),1); + addToGrid(cp,gbl,gbc,bLenScale,1); + addToGrid(cp,gbl,gbc,bPctScale,1); + addToGrid(cp,gbl,gbc,bNoScale,rem); + + addToGrid(cp,gbl,gbc,new JLabel("" Show Hits""),1); + addToGrid(cp,gbl,gbc,bAllHits,1); + addToGrid(cp,gbl,gbc,bMixHits,1); + addToGrid(cp,gbl,gbc,bBlockHits,rem); + + addToGrid(cp,gbl,gbc,new JLabel("" Only Genes""),1); + addToGrid(cp,gbl,gbc,bGeneHits,1); + addToGrid(cp,gbl,gbc,b2GeneHits,1); + addToGrid(cp,gbl,gbc,b1GeneHits,1); + addToGrid(cp,gbl,gbc,b0GeneHits,rem); + + addToGrid(cp,gbl,gbc,new JSeparator(),rem); + addToGrid(cp,gbl,gbc,new JLabel("" Show Block""),1); + addToGrid(cp,gbl,gbc,showBlocksBox,1); + addToGrid(cp,gbl,gbc,showBlkNumBox,rem); + + if (data.getMaxGrps()>manyGrps) { + addToGrid(cp,gbl,gbc,new JSeparator(),rem); + addToGrid(cp,gbl,gbc,showEmptyBox, rem); + } + + addToGrid(cp,gbl,gbc,buttonPanel, rem); + + setFromFD(); + + pack(); + setResizable(false); + + setTitle(""DotPlot Filter""); + Dimension dim = getToolkit().getScreenSize(); + setLocation(dim.width / 4,dim.height / 4); + toFront(); + requestFocus(); + setModal(true); + } + protected void showX() { + cpFiltData = data.getFilterData().copy(); + setFromFD(); + setVisible(true); + } + protected void setFromFD() { + FilterData fd = data.getFilterData(); + + int id = fd.getPctid(); + if (id>100) id=100; + pctidSlider.setValue(id); + String x = (id < 100) ? ((id < 10) ? "" "" : "" "") : """"; // blanks + pctidLabel.setText(hitLabel + x + id); + + dotSizeSlider.setValue((int)fd.getDotSize()); + + bPctScale.setSelected(fd.isPctScale()); + bLenScale.setSelected(fd.isLenScale()); + bNoScale.setSelected(fd.isNoScale()); + + bAllHits.setSelected(fd.isShowAllHits()); + bMixHits.setSelected(fd.isShowMixHits()); + bBlockHits.setSelected(fd.isShowBlockHits()); + + bGeneHits.setSelected(fd.isShowGeneIgn()); + b2GeneHits.setSelected(fd.isShowGene2()); + b1GeneHits.setSelected(fd.isShowGene1()); + b0GeneHits.setSelected(fd.isShowGene0()); + + showBlocksBox.setSelected(fd.isShowBlocks()); + showBlkNumBox.setSelected(fd.isShowBlkNum()); + + showEmptyBox.setSelected(fd.isShowEmpty()); + } + + private void addToGrid(Container c, GridBagLayout gbl, GridBagConstraints gbc, Component comp, int i) { + gbc.gridwidth = i; + gbl.setConstraints(comp,gbc); + c.add(comp); + } + + /************************************************************************************/ + private class FilterListener implements ActionListener, ChangeListener, ItemListener { + private FilterListener() { } + + public void actionPerformed(ActionEvent e) { + Object src = e.getSource(); + if (src == okButton) { + setVisible(false); + } + else if (src == cancelButton) { + data.getFilterData().setFromFD(cpFiltData); + setFromFD(); + cntl.update(); + setVisible(false); + } + else if (src == defaultButton) { + data.getFilterData().setDefaults(); + setFromFD(); + cntl.update(); + } + } + public void stateChanged(ChangeEvent e) { + Object src = e.getSource(); + FilterData fd = data.getFilterData(); + + if (src == pctidSlider) { + int s = pctidSlider.getValue(); + String x = (s < 100) ? ((s < 10) ? "" "" : "" "") : """"; // blanks + pctidLabel.setText(hitLabel + x + s); + if (bIsFirst) bIsFirst=false; // otherwise, sets to initMinPctid + else { + boolean b = fd.setPctid(s); + if (b) cntl.update(); + } + } + else if (src == dotSizeSlider) { + int s = dotSizeSlider.getValue(); + String x = (s<10) ? "" "" : "" ""; // blanks + dotSizeLabel.setText(dotLabel + x + s); + boolean b = fd.setDotSize(s); + if (b) cntl.update(); + } + } + public void itemStateChanged(ItemEvent evt) { + Object src = evt.getSource(); + FilterData fd = data.getFilterData(); + + boolean b=false; + if (src == bBlockHits || src == bAllHits || src == bMixHits) { + b = fd.setShowHits(bBlockHits.isSelected(), bAllHits.isSelected()); + } + else if (src == bGeneHits || src == b1GeneHits || src == b2GeneHits || src == b0GeneHits) { + b = fd.setGeneHits(b2GeneHits.isSelected(), b1GeneHits.isSelected(), b0GeneHits.isSelected()); + } + else if (src == bPctScale || src==bLenScale || src==bNoScale) { + b = fd.setDotScale(bLenScale.isSelected(), bPctScale.isSelected()); + } + else { + boolean isChg = (evt.getStateChange() == ItemEvent.SELECTED); + + if (src == showBlocksBox) b = fd.setShowBlocks(isChg); + else if (src == showBlkNumBox) b = fd.setShowBlkNum(isChg); + else if (src == showEmptyBox) b = fd.setShowEmpty(isChg); + } + if (b) cntl.update(); + } + } // end listener +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/ControlPanel.java",".java","7812","211","package dotplot; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Component; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.MouseEvent; + +import javax.swing.JPanel; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JSeparator; +import javax.swing.JTextField; +import javax.swing.JComboBox; + +import colordialog.ColorDialogHandler; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import util.ImageViewer; +import util.Jcomp; +import util.Utilities; +import util.Popup; + +/********************************************************** + * The Control Panel for the DotPlot (top row) + */ +public class ControlPanel extends JPanel implements HelpListener { + private static final long serialVersionUID = 1L; + private Data data; // changes to zoom, etc set in data + private Plot plot; // for show image and repaint + private Filter filter=null; + + private JButton homeButton, minusButton, plusButton; + private JTextField numField; + private JButton filterButton, showImageButton, editColorsButton; + private JButton helpButtonLg, helpButtonSm, statsButton; + private JButton scaleToggle; + private JComboBox referenceSelector; + private ColorDialogHandler cdh; + + protected ControlPanel(Data d, Plot p, HelpBar hb, ColorDialogHandler cdh) { + this.data = d; + this.plot = p; + this.cdh = cdh; + + homeButton = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/home.gif"", ""Reset to full view with default size""); + minusButton = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/minus.gif"",""Decrease the size of the dotplot""); + plusButton = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/plus.gif"", ""Increase the size of the dotplot""); + numField = Jcomp.createTextField(""1"", + ""Amount to increase/decrease +/-; Min 1, Max 10"", 2); + scaleToggle = Jcomp.createBorderIconButton(this, hb, buttonListener, + ""/images/scale.gif"", ""Draw to BP scale.""); + + referenceSelector = new JComboBox (); + referenceSelector.addActionListener(buttonListener); + referenceSelector.setToolTipText(""Change reference (x-axis) project""); + referenceSelector.setName(""Change reference (x-axis) project""); + hb.addHelpListener(referenceSelector, this); + + filter = new Filter(d, this); + filterButton = Jcomp.createButtonGray(this,hb, buttonListener, + ""Filters"", ""Filters and display options""); + + showImageButton = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/print.gif"", ""Save as image""); + editColorsButton = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/colorchooser.gif"", ""Edit the color settings""); + helpButtonLg = util.Jhtml.createHelpIconUserLg(util.Jhtml.dotplot); + helpButtonSm = Jcomp.createIconButton(this, hb, buttonListener, + ""/images/info.png"", ""Quick Help Popup""); + statsButton = (JButton) Jcomp.createIconButton(this, hb, buttonListener, + ""/images/s.png"", ""Stats Popup""); + + JPanel row = Jcomp.createRowPanelGray(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + setLayout(gbl); + gbc.fill = GridBagConstraints.HORIZONTAL;; + gbc.gridheight = 1; + gbc.ipadx = gbc.ipady = 0; + + String sp1="" "", sp2="" ""; + addToGrid(row, gbl,gbc,homeButton,sp1); + addToGrid(row, gbl,gbc,plusButton, sp1); + addToGrid(row, gbl,gbc,minusButton,sp1); + addToGrid(row, gbl,gbc,numField,sp1); + addToGrid(row, gbl,gbc,scaleToggle,sp2); + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp1); // End home functions + + addToGrid(row, gbl,gbc,referenceSelector,sp1); + addToGrid(row, gbl,gbc,filterButton,sp1); + addToGrid(row, gbl,gbc,editColorsButton,sp2); + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp1); // End change display + + addToGrid(row, gbl,gbc,showImageButton,sp1); + addToGrid(row, gbl,gbc,helpButtonLg,sp1); + addToGrid(row, gbl,gbc,helpButtonSm,sp1); + addToGrid(row, gbl,gbc,statsButton,sp1); + add(row); + + setEnable(); + } + private void addToGrid(JPanel cp, GridBagLayout gbl, GridBagConstraints gbc, Component comp, String blank) { + gbl.setConstraints(comp,gbc); + cp.add(comp); + if (blank.length()>0) addToGrid(cp, gbl,gbc,new JLabel(blank), """"); + } + + private ActionListener buttonListener = new ActionListener() { + public void actionPerformed(ActionEvent evt) { + Object src = evt.getSource(); + if (src == filterButton) { + filter.showX(); + } + else { + boolean rp = false; + if (src == homeButton) {data.setHome(); rp=true;} + else if (src == minusButton) { + data.factorZoom(getNumVal()); + plot.bPlusMinusScroll=true; + rp=true; + } + else if (src == plusButton) { + data.factorZoom(1/getNumVal()); + plot.bPlusMinusScroll=true; + rp=true; + } + else if (src == scaleToggle) { + data.bIsScaled = !data.bIsScaled; + scaleToggle.setBackground(Jcomp.getBorderColor(data.bIsScaled)); + rp=true; + } + else if (src == referenceSelector) { + data.setReference((Project)referenceSelector.getSelectedItem()); + rp=true; + } + else if (src == editColorsButton) { + cdh.showX(); + rp=true; + } + else if (src == showImageButton) ImageViewer.showImage(""DotPlot"", plot); + else if (src == helpButtonSm) popupHelp(); + else if (src == statsButton) popupStats(); + + if (rp==true) plot.repaint(); + } + setEnable(); + } + }; + private double getNumVal() { + int n = Utilities.getInt(numField.getText()); + if (n<1) { + n = 1; + numField.setText(""1""); + } + else if (n>10) { + n = 10; + numField.setText(""10""); + } + return 1.0 - ((double) n * 0.05); + } + private void popupHelp() { + String msg = + ""If multiple chr-by-chr cells are shown, click on a cell to view the cell only.""; + msg += ""\n\nFor the chr-by-chr cell view only:"" + + ""\n Select a block by double-clicking on it (boundary must be showing), "" + + ""\n or select a region by dragging the mouse and double-click on it."" + + ""\n\n The first click will turn the block/region beige, the second click will bring up"" + + ""\n the 2D display of the block/region."" + + ""\n\n A selected beige block/region will stay in view "" + + ""\n while changing the DotPlot size using the +/- buttons.""; + msg += ""\n\nFor the genome display: change the reference by selecting it via the dropdown.""; + msg += ""\n\nSee ? for details.\n""; + + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + private void popupStats() { + String msg = plot.prtCntsS(); + Popup.displayInfoMonoSpace(this, ""Dot plot stats"", msg, false); + } + + protected void kill() {filter.setVisible(false);} // DotPlotFrame on shutdown; only needed if !modal + + protected void update() {plot.repaint();} // Filter change + + protected void setEnable() {homeButton.setEnabled(!data.isHome());} + + protected void setProjects(Project[] projects) { // DotPlotFrame + if (projects == null) { + referenceSelector.setVisible(false); + return; + } + + for (Project p : projects) + referenceSelector.addItem(p); + + // Disable if self-alignment + if (projects.length == 2 && projects[0].getID() == projects[1].getID()) + referenceSelector.setEnabled(false); + } + + public String getHelpText(MouseEvent event) { // symap.frame.Helpbar + Component comp = (Component)event.getSource(); + return comp.getName(); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/ABlock.java",".java","3134","106","package dotplot; + +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.PathIterator; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +/*********************************************** + * Represents the rectangle of a block (does not contains its hits) + * + * The Shape is used in Tile, see getSmallestBoundingArea + */ + +public class ABlock implements Shape, Comparable { + private final int X = Data.X, Y = Data.Y; + + private int number; + private Rectangle rect; + + private Tile tileObj; + int sX, eX, sY, eY; // for swap reference + + protected ABlock(Tile parent, int blockNum, int sX, int eX, int sY, int eY) { + this.sX=sX; this.eX=eX; this.sY=sY; this.eY=eY; + rect = new Rectangle(); + + this.tileObj = parent; + this.number = blockNum; + rect.setFrameFromDiagonal(sX,sY,eX,eY); + } + protected void swap() { + int t=sX; sX=sY; sY=t; + t=eX; eX=eY; eY=t; + rect.setFrameFromDiagonal(sX,sY,eX,eY); + } + + public int compareTo(ABlock a) { + return number - a.number; + } + public boolean equals(Object obj) { + if (obj instanceof ABlock) { + ABlock b = (ABlock)obj; + return number == b.number && rect.equals(b.rect); + } + return false; + } + + protected String getName() { + return tileObj.getGroup(Y).getName()+"".""+tileObj.getGroup(X).getName()+"".""+getNumber(); + } + // Called by Plot and Data + protected int getStart(int axis) {return (axis == X ? rect.x : rect.y);} + protected int getEnd(int axis) {return (axis == X ? rect.x+rect.width : rect.y+rect.height);} + protected int getNumber() {return number;} + protected String getNumberStr() {return number+"""";} + protected Group getGroup(int axis) {return tileObj.getGroup(axis);} + + ////// Shape + public boolean contains(double x, double y) { + return x >= rect.x && x <= (rect.x+rect.width) && y >= rect.y && y <= (rect.y+rect.height); + } + public boolean contains(double x, double y, double w, double h) { + return contains(x,y) && contains(x+w,y) && contains(x,y+h) && contains(x+w,y+h); + } + public boolean contains(Point2D p) { + return contains(p.getX(),p.getY()); + } + public boolean contains(Rectangle2D r) { + return contains(r.getX(),r.getY(),r.getWidth(),r.getHeight()); + } + public Rectangle getBounds() { + return rect.getBounds(); + } + public Rectangle2D getBounds2D() { + return rect.getBounds2D(); + } + public PathIterator getPathIterator(AffineTransform at) { + return rect.getPathIterator(at); + } + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return rect.getPathIterator(at,flatness); + } + public boolean intersects(double x, double y, double w, double h) { + return rect.intersects(x,y,w,h); + } + public boolean intersects(Rectangle2D r) { + return rect.intersects(r); + } + public boolean intersects(ABlock ablock) { + return rect.intersects(ablock.rect); + } + public boolean contains(ABlock ablock) { + return contains(ablock.rect); + } + + // other + public String toString() { + return ""[ABlock #""+number+"" (""+rect.x+"",""+rect.y+"") - (""+(rect.x+rect.width)+"",""+(rect.y+rect.height)+"")]""; + } + protected void clear() { + rect.setRect(0,0,0,0); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/Group.java",".java","2105","67","package dotplot; + +import java.util.HashMap; + +/************************************************** + * Represents a chromosome (group); contains its blocks + */ +public class Group implements Comparable { + private int id, projID; + private String name, fullname; + private int cLenBP, sortOrder; + private long offset; + private HashMap hasBlocks; + private boolean isVisible = true; + + // sortOrder is order of chrs based on sorted names, name is chrName, chromosome length + protected Group(int id, int sortOrder, String name, String fullname, int size, int projID) { + this.id = id; + this.sortOrder = sortOrder; + this.name = (name == null) ? """" : name; + this.fullname = (fullname == null) ? """" : fullname; + this.cLenBP = size; // chromosome length + this.projID = projID; + hasBlocks = new HashMap(); + } + + protected int getProjID() {return projID;} + protected long getOffset() { return offset; } + protected int getID() { return id; } + protected int getSortOrder() { return sortOrder; } + protected String getName() { return name; } + protected String getFullName() { return fullname; } + protected int getGrpLenBP() { return cLenBP; } + + protected void setHasBlocks(Group g) { + if (!hasBlocks.containsKey(g)) hasBlocks.put(g,true); + } + protected boolean hasBlocks() { return hasBlocks.keySet().size() > 0; } + protected boolean hasBlocks(Group[] groups) { + for (Group g : groups) { + if (hasBlocks.containsKey(g) && hasBlocks.get(g)) + return true; + } + return false; + } + protected void setVisible(boolean b) { isVisible = b; } + protected boolean isVisible() { return isVisible; } + + public String toString() { return String.format(""%d"",id); } + + public boolean equals(Object obj) { + return obj instanceof Group && ((Group)obj).id == id; + } + public int compareTo(Group g) { + return sortOrder - g.sortOrder; + } + protected static void setOffsets(Group[] groups) { + if (groups != null && groups.length > 0) { + groups[0].offset = 0; + for (int i = 1; i < groups.length; i++) { + groups[i].offset = groups[i-1].offset + groups[i-1].cLenBP; + } + } + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/FilterData.java",".java","6054","191","package dotplot; + +import java.awt.Color; + +import props.PropertiesReader; +import symap.Globals; + +/************************************************************ + * Filter Data; Data class contains FilterData object, which gets passed to Filter + */ +public class FilterData { + private static int DOT_LEN = 0, DOT_PCT = 1, DOT_NO = 2; + private static int BLOCK_HITS = 0, ALL_HITS = 1, MIX_HITS = 2; + private static int GENE_IGN = 0, GENE_1 = 1, GENE_2 = 2, GENE_0=3; + + // If change default, change Filter.setEnabled + private static int dDotScale = DOT_LEN, dShowHits = ALL_HITS, dGeneHits = GENE_IGN; + + private int iPctid = 0, defaultPctid=0; + private int iDotSize=1; + + private int nDotScale = dDotScale; + private int nShowHits = dShowHits; + private int nGeneHits = dGeneHits; + + private boolean bShowBlocks = true; + private boolean bShowBlkNum = false; + private boolean bShowEmpty = true; // hide groups with no blocks; only when >20 chrs + + protected FilterData() {} // Data + + protected FilterData copy() { + FilterData fd = new FilterData(); + fd.defaultPctid = defaultPctid; + fd.iPctid = iPctid; + fd.iDotSize = iDotSize; + + fd.nDotScale = nDotScale; + fd.nShowHits = nShowHits; + fd.nGeneHits = nGeneHits; + + fd.bShowBlocks = bShowBlocks; + fd.bShowBlkNum = bShowBlkNum; + fd.bShowEmpty = bShowEmpty; + return fd; + } + + protected void setFromFD(FilterData fd) {// FilterListener.cancel + defaultPctid = fd.defaultPctid; + iPctid = fd.iPctid; + iDotSize = fd.iDotSize; + + nDotScale = fd.nDotScale; + nShowHits = fd.nShowHits; + nGeneHits = fd.nGeneHits; + + bShowBlocks = fd.bShowBlocks; + bShowBlkNum = fd.bShowBlkNum; + bShowEmpty = fd.bShowEmpty; + } + protected void setDefaults() { // Data.resetAll; FilterListener.defaults + iPctid = defaultPctid; + iDotSize = 1; + + nDotScale = dDotScale; + nShowHits = dShowHits; + nGeneHits = dGeneHits; + + bShowBlocks = true; + bShowBlkNum = false; + bShowEmpty = true; + } + + protected void setBounds(int min, int max) { // Data + iPctid = defaultPctid = min; + } + public boolean equals(Object obj) { + if (obj instanceof FilterData) { + FilterData fd = (FilterData)obj; + + return fd.iPctid==iPctid && fd.iDotSize==iDotSize + && fd.nDotScale==nDotScale && fd.nShowHits==nShowHits && fd.nGeneHits==nGeneHits + && fd.bShowBlocks == bShowBlocks && fd.bShowBlkNum == bShowBlkNum + && fd.bShowEmpty == bShowEmpty; + } + return false; + } + + protected int getPctid() { return iPctid; } + protected int getDotSize() { return iDotSize; } + + protected boolean isPctScale() { return nDotScale==DOT_PCT; } + protected boolean isLenScale() { return nDotScale==DOT_LEN; } + protected boolean isNoScale() { return nDotScale==DOT_NO; } + + protected boolean isShowGeneIgn() { return nGeneHits==GENE_IGN;} + protected boolean isShowGene2() { return nGeneHits==GENE_2;} + protected boolean isShowGene1() { return nGeneHits==GENE_1;} + protected boolean isShowGene0() { return nGeneHits==GENE_0;} + + protected boolean isShowBlockHits(){ return nShowHits == BLOCK_HITS; } + protected boolean isShowAllHits() { return nShowHits == ALL_HITS; } + protected boolean isShowMixHits() { return nShowHits == MIX_HITS; } + + protected boolean isShowBlocks() { return bShowBlocks; } + protected boolean isShowBlkNum() { return bShowBlkNum; } + protected boolean isShowEmpty() { return bShowEmpty; } + + /*******************************************************************/ + // Filter.FilterListener changes + protected boolean setPctid(int s) { + int x = iPctid; + iPctid = s; + return (x!=iPctid); + } + protected boolean setDotSize(int s) { + int x = iDotSize; + iDotSize = s; + return (x!=iDotSize); + } + protected boolean setDotScale(boolean lenScale, boolean pctScale) { + int n = nDotScale; + if (lenScale) nDotScale=DOT_LEN; + else if (pctScale) nDotScale=DOT_PCT; + else nDotScale=DOT_NO; + return (n!=nDotScale); + } + protected boolean setShowHits(boolean onlyBlock, boolean all) { + int x = nShowHits; + if (onlyBlock) nShowHits = BLOCK_HITS; + else if (all) nShowHits = ALL_HITS; + else nShowHits = MIX_HITS; + return (x!=nShowHits); + } + protected boolean setGeneHits(boolean gene2, boolean gene1, boolean gene0) { + int x = nGeneHits; + if (gene2) nGeneHits = GENE_2; + else if (gene1) nGeneHits = GENE_1; + else if (gene0) nGeneHits = GENE_0; + else nGeneHits = GENE_IGN; + return (x!=nGeneHits); + } + protected boolean setShowBlocks(boolean showBlocks) { + boolean b = bShowBlocks; + bShowBlocks = showBlocks; + return (b!=bShowBlocks); + } + protected boolean setShowBlkNum(boolean showBlkNum) { + boolean b = bShowBlkNum; + bShowBlkNum = showBlkNum; + return (b!=bShowBlkNum); + } + protected boolean setShowEmpty(boolean showEmpty) { + boolean b = bShowEmpty; + bShowEmpty = showEmpty; + return (b!=bShowEmpty); + } + protected Color getRectColor() {return blockRectColor;} + protected Color getColor(DPHit hd) { + if (hd.isBlock()) { + if (hd.bothGene()) return blockGeneBothColor; + if (hd.oneGene()) return blockGeneOneColor; + return blockColor; + } + if (hd.bothGene()) return geneBothColor; + if (hd.oneGene()) return geneOneColor; + return nonBlockColor; + } + + // accessed and changed by ColorDialog - do not change; protected does not work CAS576 + public static Color blockColor; + public static Color nonBlockColor; + public static Color blockRectColor; + public static Color blockGeneBothColor; + public static Color blockGeneOneColor; + public static Color geneBothColor; + public static Color geneOneColor; + + static { + PropertiesReader props = new PropertiesReader(Globals.class.getResource(""/properties/dotplot.properties"")); + + blockColor = props.getColor(""blockColor""); + nonBlockColor = props.getColor(""nonBlockColor""); + blockRectColor = props.getColor(""blockRectColor""); + blockGeneBothColor = props.getColor(""blockGeneBothColor""); + blockGeneOneColor = props.getColor(""blockGeneOneColor""); + geneBothColor = props.getColor(""geneBothColor""); + geneOneColor = props.getColor(""geneOneColor""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/Tile.java",".java","4003","121","package dotplot; + +import java.util.Vector; +import java.util.Iterator; +import java.awt.Shape; +import java.awt.geom.Rectangle2D; +import java.util.Collections; + +/*********************************************** + * A cell representing hits and blocks of 2 chromosomes + */ +public class Tile { + private final int X = Data.X, Y = Data.Y; + + private Group group[]; // chromosomes for x and y axis + private Project proj[]; + private Vector ablocks; // synteny blocks - rectangles around group of hits in block + private DPHit hits[] = null; // all hits with indication if in block + + protected Tile(Project pX, Project pY, Group grpX, Group grpY) { + proj = new Project[2]; + group = new Group[2]; + ablocks = new Vector (); + + proj[X] = pX; + proj[Y] = pY; + group[X] = grpX; + group[Y] = grpY; + } + // Called by Data.DBload + protected void addBlock(int number, int sX, int eX, int sY, int eY) { + ablocks.add(new ABlock(this, number,sX,eX,sY,eY)); + Collections.sort(ablocks); + } + public boolean equals(Object obj) { + if (obj instanceof Tile) { + Tile b = (Tile)obj; + return group[X].equals(b.group[X]) && group[Y].equals(b.group[Y]); + } + return false; + } + protected void clearBlocks() { ablocks.clear();} + + protected boolean setHits(DPHit[] hits) { + this.hits = hits; + return true; + } + + protected ABlock getBlock(int number) {return ablocks.get(number-1);} // Called by Plot + + protected int getNumBlocks() {return ablocks.size(); }// Called by Plot + + protected DPHit[] getHits() { return hits; }// Called by Plot and Ablock + + protected int getProjID(int axis) {return group[axis].getProjID(); }// or proj.getID() + + protected Project getProject(int axis) {return proj[axis];} // DBload + + protected Group getGroup(int axis) { return group[axis]; } // Plot, ABlock, DBload + + protected boolean hasHits() {return (hits!=null && hits.length>0);} // Data.initialize + + protected void swap(int pid1, int pid2) { // Data.initialize + if (pid1==proj[X].getID() && pid2==proj[Y].getID()) return; + + Group tg = group[0]; group[0]=group[1]; group[1]=tg; + Project tp = proj[0]; proj[0]=proj[1]; proj[1]=tp; + for (ABlock blk : ablocks) blk.swap(); + for (DPHit ht : hits) ht.swap(); + } + + public String toString() { + int h = (hits==null) ? 0 : hits.length; + return ""Tile ""+group[Y].getName()+"",""+group[X].getName() + + "" Blocks "" + ablocks.size() + "" Hits "" + h + + "" "" + proj[Y].getDisplayName() +"","" + proj[X].getDisplayName(); + } + + /****************************************************************/ + // Called by Plot, Tile, Project + protected static Tile getTile(Tile[] tiles, Group grpX, Group grpY) { + if (tiles != null) + for (Tile t : tiles) + if (t.group[Data.X] == grpX && t.group[Data.Y] == grpY) + return t; + return null; + } + /*************************************************************************/ + // Called from Data when there is a mouse selection + protected static ABlock getBlock(Tile[] tiles, Group grpX, Group grpY, double xUnits, double yUnits) { + Tile t = getTile(tiles,grpX,grpY); + ABlock b = (t != null) ? t.getBlock(xUnits,yUnits) : null; + return b; + } + private ABlock getBlock(double xUnits, double yUnits) { // called above + synchronized (ablocks) { + ABlock b = null; + ABlock smallest = null; + Iterator iter = ablocks.iterator(); + while (iter.hasNext()) { + b = (ABlock)iter.next(); + if (b.contains(xUnits,yUnits)) { + if (smallest == null || getSmallestBoundingArea(smallest,b) == b) + smallest = b; + } + } + return smallest; + } + } + private static Shape getSmallestBoundingArea(Shape s1, Shape s2) { // called above + if (s1 == null) return s2; + if (s2 == null) return s1; + + Rectangle2D b1, b2; + b1 = s1.getBounds2D(); + b2 = s2.getBounds2D(); + + return (b1.getWidth() * b1.getHeight()) <= (b2.getWidth() * b2.getHeight()) ? s1 : s2; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/DPHit.java",".java","1222","39","package dotplot; + +/***************************************************** + * Represents a hit for DotPlot; populated in Data.DBload + */ +public class DPHit { + private int x, y; + private double pctid; + private boolean isBlock; + private int length, geneOlap; + + protected DPHit(int posX, int posY, double pctid, int geneOlap, boolean isBlock, int length) { + x = posX; + y = posY; + this.pctid = pctid; // pctid of 0 is isSelf diagonal + this.geneOlap = geneOlap; + this.isBlock = isBlock; + this.length = length; + } + protected void swap() { // swap reference + int t=x; x=y; y=t; + } + protected int getX() {return x; } + protected int getY() {return y; } + + protected double getPctid() {return pctid; } + protected int getScalePctid(double min) {// scale 1-5 + if (pctid==Data.DIAG_HIT) return 1; + double x = (pctid-min)+1; + return (int) (x/20.0); + } + protected boolean bothGene() {return geneOlap==2;} + protected boolean oneGene() {return geneOlap==1;} + protected boolean noGene() {return geneOlap==0;} + protected int getLength() {return length; } + protected boolean isBlock(){return isBlock; } + protected boolean isDiagHit() {return pctid==Data.DIAG_HIT;} // for diagonal +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/Plot.java",".java","24070","698","package dotplot; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.geom.AffineTransform; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.font.TextLayout; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; + +import symap.frame.HelpListener; +import symap.frame.HelpBar; + +/** + * Draws the dotplot + **/ +public class Plot extends JPanel implements HelpListener { + private static final long serialVersionUID = 1L; + private final int X = Data.X, Y = Data.Y; + private final double pctidLow = 30.0; // values don't seem to be lower than this, so use a constant + private Data data; + private JScrollPane scroller; + private Dimension dim; + private int sX1, sX2, sY1, sY2; // coordinates of selected region + private double xPixelBP, yPixelBP; // pixels per basepair + private boolean isSelectingArea = false; + private FilterData fd=null; + private int cntBlocks; + private int cnt2GeneBlk, cnt1GeneBlk, cnt0GeneBlk, cntHitBlk, cntHitNonBlk, cnt2GeneNB, cnt1GeneNB, cnt0GeneNB; + private int cntHitsTot, cnt0GeneTot, cnt1GeneTot, cnt2GeneTot; + private String lastInfoMsg=""""; + private boolean is2D=false; + protected boolean bPlusMinusScroll=false; // if +/- used, scroll to selected block in Tile view + + protected Plot(Data data, HelpBar hb, boolean is2D) { + super(null); + + this.data = data; + this.is2D = is2D; + + fd = data.getFilterData(); + + dim = new Dimension(); + + setBackground(FAR_BACKGROUND); + scroller = new JScrollPane(this); + scroller.setBackground(FAR_BACKGROUND); + scroller.getViewport().setBackground(FAR_BACKGROUND); + scroller.getVerticalScrollBar().setUnitIncrement(10); + + PlotListener l = new PlotListener(); + addMouseListener(l); + addMouseMotionListener(l); + + hb.addHelpListener(this); + } + + protected JScrollPane getScrollPane() { // DotPlotFrame, Plot + return scroller; + } + + /****************************************************************************/ + public void paintComponent(Graphics g) { + super.paintComponent(g); + + cnt2GeneBlk=cnt1GeneBlk=cnt0GeneBlk=cntHitBlk=cnt2GeneNB=cnt1GeneNB=cnt0GeneNB=cntHitNonBlk=0; + cntHitsTot=cnt0GeneTot=cnt1GeneTot=cnt2GeneTot=cntBlocks=0; + + // Save Image had blurry text until this is added + ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + setDims(); + Group[] xGroups = data.getVisibleGroups(X); + Group[] yGroups = data.getVisibleGroupsY(xGroups); + + Group.setOffsets(xGroups); + Group.setOffsets(yGroups); + + //draw border + g.setColor(BACKGROUND); + g.fillRect(MARGIN + 1, MARGIN + 1, dim.width - 1, dim.height - 1); + g.setColor(BACKGROUND_BORDER); + g.drawRect(MARGIN, MARGIN, dim.width, dim.height); + + //draw title + drawCenterText(g, data.getProject(X).getDisplayName(), // Ref + MARGIN, MARGIN/4 + 10, MARGIN + dim.width, MARGIN/2, HORZ); + + //draw chromosome names + if (data.isTileView()) { + drawCenterText(g, data.getCurrentProj().getDisplayName(), + MARGIN/2 + 10, MARGIN, MARGIN/2, MARGIN + dim.height, VERT); + } + else { + long offset = 0; + for (int i = 1; i < data.getNumProjects(); i++) { + Project p = data.getProject(i); + int y = MARGIN + (int)(offset * yPixelBP); + long size = data.getVisibleGroupsSize(i, xGroups); + + if (size > 0) { + drawCenterText(g, p.getDisplayName(), + MARGIN/2 + 10, y, MARGIN/2, y + (int)(size * yPixelBP), VERT); + g.setColor(BACKGROUND_BORDER); + + if (i > 1) g.drawLine(MARGIN-17, y, MARGIN, y); + offset += size; + } + } + } + + //draw blocks & hits + if (!data.isTileView()) drawAll(g); + else drawTile(g); + prtCntsInfo(); + } + /**********************************************************************/ + private void setDims() { + double zoom = data.getZoomFactor(); // Control +/- + Dimension d = new Dimension((int)(scroller.getWidth() * zoom), (int)(scroller.getHeight() * zoom)); + setPreferredSize(d); + dim.width = (int)((d.width - (MARGIN * 1.1))); + dim.height = (int)((d.height - (MARGIN * 1.2))); + + if (data.getProject(X) == null || data.getProject(Y) == null) return; + + if (data.isTileView()) { // Selected tile + xPixelBP = dim.getWidth() / data.getCurrentGrpSize(X); + yPixelBP = dim.getHeight() / data.getCurrentGrpSize(Y); + } + else { + xPixelBP = dim.getWidth() / data.getVisibleGroupsSize(X); + yPixelBP = dim.getHeight() / data.getVisibleGroupsSizeY(data.getVisibleGroups(X)); + } + + if (data.isScaled()) { // Control Scale button + yPixelBP = xPixelBP * data.getScaleFactor(); + dim.height = (int)(yPixelBP * data.getVisibleGroupsSizeY(data.getVisibleGroups(X))); + d.height = (int)(dim.height + (MARGIN * 1.2)); + setPreferredSize(d); + } + revalidate(); + scroller.getViewport().revalidate(); + } + + /********************************************************************/ + private void drawAll(Graphics g) { + Group[] xGroups = data.getVisibleGroups(X); + Group[] yGroups = data.getVisibleGroupsY(xGroups); + + // Figure out the longest group names + int maxYGrpName = 0, maxXGrpName = 0; + FontMetrics mtc = g.getFontMetrics(g.getFont()); + for (Group grp : yGroups) { + int w = mtc.stringWidth(grp.getName()); + if (w > maxYGrpName) maxYGrpName = w; + } + for (Group grp : xGroups) { + int w = mtc.stringWidth(grp.getName()); + if (w > maxXGrpName) maxXGrpName = w; + } + + //draw chr# and border; scale is 1 unless parameter min_display_sz_bp set by user + for (Group grp : xGroups) { + int x1 = MARGIN + (int)(grp.getOffset() * xPixelBP ); + int x2 = x1 + (int) (int)(grp.getGrpLenBP() * xPixelBP); // use this order to match calc of grp offsets + drawCenterText(g, grp.getName(), x1, MARGIN/2 + 10, x2, MARGIN, HORZ); + + if (grp != xGroups[xGroups.length-1]) + g.drawLine(x2, MARGIN, x2, dim.height + MARGIN); // vertical line between 2 tiles + } + for (Group grp : yGroups) { + int y1 = MARGIN + (int)(grp.getOffset() * yPixelBP ); + int y2 = y1 + (int)(grp.getGrpLenBP() * yPixelBP) ; + + drawCenterText(g, grp.getName(), MARGIN/2, y1, MARGIN, y2, HORZ); + + if (grp != yGroups[yGroups.length-1]) + g.drawLine(MARGIN, y2, dim.width + MARGIN, y2); // horz line between 2 tiles + } + + //draw hits + int dotSizeB = dotSize(data.getDotSize()); + int dotSizeNB = (fd.isShowMixHits()) ? dotSize(1) : dotSizeB; + for (Tile tile : data.getTiles()) { + cntBlocks += tile.getNumBlocks(); + + Group gX = tile.getGroup(X); + Group gY = tile.getGroup(Y); + if (!data.isGroupVisible(gX) || !data.isGroupVisible(gY)) continue; + + int x = MARGIN + (int)(gX.getOffset()*xPixelBP); + int y = MARGIN + (int)(gY.getOffset()*yPixelBP); + + for (DPHit ht : tile.getHits()) { + if (!showHit(fd, ht)) continue; + + Color c = fd.getColor(ht); + g.setColor(c); + + drawHit(g, ht, x, y, dotSizeB, ht.isBlock(), fd.isShowMixHits(), dotSizeNB); + } + } + //draw blocks (after hits so drawn on top + if (fd.isShowBlocks() || fd.isShowBlkNum()) { + for (Tile tile : data.getTiles()) { + Group gX = tile.getGroup(X); + Group gY = tile.getGroup(Y); + if (!data.isGroupVisible(gX) || !data.isGroupVisible(gY)) continue; + + int x = (int)(gX.getOffset()*xPixelBP); + int y = (int)(gY.getOffset()*yPixelBP); + + for (int k = 1; k <= tile.getNumBlocks(); k++) { + ABlock blk = tile.getBlock(k); + int rx = x + (int)(blk.getStart(X) * xPixelBP); + int ry = y + (int)(blk.getStart(Y) * yPixelBP); + int rwidth = (int)((int)((blk.getEnd(X) - blk.getStart(X))) * xPixelBP); + int rheight = (int)((int)((blk.getEnd(Y) - blk.getStart(Y))) * yPixelBP); + + if (fd.isShowBlocks()) { // allow this to be turned off and still show block# + g.setColor(fd.getRectColor()); + g.drawRect(rx+MARGIN, ry+MARGIN, rwidth+1, rheight+1); + } + if (fd.isShowBlkNum()) { + Rectangle r = new Rectangle(rx+MARGIN, ry+MARGIN, rwidth+1, rheight+1); + drawBlockNum(g, blk, r); + } + } + } + } + } + /*************************************************************************/ + // draw hit for drawAll (similar in drawGrp) + private void drawHit(Graphics g, DPHit ht, + int x, int y, int size, + boolean isBlock, boolean isMix, int sizeNB) // size of non-block is isMix + { + boolean bPct = fd.isPctScale(); + boolean bLen = fd.isLenScale(); + + int s = (bLen) ? ht.getLength() / 2 : 1; // polygon/line is length of hit; 1 if !bLen + int as = Math.abs(s); + int hx = ht.getX(), hy = ht.getY(); + + int x1 = x + (int)((hx - s) * xPixelBP), y1 = y + (int)((hy - as) * yPixelBP); + int x2 = x + (int)((hx + s) * xPixelBP), y2 = y + (int)((hy + as) * yPixelBP); + + if (!isBlock && isMix) { + g.drawLine(x1,y1,x2,y2); + return; + } + if (bLen) { + if (size <= 1) { + g.drawLine(x1,y1,x2,y2); + } + else { + double aspect = size * ((double)getHeight()/(double)getWidth()); // doesn't change + int[] px = new int[4]; + int[] py = new int[4]; + px[0] = x1 - size; py[0] = y1 - (int)(aspect); + px[1] = x1 + size; py[1] = y1 - (int)(aspect); + px[2] = x2 + size; py[2] = y2 + (int)(aspect); + px[3] = x2 - size; py[3] = y2 + (int)(aspect); + + // Constrain to drawing area + px[0] = Math.max(px[0], MARGIN); py[0] = Math.max(py[0], MARGIN); + px[1] = Math.min(px[1], MARGIN+dim.width); py[1] = Math.max(py[1], MARGIN); + px[2] = Math.min(px[2], MARGIN+dim.width); py[2] = Math.min(py[2], MARGIN+dim.height); + px[3] = Math.max(px[3], MARGIN); py[3] = Math.min(py[3], MARGIN+dim.height); + + g.fillPolygon(px, py, 4); + } + } + else { + if (bPct) size = size * ht.getScalePctid(pctidLow); + g.drawOval((x1+x2)/2, (y1+y2)/2, size, size); + g.fillOval((x1+x2)/2, (y1+y2)/2, size, size); + } + } + + private void drawTile(Graphics g) { + g.setColor(Color.BLACK); + Group gX = data.getCurrentGrp(X); + Group gY = data.getCurrentGrp(Y); + + g.setFont(PROJ_FONT); + drawCenterText(g, gX.getName(), MARGIN, MARGIN/2 + 10, MARGIN + dim.width, MARGIN, HORZ); + drawCenterText(g, gY.getName(), MARGIN/2 + 10, MARGIN, MARGIN, MARGIN + dim.height, HORZ); + + Rectangle rect = new Rectangle(); + Tile tile = Tile.getTile(data.getTiles(),gX,gY); + cntBlocks += tile.getNumBlocks(); + + // draw hits (similar to drawHit) + DPHit hits[] = tile.getHits(); + + boolean isMix = fd.isShowMixHits(); + int dotSizeB = dotSize(data.getDotSize()); + boolean bPct = fd.isPctScale(); + boolean bLen = fd.isLenScale(); + + double aspect = (double)getHeight()/(double)getWidth(); + + for (int i = hits.length-1; i >= 0; --i) { + if (hits[i] == null) continue; + if (!showHit(fd, hits[i])) continue; + + Color c = fd.getColor(hits[i]); + g.setColor(c); + + int s = hits[i].getLength() / 2; + int x1 = (int)((hits[i].getX() - s) * xPixelBP) + MARGIN; + int y1 = (int)((hits[i].getY() - Math.abs(s)) * yPixelBP) + MARGIN; + int x2 = (int)((hits[i].getX() + s) * xPixelBP) + MARGIN; + int y2 = (int)((hits[i].getY() + Math.abs(s)) * yPixelBP) + MARGIN; + + if (!hits[i].isBlock() && isMix) { + g.drawLine(x1,y1,x2,y2); + continue; + } + int sz = dotSizeB; + if (bLen) { + if (sz <= 1 ) { + g.drawLine(x1,y1,x2,y2); + } + else { + double sza = sz*aspect; + int[] x = new int[4]; + int[] y = new int[4]; + x[0] = x1 - (int)(sz); y[0] = y1 - (int)(sza); + x[1] = x1 + (int)(sz); y[1] = y1 - (int)(sza); + x[2] = x2 + (int)(sz); y[2] = y2 + (int)(sza); + x[3] = x2 - (int)(sz); y[3] = y2 + (int)(sza); + + // Constrain to drawing area + x[0] = Math.max(x[0], MARGIN); y[0] = Math.max(y[0], MARGIN); + x[1] = Math.min(x[1], MARGIN+dim.width);y[1] = Math.max(y[1], MARGIN); + x[2] = Math.min(x[2], MARGIN+dim.width);y[2] = Math.min(y[2], MARGIN+dim.height); + x[3] = Math.max(x[3], MARGIN); y[3] = Math.min(y[3], MARGIN+dim.height); + + g.fillPolygon(x, y, 4); + } + } + else { + if (bPct) sz = sz * hits[i].getScalePctid(pctidLow); + g.drawOval((x1+x2)/2, (y1+y2)/2, sz, sz); + g.fillOval((x1+x2)/2, (y1+y2)/2, sz, sz); + } + } + + //draw blocks; draw Number; highlight selected; + Rectangle r2c = null; + if (tile != null && (fd.isShowBlocks() || fd.isShowBlkNum())){ + ABlock blk; + for (int i = tile.getNumBlocks(); i > 0; --i) { + blk = tile.getBlock(i); + rect.x = MARGIN + (int)(blk.getStart(X) * xPixelBP); + rect.y = MARGIN + (int)(blk.getStart(Y) * yPixelBP); + rect.width = MARGIN + (int)(blk.getEnd(X) * xPixelBP) - rect.x; + rect.height = MARGIN + (int)(blk.getEnd(Y) * yPixelBP) - rect.y; + + if (blk == data.getSelectedBlock()) { + g.setColor(SELECTED); + g.fillRect(rect.x,rect.y,rect.width+1,rect.height+1); + r2c = rect.getBounds(); + } + if (fd.isShowBlocks()) { + g.setColor(fd.getRectColor()); + g.drawRect(rect.x,rect.y,rect.width+1,rect.height+1); + } + if (fd.isShowBlkNum()) { + drawBlockNum(g, blk, rect); + } + } + } + + //draw dynamic selection + if (data.hasSelectedArea()) { + rect.x = MARGIN + (int)(data.getX1() * xPixelBP); + rect.y = MARGIN + (int)(data.getY1() * yPixelBP); + rect.width = MARGIN + (int)(data.getX2() * xPixelBP) - rect.x; + rect.height = MARGIN + (int)(data.getY2() * yPixelBP) - rect.y; + g.setColor(Color.BLACK); + g.drawRect(rect.x, rect.y, rect.width, rect.height); + g.setColor(SELECTED); + g.fillRect(rect.x+1, rect.y+1, rect.width-1, rect.height-1); + r2c = rect.getBounds(); + } + else if (isSelectingArea) { + g.setColor(Color.BLACK); + g.drawRect( Math.min(sX1,sX2), Math.min(sY1,sY2), + Math.max(sX1,sX2)-Math.min(sX1,sX2), Math.max(sY1,sY2)-Math.min(sY1,sY2)); + } + if (bPlusMinusScroll) { // Keep highlighted rectangle in view + bPlusMinusScroll=false; + + if (r2c!=null) { + final Rectangle rc = r2c; + SwingUtilities.invokeLater(() -> { // is off without this, especially with large N + JViewport vp = scroller.getViewport(); + Rectangle vpr = vp.getViewRect(); + + int x = rc.x - (vpr.width - rc.width)/2; + int y = rc.y - (vpr.height - rc.height)/2; + + x = Math.max(0, x); + y = Math.max(0, y); + x = Math.min(x, getWidth() - vpr.width); + y = Math.min(y, getHeight() - vpr.height); + vp.setViewPosition(new Point(x,y)); + }); + } + } + } + private boolean showHit(FilterData fd, DPHit ht) { + if (ht.isDiagHit()) return true; // isSelf, always draw diagonal + + cntHitsTot++; + if (ht.bothGene()) cnt2GeneTot++; + else if (ht.oneGene()) cnt1GeneTot++; + else cnt0GeneTot++; + + if (fd.isShowBlockHits() && !ht.isBlock()) return false; + + if (fd.isShowGene0() && !ht.noGene()) return false; + if (fd.isShowGene1() && !ht.oneGene()) return false; + if (fd.isShowGene2() && !ht.bothGene()) return false; + + if (ht.getPctid() < fd.getPctid()) return false; + + // all pass, do counts for summary + if (ht.isBlock()) { + cntHitBlk++; + if (ht.bothGene()) cnt2GeneBlk++; + else if (ht.oneGene()) cnt1GeneBlk++; + else if (ht.noGene()) cnt0GeneBlk++; + } + else { + cntHitNonBlk++; + if (ht.bothGene()) cnt2GeneNB++; + else if (ht.oneGene()) cnt1GeneNB++; + else if (ht.noGene()) cnt0GeneNB++; + } + return true; + } + + // Info + protected String prtCntsInfo() { + boolean p=false; + String b = String.format(""Block Hits %s Annotated: Both %s One %s None %s "", + pStr(cntHitBlk, cntHitsTot,p), pStr(cnt2GeneBlk, cntHitBlk,p), + pStr(cnt1GeneBlk, cntHitBlk,p), pStr(cnt0GeneBlk, cntHitBlk,p)); + + String nb = String.format(""!Block Hits %s Annotated: Both %s One %s None %s"", + pStr(cntHitNonBlk, cntHitsTot,p), pStr(cnt2GeneNB, cntHitNonBlk,p), + pStr(cnt1GeneNB, cntHitNonBlk,p), pStr(cnt0GeneNB, cntHitNonBlk,p)); + + String msg = (is2D) ? b + ""\n"" + nb : "" "" + b + nb; + + lastInfoMsg=msg; + return msg; + } + protected String prtCntsS() { + String w="">> "", x, b, nb, msg, fn=""""; + if (data.isTileView()) { + if (data.isSelf) { + w += data.getProject(X).getDisplayName() + "" self-synteny "" + data.getCurrentGrp(X).getFullName() + "" "" + data.getCurrentGrp(Y).getFullName(); + if (data.getCurrentGrp(X).getFullName().equals(data.getCurrentGrp(Y).getFullName())) + fn = ""\nStats cover both sides of diagonal""; + } + else { + w += data.getProject(X).getDisplayName() + "" "" + data.getCurrentGrp(X).getFullName() + "" "" + + data.getProject(Y).getDisplayName() + "" "" + data.getCurrentGrp(Y).getFullName(); + } + } + else { + if (data.isSelf) { + w += data.getProject(X).getDisplayName() + "" self-synteny ""; + fn = ""\nStats cover both sides of diagonal""; + } + else { + for (int i = 0; i < data.getNumProjects(); i++) + w += data.getProject(i).getDisplayName() + "" ""; + } + } + + w += String.format("" #Blocks=%,d %sId=%d\n"", cntBlocks, ""%"", (int) fd.getPctid()); + + String sz1 = getSize(cntHitsTot); + String sz2 = getSize(cnt2GeneTot); + String sz3 = getSize(cnt1GeneTot); + String sz4 = getSize(cnt0GeneTot); + String fmt = "" %-11s "" + sz1 + "" %s %-9s Both "" + sz2 + "" %14s One "" + sz3 + "" %14s None "" + sz4 + "" %12s\n""; + + boolean p=true; + String blank="" ""; //(xxx%) + x = String.format(fmt, + "" All Hits"", cntHitsTot, blank, ""Annotated"", + cnt2GeneTot, blank,cnt1GeneTot, blank, cnt0GeneTot, blank); + + b = String.format(fmt, + "" Block Hits"", cntHitBlk, ""(""+pStr(cntHitBlk, cntHitsTot,p)+"")"", """", + cnt2GeneBlk, pStr(cnt2GeneBlk, cnt2GeneTot, cntHitBlk), + cnt1GeneBlk, pStr(cnt1GeneBlk, cnt1GeneTot, cntHitBlk), + cnt0GeneBlk, pStr(cnt0GeneBlk, cnt0GeneTot, cntHitBlk)); + + nb = String.format(fmt, + ""!Block Hits"", cntHitNonBlk, ""(""+pStr(cntHitNonBlk, cntHitsTot,p)+"")"", """", + cnt2GeneNB, pStr(cnt2GeneNB, cnt2GeneTot,cntHitNonBlk), + cnt1GeneNB, pStr(cnt1GeneNB, cnt1GeneTot,cntHitNonBlk), + cnt0GeneNB, pStr(cnt0GeneNB, cnt0GeneTot,cntHitNonBlk)); + + msg = w + x + b + nb + fn; + return msg; + } + + private String pStr(int top, int bottom, boolean isP) { // isP=true for popup; + String ret=""""; + if (bottom==0) ret = ""n/a""; + else if (top==0) ret = ""0%""; + else { + double x = ((double)top/(double)bottom)*100.0; + if (isP) ret = String.format(""%4.1f%s"", x, ""%""); + else { + if (x>=99.5 && x<100.0) ret = String.format(""%4.1f%s"", x, ""%""); // don't let it round up to 100 + else if (x<1) ret = ""<1%""; + else ret = String.format(""%s"", Integer.toString((int) Math.round(x)) + ""%""); + } + } + if (isP) ret = String.format(""%5s"", ret); + return ret; + } + private String pStr(int top, int bottom, int bottom2) { + String x = pStr(top, bottom, true); + String y = pStr(top, bottom2, true); + return ""("" + x + "", "" + y + "")""; + } + + private String getSize(int n) { + int x = Integer.toString(n).length()+1; + return ""%,"" + x + ""d""; + } + private void drawBlockNum(Graphics g, ABlock blk, Rectangle r) { + FontMetrics fm = g.getFontMetrics(); // fm.stringWidth(s)=8, fm.getHeight()=17 + String s = blk.getNumber() + """"; + g.setColor(Color.BLACK); + g.setFont(BLK_FONT); + + int rx = r.x + (r.width/2); + int ry = r.y + (r.height/2); + + int low = MARGIN+(fm.getHeight()/2); + if (ry= Math.min(sX1, sX2) && x <= Math.max(sX1, sX2) && y >= Math.min(sY1, sY2) && y <= Math.max(sY1, sY2)) + { + data.show2dArea(); + } + else { + if (data.clearSelectedArea()) repaint(); + } + } + + public void mouseClicked(MouseEvent evt) { + if (evt.getButton() != MouseEvent.BUTTON1) return; + + long x = evt.getX(); + long y = evt.getY(); + + setDims(); + + long bpX = (long)((x-MARGIN)/xPixelBP); + long bpY = (long)((y-MARGIN)/yPixelBP); + + util.Jcomp.setCursorBusy(Plot.this, true); + + if (data.isTileView()) { // 2d-view + data.selectBlock(bpX, bpY); // If in a block, will set it as selected + repaint(); // Always repaint to remove highlight of previous selected block + } + else if (x >= MARGIN && x <= MARGIN+dim.width && y >= MARGIN && y <= MARGIN+dim.height) { + if (data.selectTile(bpX, bpY)) repaint(); + } + util.Jcomp.setCursorBusy(Plot.this, false); + } + + public void mouseReleased(MouseEvent arg0) { + if (!isSelectingArea) return; + + isSelectingArea = false; + if (sX1 > sX2) {int temp = sX1; sX1 = sX2; sX2 = temp;} + if (sY1 > sY2) {int temp = sY1; sY1 = sY2; sY2 = temp;} + + if (data.isTileView()) { + data.selectArea(dim,sX1-MARGIN,sY1-MARGIN,sX2-MARGIN,sY2-MARGIN); + repaint(); + } + } + public void mouseDragged(MouseEvent e) { + if (!data.isTileView()) return; + + sX2 = e.getX(); + sY2 = e.getY(); + + if (!isSelectingArea) { + isSelectingArea = true; + sX1 = sX2; + sY1 = sY2; + } + repaint(); + } + public void mouseEntered(MouseEvent e) { } + public void mouseExited(MouseEvent e) { } + public void mouseMoved(MouseEvent e) { } + } + /****************************************************************/ + // dotplot.properties was removed and hardcoded here + private static final Color FAR_BACKGROUND = Color.white; + private static final Color BACKGROUND = Color.white; + private static final Color BACKGROUND_BORDER = Color.black; + private static final Color SELECTED = new Color(247,233,213,200); + private static final Font PROJ_FONT = new Font(""Arial"",0,14); + private static final Font BLK_FONT = new Font(""Arial"",0,12); + + private static int MARGIN = 50; + private static final boolean HORZ = true, VERT = false; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/Data.java",".java","20468","592","package dotplot; + +import java.awt.Dimension; +import java.awt.Shape; +import java.awt.Color; +import java.awt.geom.Rectangle2D; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; + +import database.DBconn2; +import props.PropsDB; +import symap.Globals; +import symap.drawingpanel.SyMAP2d; +import symap.mapper.HfilterData; +import util.ErrorReport; +import util.Utilities; + +/** + * This contains the arrays of data (Project and Tile (chr-chr)) and interface code with Filter + * And the interface into calling 2D + */ +public class Data { + protected static final double DIAG_HIT = 200; + protected static final double DEFAULT_ZOOM = 0.99; + protected static final int X = 0, Y = 1; + private static int initMinPctid = -1; // find first time + + private Project projects[]; // loaded data + private Tile[] tiles; + + private Group currentGrp[]; // selected tile, 2 grps + private Project currentProjY; + private int maxGrps=0; + + private SyMAP2d symap; + private PropsDB projProps; + private FilterData filtData; + private ControlPanel cntl=null; + private boolean is2D=false; + + private double sX1, sX2, sY1, sY2; + private Shape selectedBlock; + private double zoomFactor, scaleFactor = 1; + private boolean hasSelectedArea, isTileView; + protected boolean bIsScaled=false; + + private DBconn2 tdbc2; + private DBload dbLoad; + protected boolean isSelf=false; + + // Called from DotPlotFrame; for ChrExp, called on first time its used + protected Data(DBconn2 dbc2, String type, boolean is2d) { + try { + tdbc2 = new DBconn2(""Dotplot"" + type + ""-"" + DBconn2.getNumConn(), dbc2); + this.is2D = is2d; + + dbLoad = new DBload(tdbc2); + + projProps = new PropsDB(dbc2); + + if (initMinPctid<=0) + initMinPctid = tdbc2.executeInteger(""select min(pctid) from pseudo_hits""); // set for slider + + } catch (Exception e) {ErrorReport.print(e, ""Unable to create SyMAP instance"");} + + projects = null; + tiles = new Tile[0]; + currentGrp = new Group[] {null,null}; + currentProjY = null; + + setHome(); + + filtData = new FilterData(); + } + /************************************************************* + * Called from: DotPlotFrame (genome), frame.ChrExpFrame (groups), Data.setReference (change ref) + * xGroupIDs, yGroupIDs null if genome + */ + public void initialize(int[] projIDs, int[] xGroupIDs, int[] yGroupIDs) { + try { + clear(); + + /* init projects*/ + Vector newProjects = new Vector(projIDs.length); + for (int i = 0; i < projIDs.length; i++) {// 1 -> 0 + Project p = new Project(projIDs[i], tdbc2); + newProjects.add( p ); + } + projects = newProjects.toArray(new Project[0]); + isSelf = projects.length==2 && projects[0].getID()== projects[1].getID(); + + dbLoad.loadGrpsAndBlocks(projects, xGroupIDs, yGroupIDs, projProps); // needs to redone for ref + for (Project p : projects) + maxGrps = Math.max(p.getNumGroups(), maxGrps); + + /* init tiles */ + tiles = Project.createTiles(projects, tiles, projProps); + + /* add blocks and hits to tiles */ + for (Tile tObj : tiles) { + boolean bSwap = projProps.isSwapped(tObj.getProjID(X), tObj.getProjID(Y)); // if DB.pairs.proj1_idx=proj(Y) + if (tObj.hasHits()) tObj.swap(tObj.getProjID(X), tObj.getProjID(Y)); + else { + dbLoad.loadBlocks(tObj, bSwap); + + dbLoad.loadHits(tObj, bSwap); + } + } + filtData.setBounds(dbLoad.minPctid, 100); + + if (getNumVisibleGroups() == 2) selectTile(100, 100); // kludge; this sets current... + + } catch (Exception e) { ErrorReport.print(e,""Initialize""); } + } + protected void setCntl(ControlPanel cntl) {this.cntl = cntl;} + /***************************************************************************/ + private void clear() { // initialize, kill + setHome(); + sX1 = sX2 = sY1 = sY2 = 0; + currentGrp[0] = currentGrp[1] = null; + currentProjY = null; + maxGrps = 0; + + tiles = new Tile[0]; + projects = null; + dbLoad.clear(); + } + /***********************************************************************/ + // Select for 2D + private void show2dBlock() { + if (selectedBlock==null) return; + + // can not do multiple 2d display + symap = new SyMAP2d(tdbc2, null); + symap.getDrawingPanel().setTracks(2); + + if (selectedBlock instanceof ABlock) { + ABlock ib = (ABlock)selectedBlock; + + Project pX = projects[X]; + Project pY = getCurrentProj(); + Group gX = ib.getGroup(X); + Group gY = ib.getGroup(Y); + + HfilterData hd = new HfilterData (); + hd.setForDP(ib.getNumber()); + symap.getDrawingPanel().setHitFilter(1,hd); // copy template + + symap.getDrawingPanel().setSequenceTrack(1,pY.getID(),gY.getID(),Color.CYAN); + symap.getDrawingPanel().setSequenceTrack(2,pX.getID(),gX.getID(),Color.GREEN); + + if (pY.getID()==pX.getID() && gX.getID()==gY.getID() && ib.getStart(X)>ib.getStart(Y)) {// shows the full chr; CAS576 + symap.getDrawingPanel().setTrackEnds(1,0,gY.getGrpLenBP()); + symap.getDrawingPanel().setTrackEnds(2,0,gX.getGrpLenBP()); + } + else { + symap.getDrawingPanel().setTrackEnds(1,ib.getStart(Y),ib.getEnd(Y)); + symap.getDrawingPanel().setTrackEnds(2,ib.getStart(X),ib.getEnd(X)); + } + symap.getFrame().showX(); + } + else { + Rectangle2D bounds = selectedBlock.getBounds2D(); + show2dArea(bounds.getMinX(),bounds.getMinY(),bounds.getMaxX(),bounds.getMaxY()); + } + } + + private void show2dArea(double x1, double y1, double x2, double y2) { + Project pX = projects[X]; + Project pY = getCurrentProj(); + String track[] = {"""",""""}; // group + for (int n = 0; n < 2; n++) { + track[n] = currentGrp[n].toString(); + } + if (track[X].length() == 0 || track[Y].length() == 0) { + System.out.println(""No Sequences found to display! x="" + track[X] + "" y="" + track[Y]); + return; + } + try { + symap = new SyMAP2d(tdbc2, null); + } catch (Exception e) {ErrorReport.print(e, ""Unable to create SyMAP instance"");} + + symap.getDrawingPanel().setTracks(2); + + HfilterData hd = new HfilterData(); // use 2D filter + hd.setForDP(0); // will show all; highlight blocks + symap.getDrawingPanel().setHitFilter(1,hd); // template for defaults + + symap.getDrawingPanel().setSequenceTrack(1,pY.getID(),Integer.parseInt(track[Y]),Color.CYAN); + symap.getDrawingPanel().setSequenceTrack(2,pX.getID(),Integer.parseInt(track[X]),Color.GREEN); + + if (pY.getID()==pX.getID() && currentGrp[X].getID()==currentGrp[Y].getID() && x1>y1) { + util.Popup.showInfoMsg(""Self-synteny"", ""You must select below the diagonal for self-chromosomes""); + return; + } + else { + symap.getDrawingPanel().setTrackEnds(1,y1,y2); + symap.getDrawingPanel().setTrackEnds(2,x1,x2); + } + symap.getFrame().showX(); + } + + /***************************************** + * DotPlotFrame + */ + protected Project[] getProjects() { return projects; } + + protected void kill() { + clear(); + tiles = new Tile[0]; + if (projects != null) { + for (Project p : projects) + if (p != null) p.setGroups(null); + } + + if (symap != null) symap = null; + tdbc2.close(); + } + + /***************************************** + * XXX Control + */ + protected void setHome() { + zoomFactor = DEFAULT_ZOOM; + hasSelectedArea = false; + isTileView = false; + selectedBlock = null; + bIsScaled = false; + scaleFactor = 1; + } + + protected void factorZoom(double mult) { zoomFactor *= mult;} // def 0.99 + + protected boolean isHome() { + boolean bAll = zoomFactor==DEFAULT_ZOOM && bIsScaled==false && scaleFactor==1; + if (is2D) return bAll; + return isTileView==false && bAll; + } + protected double getZoomFactor() { return zoomFactor; } // Sets scrollbars, sets dot size in Tile view + protected double getScaleFactor() { return scaleFactor; } + protected boolean isScaled() { return bIsScaled; } + + protected void setReference(Project reference) { + if (reference == projects[X]) + return; + + int[] newProjects = new int[projects.length]; + newProjects[0] = reference.getID(); + int i = 1; + for (Project p : projects) + if (p.getID() != reference.getID()) + newProjects[i++] = p.getID(); + + initialize(newProjects, null, null); + } + /*********************************************** + * XXX Plot + */ + protected boolean hasSelectedArea() {return hasSelectedArea;} + protected ABlock getSelectedBlock() {return (ABlock) selectedBlock;} + protected boolean isTileView() {return isTileView;} // plot and Control + + protected void show2dArea() {show2dArea(sX1,sY1,sX2,sY2);} + + // Plot.PlotListener mouseClick + protected boolean selectTile(long xUnits, long yUnits) { + if (projects[X] == null || projects[Y] == null) return false; + + currentGrp[X] = projects[X].getGroupByOffset(xUnits); + + currentGrp[Y] = getGroupByOffset(yUnits, getVisibleGroupsY(getVisibleGroups(X))); + currentProjY = getProjectByID(currentGrp[Y].getProjID()); + + if (currentGrp[X] != null && currentGrp[Y] != null && currentProjY != null) { + zoomFactor = DEFAULT_ZOOM; + isTileView = true; + } + if (cntl!=null) cntl.setEnable(); // update home button, null the 1st time from 2D + return true; + } + protected boolean selectBlock(double xUnits, double yUnits) { + Shape s = null; + if (filtData.isShowBlocks() && !hasSelectedArea && isTileView()) { + s = Tile.getBlock(tiles,currentGrp[X],currentGrp[Y],xUnits,yUnits); + + if (s != null) { + if (s == selectedBlock) show2dBlock(); + } + } + selectedBlock = s; + return (selectedBlock!=null); + } + protected boolean selectArea(Dimension size, double x1, double y1, double x2, double y2) { + double xmax = currentGrp[X].getGrpLenBP(); + double ymax = currentGrp[Y].getGrpLenBP(); + double xfactor = size.getWidth() / xmax; + double yfactor = size.getHeight() / ymax; + + selectedBlock = null; + this.sX1 = Math.min(x1,x2) / xfactor; + this.sX2 = Math.max(x1,x2) / xfactor; + this.sY1 = Math.min(y1,y2) / yfactor; + this.sY2 = Math.max(y1,y2) / yfactor; + + //keep inside bounds, or ignore if completely outside + if (this.sX1 < 0) this.sX1 = 0; + if (this.sY1 < 0) this.sY1 = 0; + if (this.sX2 > xmax) this.sX2 = xmax; + if (this.sY2 > ymax) this.sY2 = ymax; + + if (this.sX1 > xmax || this.sX2 < 0 || this.sY1 > ymax || this.sY2 < 0) hasSelectedArea = false; + else hasSelectedArea = true; + + return hasSelectedArea; + } + + protected boolean clearSelectedArea() { + boolean rc = hasSelectedArea; + hasSelectedArea = false; + return rc; + } + /***************************************************************************/ + protected boolean isGroupVisible(Group g) { // plot and data + return (g.isVisible() && (g.hasBlocks() || filtData.isShowEmpty())); + } + private boolean isGroupVisible(Group gY, Group[] gX) { // data + return (gY.isVisible() && (gY.hasBlocks(gX) || filtData.isShowEmpty())); + } + protected int getNumVisibleGroups() { // control and data + int count = 0; + for (Project p : projects) + count += p.getNumVisibleGroups(); + return count; + } + protected Group[] getVisibleGroups(int axis) { // plot and data + int num = getProject(axis).getNumGroups(); + Vector out = new Vector(num); + + for (int i = 1; i <= num ; i++) { + Group g = projects[axis].getGroupByOrder(i); + if (isGroupVisible(g)) + out.add(g); + } + + return out.toArray(new Group[0]); + } + protected Group[] getVisibleGroupsY(Group[] xGroups) { // plot and data + Vector out = new Vector(); + + if (isTileView) out.add(currentGrp[Y]); + else { + for (int axis = 1; axis < projects.length; axis++) { + int num = projects[axis].getNumGroups(); + for (int i = 1; i <= num ; i++) { + Group g = projects[axis].getGroupByOrder(i); + if (isGroupVisible(g, xGroups)) + out.add(g); + } + } + } + return out.toArray(new Group[0]); + } + protected long getVisibleGroupsSizeY(Group[] xGroups) { // plot.setDims + long size = 0; + for (Group g : getVisibleGroupsY(xGroups)) + size += g.getGrpLenBP(); + return size; + } + protected long getVisibleGroupsSize(int axis) { // plot.setDims + long size = 0; + for (Group g : getVisibleGroups(axis)) + size += g.getGrpLenBP(); + return size; + } + protected long getVisibleGroupsSize(int yAxis, Group[] xGroups) { // plot.paintComponenet + long size = 0; + for (Group g : getVisibleGroups(yAxis, xGroups)) + size += g.getGrpLenBP(); + return size; + } + private Group[] getVisibleGroups(int yAxis, Group[] xGroups) { // above + Vector out = new Vector(); + + int numGroups = projects[yAxis].getNumGroups(); + for (int i = 1; i <= numGroups ; i++) { + Group g = projects[yAxis].getGroupByOrder(i); + if (isGroupVisible(g, xGroups)) + out.add(g); + } + return out.toArray(new Group[0]); + } + /***************************************************************************/ + protected int getInitPctid() { return initMinPctid;} // Filter on startup; get the initial DB value + + protected FilterData getFilterData() { return filtData; } // plot and Filter.FilterListener + protected Project getProject(int axis) { return projects[axis]; } // plot and data + protected int getNumProjects() { return projects.length; } // plot and data + + protected Group getCurrentGrp(int axis) {return currentGrp[axis];} + protected Project getCurrentProj() {return currentProjY;} + protected int getCurrentGrpSize(int axis) { + return currentGrp[axis] == null ? 0 : currentGrp[axis].getGrpLenBP(); + } + protected int getMaxGrps() { return maxGrps;} + protected double getX1() { return sX1; } // plot + protected double getX2() { return sX2; } + protected double getY1() { return sY1; } + protected double getY2() { return sY2; } + protected Tile[] getTiles() { return tiles; } + + protected int getDotSize() {return filtData.getDotSize();} + + // Set in ControlPanel, read by Plot + private int statOpt=0; + protected void setStatOpts(int n) {statOpt = n;} + protected int getStatOpts() {return statOpt;} + + /******************************************************************/ + private static Group getGroupByOffset(long offset, Group[] groups) { + if (groups != null) + for (int i = groups.length-1; i >= 0; i--) + if (groups[i].getOffset() < offset) return groups[i]; + return null; + } + private Project getProjectByID(int id) { // Data.selectTile + for (Project p : projects) + if (p.getID() == id) + return p; + return null; + } + + /**************************************************** + * Loads data for the plot + */ + protected class DBload { + private final int X = Data.X, Y = Data.Y; + private int minPctid; + private DBconn2 tdbc2; + protected DBload(DBconn2 tdbc2) { + this.tdbc2 = tdbc2; + } + protected void clear() {minPctid=100;}; + + // For all projects; add groups to projects, and blocks to groups; + protected void loadGrpsAndBlocks(Project[] projects, int[] xGroupIDs, int[] yGroupIDs, PropsDB pp) { + try { + Vector list = new Vector(); + String qry; + ResultSet rs; + String groupList = null; + + // for each project, add groups + for (Project prj : projects) { + if (xGroupIDs != null && yGroupIDs != null) { // chromosomes only (from CE) + groupList = ""(""; + if (prj == projects[0]) groupList += Utilities.getCommaSepString(xGroupIDs); + else groupList += Utilities.getCommaSepString(yGroupIDs); + groupList += "")""; + } + String inGrp = (groupList == null) ? """" : "" AND g.idx IN "" + groupList; + + qry = ""SELECT g.idx, g.sort_order, g.name, g.fullname, p.length "" + + "" FROM xgroups AS g JOIN pseudos AS p ON (p.grp_idx=g.idx) "" + + "" WHERE g.proj_idx="" + prj.getID() + inGrp + + "" AND g.sort_order > 0 ORDER BY g.sort_order""; + + rs = tdbc2.executeQuery(qry); + while (rs.next()) { + int idx = rs.getInt(1); + Group g = prj.getGroupByID(idx); + if (g == null) + g = new Group(idx, rs.getInt(2), rs.getString(3), rs.getString(4), rs.getInt(5), prj.getID()); + list.add(g); + } + prj.setGroups( list.toArray(new Group[0]) ); + list.clear(); + rs.close(); + } + + if (xGroupIDs != null && yGroupIDs != null) + groupList = ""("" + Utilities.getCommaSepString(xGroupIDs) + "", "" + + Utilities.getCommaSepString(yGroupIDs) + "")""; + + // does the reference groupN have block with projectI groupM + Project pX = projects[X]; + for (int i = 0; i < projects.length; i++) { // start at 0 to include self-alignments + Project pY = projects[i]; + boolean swapped = pp.isSwapped(pX.getID(), pY.getID()); + String inGrp = (groupList == null) ? """" : "" AND g.idx IN "" + groupList; + int p1 = (swapped) ? pX.getID() : pY.getID(); + int p2 = (swapped) ? pY.getID() : pX.getID(); + + qry = ""SELECT b.grp1_idx, b.grp2_idx "" + + "" FROM blocks AS b "" + + "" JOIN xgroups AS g ON (g.idx=b.grp1_idx) "" + + "" WHERE (b.proj1_idx="" + p1 + "" AND b.proj2_idx="" + p2 + inGrp + + "" AND g.sort_order > 0) "" + + "" GROUP BY b.grp1_idx,b.grp2_idx""; + rs = tdbc2.executeQuery(qry); + while (rs.next()) { + int grp1_idx = rs.getInt(swapped ? 2 : 1); + int grp2_idx = rs.getInt(swapped ? 1 : 2); + Group g1 = pY.getGroupByID(grp1_idx); + Group g2 = pX.getGroupByID(grp2_idx); + if (g1 != null && g2 != null) { + g1.setHasBlocks(g2); + g2.setHasBlocks(g1); + } + } + rs.close(); + } + } + catch (Exception e) {ErrorReport.print(e, ""Loading projects and groups"");} + } + + // For this Tile: Add blocks to a tile (cell) + protected void loadBlocks(Tile tile, boolean swapped) { + try { + Group gX = (swapped ? tile.getGroup(Y) : tile.getGroup(X)); + Group gY = (swapped ? tile.getGroup(X) : tile.getGroup(Y)); + + String qry = ""SELECT blocknum, start2, end2, start1, end1 ""+ + ""FROM blocks WHERE grp1_idx=""+gY+"" AND grp2_idx=""+gX; + ResultSet rs = tdbc2.executeQuery(qry); + tile.clearBlocks(); + while (rs.next()) { + int start2 = rs.getInt(2); + int end2 = rs.getInt(3); + int start1 = rs.getInt(4); + int end1 = rs.getInt(5); + + tile.addBlock( + rs.getInt(1), // blocknum + swapped ? start1 : start2, // int sX + swapped ? end1 : end2, // int eX + swapped ? start2 : start1, // int sY + swapped ? end2 : end1); // int eY + } + rs.close(); + } + catch (Exception e) {ErrorReport.print(e, ""Loading Blocks"");} + } + // For this tile, Add hits + protected void loadHits(Tile tile, boolean swapped) { + try { + List hits = new ArrayList(); + int xx=X, yy=Y; + if (swapped) {xx=Y; yy=X;} + Project pX = tile.getProject(xx), pY = tile.getProject(yy); + Group gX = tile.getGroup(xx), gY = tile.getGroup(yy); + + String qry = ""SELECT (h.start2+h.end2)>>1 as posX, (h.start1+h.end1)>>1 as posY,"" + + ""h.pctid, h.gene_overlap, b.block_idx, (h.end2-h.start2) as length, h.strand "" + + ""FROM pseudo_hits AS h "" + + ""LEFT JOIN pseudo_block_hits AS b ON (h.idx=b.hit_idx) "" + + ""WHERE (h.proj1_idx="" + pY.getID() + "" AND h.proj2_idx="" + pX.getID()+ + "" AND h.grp1_idx="" + gY.getID() + "" AND h.grp2_idx="" + gX.getID()+"")""; + ResultSet rs = tdbc2.executeQuery(qry); + while (rs.next()) { + int posX = rs.getInt(1); + int posY = rs.getInt(2); + int pctid = rs.getInt(3); + int geneOlap = rs.getInt(4); + long blockidx = rs.getLong(5); + int length = rs.getInt(6); + String strand = rs.getString(7); + if (strand.equals(""+/-"") || strand.equals(""-/+"")) length = -length; + + DPHit hit = new DPHit(swapped ? posY : posX, + swapped ? posX : posY, + pctid, geneOlap, blockidx!=0, length); + hits.add(hit); + minPctid = Math.min(minPctid, pctid); + } + rs.close(); + + if (isSelf && gY.getID()==gX.getID()) {// create diagonal hit + int len = tdbc2.executeInteger(""select length from pseudos where grp_idx="" + gY.getID()); + DPHit hit = new DPHit(len/2, len/2, DIAG_HIT, 0, false, len); + hits.add(hit); + } + tile.setHits(hits.toArray(new DPHit[0])); + hits.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Loading Blocks""); } + } + } + // End DBload +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/Project.java",".java","2359","88","package dotplot; + +import java.util.Vector; +import database.DBconn2; +import props.PropsDB; +import symap.manager.Mproject; + +/*************************************************************** + * Called in Data for each selected project + * This uses the more global Mproject, but adds a little data and interface + */ +public class Project { + private int id; + private String displayName; + private String grpPrefix; + private Group[] groups; + + protected Project(int id, DBconn2 dbc2) { + Mproject tProj = new Mproject(dbc2, id, """", """"); + tProj.loadParamsFromDB(); + + this.id = id; + this.displayName = tProj.getDisplayName(); + this.grpPrefix = tProj.getGrpPrefix(); + } + // Data.DBload reads all data + protected void setGroups(Group[] grps) { + if (grps != null) Group.setOffsets(grps); + groups = grps; + } + + protected Group getGroupByOrder(int sortOrder) { + return groups == null ? null : groups[sortOrder-1]; + } + + protected Group getGroupByID(int id) { + if (groups != null) + for (Group g : groups) + if (g.getID() == id) return g; + return null; + } + + protected Group getGroupByOffset(double offset) { + if (groups != null) + for (int i = groups.length-1; i >= 0; i--) + if (groups[i].getOffset() < offset) return groups[i]; + return null; + } + + protected int getNumGroups() { + return groups == null ? 0 : groups.length; + } + + protected int getNumVisibleGroups() { + int count = 0; + for (Group g : groups) + if (g.isVisible()) count++; + return count; + } + + protected int getID() { return id; } + protected String getGrpPrefix() { return grpPrefix; } + protected String getDisplayName() { return displayName; } + public String toString() { return displayName; } + + public boolean equals(Object obj) { + return obj instanceof Project && ((Project)obj).id == id; + } + /***************************************************** + * Called in data.initialize to set up tiles + */ + protected static Tile[] createTiles(Project[] projects, Tile[] tiles, PropsDB pp) { + Vector out = new Vector(tiles.length); + Project pX = projects[0]; + for (int i = 1; i < projects.length; i++) { + Project pY = projects[i]; + for (Group gX : pX.groups) { + for (Group gY : pY.groups) { + Tile t = Tile.getTile(tiles, gX, gY); + if (t == null) t = new Tile(pX, pY, gX, gY); + out.add(t); + } + } + } + return out.toArray(new Tile[0]); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/dotplot/DotPlotFrame.java",".java","2822","80","package dotplot; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JFrame; +import javax.swing.WindowConstants; + +import colordialog.ColorDialogHandler; +import database.DBconn2; +import props.PersistentProps; +import symap.frame.HelpBar; + +/***************************************************************** + * Called from the SyMAP manager and Explorer + */ +public class DotPlotFrame extends JFrame { + private static final long serialVersionUID = 1L; + private Data data; + private PersistentProps persistentProps; + + // ManagerFrame for selected genomes + public DotPlotFrame(String title, DBconn2 dbc2, int projXIdx, int projYIdx) { + this(title, dbc2, new int[] { projXIdx, projYIdx }, null, null, null, true); + } + // ManagerFrame for all genomes, DotPlotFrame for chromosomes, ChrExpFrame for chromosomes; + public DotPlotFrame(String title, DBconn2 dbc2, int[] projIDs, + int[] xGroupIDs, int[] yGroupIDs, // null if whole genome + HelpBar helpBar, // not null if from CE + boolean hasRefSelector) // false if from CE + { + super(title); + if (projIDs==null || projIDs.length==0) System.err.println(""No Projects! Email symap@agcol.arizona.edu""); + + String type = (hasRefSelector) ? ""G"" : ""E""; // mark connections in Data + boolean is2D = (hasRefSelector) ? false : true; // for info display and Home + + data = new Data(dbc2, type, is2D); // created FilterData object + data.initialize(projIDs, xGroupIDs, yGroupIDs); + + HelpBar hb = (helpBar!=null) ? helpBar : new HelpBar(-1, 17); + + Plot plot = new Plot(data, hb, is2D); + + persistentProps = new PersistentProps(); // does not work unless this is global + ColorDialogHandler colorDialogHandler = new ColorDialogHandler(persistentProps); + colorDialogHandler.setDotPlot(); // Set in FilterData + + ControlPanel controls = new ControlPanel(data, plot, hb, colorDialogHandler); + data.setCntl(controls); + + if (hasRefSelector) controls.setProjects( data.getProjects() ); + else controls.setProjects(null); + + // Setup frame + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) { + if (data != null) data.kill(); + data = null; + controls.kill(); + } + }); + setLayout( new BorderLayout() ); + add( controls, BorderLayout.NORTH ); + add( plot.getScrollPane(),BorderLayout.CENTER ); + if (helpBar==null) add( hb, BorderLayout.SOUTH ); // otherwise, in CE on side + + Dimension dim = getToolkit().getScreenSize(); + setLocation(dim.width / 4,dim.height / 4); + } + public void clear() {// close connection from ChrExpFrame + if (data != null) data.kill(); + data = null; + } + public Data getData() { return data; } // ChrExpFrame +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/props/PersistentProps.java",".java","2473","90","package props; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Properties; + +import util.ErrorReport; +import util.FileDir; + +/************************************************************* + * This reads/writes from user.dir/.symap_saved_props + * ColorDialog.setColors() getProp; setCookie() setProp and deleteProp; name=SyMapColors + * symapQuery.FieldData setColumnDefaults(), saveColumnDefaults(); name=SyMapColumns1 and name=SyMapColumns2 + * SyMAPframe, name=SyMAPDisplayPosition + * + * PropertiesReader reads from /properties + */ +public class PersistentProps { + private Properties props; + private File file; + private String name; + + public static final String PERSISTENT_PROPS_FILE = symap.Globals.PERSISTENT_PROPS_FILE; + private static final String PP_HEADER = ""SyMAP Saved Properties. Do not modify.""; + + public PersistentProps() { + file = FileDir.getFile(PERSISTENT_PROPS_FILE,true); + props = new Properties(); + readProps(props,file); + } + + public PersistentProps copy(String name) { + return new PersistentProps(props, file, name); + }; + private PersistentProps(Properties props, File file, String name) { + this.file = file; + this.props = props; + this.name = name; + } + + public boolean equals(Object obj) { + if (obj instanceof PersistentProps) { + PersistentProps ch = (PersistentProps)obj; + return (ch.file==file && ch.props==props && ch.name==name); + } + return false; + } + + public String getName() {return name;} + public void setName(String name) {this.name = name;} + + public String getProp() { + synchronized (props) { + return props.getProperty(name); + } + } + + public void setProp(String value) { + synchronized (props) { + props.setProperty(name,value); + writeProps(props,file); + } + } + public void deleteProp() { + synchronized (props) { + props.remove(name); + writeProps(props,file); + } + } + private synchronized static void readProps(Properties props, File file) { + try { + if (file.isFile()) + props.load(new FileInputStream(file)); + } + catch (Exception e) { + ErrorReport.print(e, ""Reading "" + PERSISTENT_PROPS_FILE); + } + } + private synchronized static void writeProps(Properties props, File file) { + try { + props.store(new FileOutputStream(file),PP_HEADER); + } + catch (Exception e) { + ErrorReport.print(e, ""Writing "" + PERSISTENT_PROPS_FILE); + } + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/props/PropertiesReader.java",".java","1922","75","package props; + +import java.awt.Color; +import java.io.IOException; +import java.io.File; +import java.io.FileInputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.Properties; +import java.util.StringTokenizer; + +import util.ErrorReport; + +/** + * Class PropertiesReader handles getting values from properties files + */ +public class PropertiesReader extends Properties { + private static final long serialVersionUID = 1L; + + // colorDialog + public PropertiesReader(URL url) { + super(); + try { + load(url.openStream()); + fixProps(); + } catch (IOException e) { + ErrorReport.print(e, ""PropertiesReader unable to load ""+url); + } + } + // ManagerFrame: read symap.config + // Mproject: get and update project params file + // Mpair: read pair params file + public PropertiesReader(File file) { + super(); + try { + load(new FileInputStream(file)); + fixProps(); + } catch (IOException e) { + ErrorReport.print(e, ""PropertiesReader unable to load ""+file); + } + } + + public String getString(String key) { + String s = (String)getProperty(key); + if (s != null) s = s.trim(); + if (s != null) s = s.intern(); + return s; + } + + public Color getColor(String key) { + return parseColor((String)getProperty(key)); + } + + private void fixProps() { + for (Enumeration e = propertyNames(); e.hasMoreElements(); ) { + String propName = e.nextElement().toString(); + String val = getProperty(propName); + if (val.contains(""#"")) { + val = val.replaceAll(""#.*"",""""); + setProperty(propName,val); + } + } + } + private Color parseColor(String colorString) { + StringTokenizer st = new StringTokenizer(colorString, "",""); + int r = Integer.decode(st.nextToken()).intValue(); + int g = Integer.decode(st.nextToken()).intValue(); + int b = Integer.decode(st.nextToken()).intValue(); + int a = 255; + if (st.hasMoreTokens()) + a = Integer.decode(st.nextToken()).intValue(); + return new Color(r, g, b, a); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/props/PropsDB.java",".java","5390","185","package props; + +import java.util.Vector; + +import java.util.Properties; +import java.sql.ResultSet; + +import database.DBconn2; +import util.ErrorReport; + +/****************************************************** + * Used by Explorer and one call in dotplot; it read proj_props, plus check for pairs + * dbProp contains everything in the proj_props DB table + * Vector of pairs, Array of projects + */ +public class PropsDB { + private DatabaseProperties dbProjProp; + private Vector pairs; + private Project[] projects; + private DBconn2 dbc2; + + public PropsDB(DBconn2 dbc2) { // DrawingPanel and Dotplot.Data + this.dbc2 = dbc2; + pairs = new Vector(); + dbProjProp = new DatabaseProperties(); + load(); + } + private void load() { + try { + pairs.clear(); + + // Projects + dbProjProp.loadAllProps(dbc2); + + Vector pvector = new Vector(); + + ResultSet rs = null; + int id, p1id, p2id; + + rs = dbc2.executeQuery(""select idx,type,name from projects""); + while (rs.next()) { + id = rs.getInt(1); + pvector.add(new Project(id,rs.getString(3),rs.getString(2))); + } + rs.close(); + + if (!pvector.isEmpty()) { + projects = new Project[pvector.size()]; + projects = (Project[])pvector.toArray(projects); + } + // Pairs + rs = dbc2.executeQuery(""SELECT idx,proj1_idx,proj2_idx FROM pairs""); + while (rs.next()) { + p1id = rs.getInt(2); + p2id = rs.getInt(3); + pairs.add( new Pair(rs.getInt(1), p1id, p2id) ); + } + + for (Pair pp : pairs) {// for Sequence popup + String x = dbc2.executeString(""select value from pair_props where name='algo1' and pair_idx="" + pp.pid); + pp.isAlgo1 = (x!=null) ? x.equals(""1"") : true; + x = dbc2.executeString(""select value from pair_props where name='number_pseudo' and pair_idx="" + pp.pid); + pp.hasPseudo = (x!=null) ? x.equals(""1"") : false; + } + rs.close(); + } + catch (Exception e) {ErrorReport.print(e, ""Project pool reset"");} + } + + public int getPairIdx(int pp1, int pp2) { // MapperPool to check version + if (hasPair(pp1, pp2)) return getPair(pp1, pp2).pid; + if (hasPair(pp2, pp1)) return getPair(pp2, pp1).pid; + return -1; + } + public boolean isAlgo1(int pp1, int pp2) { + if (hasPair(pp1, pp2)) return getPair(pp1, pp2).isAlgo1; + if (hasPair(pp2, pp1)) return getPair(pp2, pp1).isAlgo1; + return false; + } + public String getProperty(int projectID, String property) { // Sequence + return dbProjProp.getProperty((Object) projectID,property); + } + public String getName(int projectID) { // Sequence + for (int i = 0; i < projects.length; i++) { + if (projects[i].id == projectID) return projects[i].name; + } + return null; + } + public String getDisplayName(int projectID) { // Sequence + return getProperty(projectID,""display_name""); + } + public boolean hasPair(int p1, int p2) { // MapperPool + for (Pair pp : pairs) { + if (pp.p1 == p1 && pp.p2 == p2) + return true; + } + return false; + } + public boolean hasPseudo(int pp1, int pp2) { // MapperPool + if (hasPair(pp1, pp2)) return getPair(pp1, pp2).hasPseudo; + if (hasPair(pp2, pp1)) return getPair(pp2, pp1).hasPseudo; + return false; + } + public boolean isSwapped(int pX, int pY) { // Data + Pair pair = getPair(pX, pY); + return (pair == null || pX == pair.getP1()); + } + private Pair getPair(int p1, int p2) { + for (Pair pp : pairs) { + if ((pp.getP1() == p1 && pp.getP2() == p2) || (pp.getP1() == p2 && pp.getP2() == p1)) + return pp; + } + return null; + } + ///////////////////////////////////////////////////////////////////// + protected class Project { + protected int id; + protected String name; + protected String type; + + protected Project(int id, String name, String type) { + this.id = id; + if (name == null) this.name = """"; + else this.name = name; + this.type = type.intern(); + } + + public boolean equals(Object obj) { + return obj instanceof Project && ((Project)obj).id == id; + } + } + private class Pair { + private int p1, p2; + private int pid; + private boolean isAlgo1=false; + private boolean hasPseudo=false; // for MapperPool to know if need to set annot_hits annot_idx to 0 + + protected Pair(int pid, int p1, int p2) { + this.pid = pid; + this.p1 = p1; + this.p2 = p2; + } + + protected int getP1() { return p1; } + protected int getP2() { return p2; } + + public String toString() { return ""[ProjectPair: ""+pid+"" (""+p1+"",""+p2+"")]""; } + } + + /** + * Class DatabaseProperties can load properties from a database for quick access. + */ + private class DatabaseProperties extends Properties { + private static final long serialVersionUID = 1L; + public static final String SEPARATOR = "":##:""; + + private DatabaseProperties() {super();} + + private void loadAllProps(DBconn2 dbc2) throws Exception { + ResultSet rs = null; + try { + rs = dbc2.executeQuery(""SELECT proj_idx, name, value from proj_props""); + while (rs.next()) { + setProperty(rs.getObject(1),rs.getString(2),rs.getString(3)); + } + } + finally { + if (rs != null) { + try { rs.close();} catch (Exception e) { } + rs = null; + } + } + } + protected String getProperty(Object id, String name) { + return getProperty(getKey(id,name)); + } + private Object setProperty(Object ids, String name, String value) { + return setProperty(getKey(ids,name),value); + } + private String getKey(Object id, String name) { + return new StringBuffer().append(id).append(SEPARATOR).append(name).toString(); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/circview/ControlPanelCirc.java",".java","19721","500","package circview; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.ActionEvent; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButton; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JSeparator; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import colordialog.ColorDialogHandler; +import props.PersistentProps; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import util.ImageViewer; +import util.Jcomp; +import util.Popup; +import util.Utilities; + +/******************************************************************* + * Control Panel for Circle View + */ +public class ControlPanelCirc extends JPanel implements HelpListener { + private static final long serialVersionUID = 1L; + private CircPanel circPanel; + private HelpBar helpPanel; + + private JButton homeButton, plusButton, minusButton, rotateLButton, rotateRButton; + private JButton helpButton, saveButton, infoButton; + private JButton scaleToggle, rotateToggle, revToggle, selfToggle; + + private JButton viewPopupButton; + private String[] actOptions = {""All blocks"",""Inverted only"",""Non-inverted only"",""Two-color all blocks""}; + private JRadioButtonMenuItem view0Radio = new JRadioButtonMenuItem(actOptions[0]); + private JRadioButtonMenuItem view1Radio = new JRadioButtonMenuItem(actOptions[1]); + private JRadioButtonMenuItem view2Radio = new JRadioButtonMenuItem(actOptions[2]); + private JRadioButtonMenuItem view3Radio = new JRadioButtonMenuItem(actOptions[3]); + + private JButton colorButton; + private ColorDialogHandler cdh; + private PersistentProps persistentProps; + + + public ControlPanelCirc(CircPanel cp, HelpBar hb, boolean bIsWG, + boolean isSelf, boolean hasSelf) { // isSelf - only self align; hasSelf - at least one project has self align + helpPanel = hb; + circPanel = cp; + circPanel.bShowSelf = isSelf; // turn on showing self since isSelf + + persistentProps = new PersistentProps(); // does not work unless this is global + cdh = new ColorDialogHandler(persistentProps); // needs to be called on creation to init non-default colors + + homeButton = Jcomp.createIconButton(null, helpPanel, buttonListener, ""/images/home.gif"", + ""Home: Reset to original size settings.""); + homeButton.setEnabled(false); + + minusButton = Jcomp.createIconButton(null, helpPanel, buttonListener, ""/images/minus.gif"", + ""Decrease the circle size.""); + plusButton = Jcomp.createIconButton(null, helpPanel, buttonListener, ""/images/plus.gif"", + ""Increase the circle size.""); + String msg = (bIsWG) ? ""genome size."" : ""chromosome size.""; + scaleToggle = Jcomp.createBorderIconButton(null, helpPanel, buttonListener, ""/images/scale.gif"", + ""Toggle: Scale to the "" + msg); + + rotateRButton = Jcomp.createIconButton(null, helpPanel, buttonListener,""/images/rotate-right.png"", + ""Rotate the image clock-wise.""); + rotateLButton = Jcomp.createIconButton(null, helpPanel, buttonListener,""/images/rotate-left.png"", + ""Rotate the image counter-clock-wise.""); + + rotateToggle = Jcomp.createBorderButton(null, helpPanel, buttonListener,""Rotate"", + ""Toggle: Rotate the text.""); + + colorButton = Jcomp.createIconButton(null, helpPanel, buttonListener,""/images/colorPalette.png"", + ""Menu of ways to alter block colors.""); + colorButton.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + new ChgColor(); + } + }); + + viewPopupButton = Jcomp.createButtonGray(this,helpPanel, null /*has own listener*/,""View"", + ""Click button for menu of options""); + createViewPopup(); + + selfToggle = Jcomp.createBorderButton(null, helpPanel, buttonListener, ""Self-align"", + ""Toggle: Show self-alignment synteny blocks""); + if (isSelf) { + circPanel.bShowSelf = isSelf; + selfToggle.setBackground(Jcomp.getBorderColor(isSelf)); + } + revToggle = Jcomp.createBorderButton(null,helpPanel,buttonListener,""Reverse"", + ""Toggle: Reverse reference, which re-assigns reference colors""); + + saveButton = Jcomp.createIconButton(this,helpPanel,buttonListener,""/images/print.gif"", + ""Save image"" ); + infoButton = Jcomp.createIconButton(this,helpPanel,buttonListener,""/images/info.png"", + ""Quick Circle Help"" ); + helpButton = util.Jhtml.createHelpIconUserLg(util.Jhtml.circle); + + //// build row /////////// + JPanel row = Jcomp.createRowPanelGray(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + setLayout(gbl); // If row.setLayout(gbl), cannot add Separators, but ipadx, etc work + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.gridheight = 1; + gbc.ipadx = 0; + gbc.ipady = 0; + + String sp1="" "", sp2="" ""; + addToGrid(row, gbl,gbc,homeButton, sp2); + addToGrid(row, gbl,gbc,plusButton, sp1); + addToGrid(row, gbl,gbc,minusButton, sp2); + addToGrid(row, gbl,gbc,rotateRButton,sp1); + addToGrid(row, gbl,gbc,rotateLButton,sp1); + addToGrid(row, gbl,gbc,rotateToggle, sp2); + addToGrid(row, gbl,gbc,scaleToggle, sp2); // needs extra space between image + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp1); // End home functions + + addToGrid(row, gbl,gbc,viewPopupButton, sp1); + if (hasSelf) addToGrid(row, gbl,gbc,selfToggle,sp1); // only if there is self + if (bIsWG && !isSelf) addToGrid(row, gbl,gbc,revToggle, sp2); // only for whole genome + addToGrid(row, gbl,gbc,colorButton, sp2); + addToGrid(row, gbl, gbc, new JSeparator(JSeparator.VERTICAL), sp2); // end alter display + + addToGrid(row, gbl,gbc,saveButton,sp1); + addToGrid(row, gbl,gbc,helpButton,sp1); + addToGrid(row, gbl,gbc,infoButton,sp1); + + add(row); + } + private void addToGrid(JPanel cp, GridBagLayout gbl, GridBagConstraints gbc, Component comp, String blank) { + gbl.setConstraints(comp,gbc); + cp.add(comp); + if (blank.length()>0) addToGrid(cp, gbl,gbc,new JLabel(blank), """"); + } + private void createViewPopup() { + PopupListener listener = new PopupListener(); + view0Radio.addActionListener(listener); + view1Radio.addActionListener(listener); + view2Radio.addActionListener(listener); + view3Radio.addActionListener(listener); + + JPopupMenu popupMenu = new JPopupMenu(); + popupMenu.setBackground(symap.Globals.white); + + JMenuItem popupTitle = new JMenuItem(); + popupTitle.setText(""Select View""); + popupTitle.setEnabled(false); + popupMenu.add(popupTitle); + popupMenu.addSeparator(); + + popupMenu.add(view0Radio); + popupMenu.add(view1Radio); + popupMenu.add(view2Radio); + popupMenu.add(view3Radio); + + ButtonGroup grp = new ButtonGroup(); + grp.add(view0Radio); grp.add(view1Radio); grp.add(view2Radio); grp.add(view3Radio); + + viewPopupButton.setComponentPopupMenu(popupMenu); // zoomPopupButton create in main + viewPopupButton.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + popupMenu.show(e.getComponent(), e.getX(), e.getY()); + } + }); + + Dimension d = new Dimension(100, 25); // w,d + viewPopupButton.setPreferredSize(d); + viewPopupButton.setMaximumSize(d); + viewPopupButton.setMinimumSize(d); + + viewPopupButton.setText(actOptions[0]); + view0Radio.setSelected(true); + } + /********************************************************************** + * Action + */ + private class PopupListener implements ActionListener { + private PopupListener() { } + public void actionPerformed(ActionEvent event) { + Object src = event.getSource(); + int idx=0; + if (src==view0Radio) idx=0; + else if (src==view1Radio) idx=1; + else if (src==view2Radio) idx=2; + else if (src==view3Radio) idx=3; + else return; + + circPanel.invChoice = idx; + viewPopupButton.setText(actOptions[idx]); + circPanel.makeRepaint(); + } + } + private ActionListener buttonListener = new ActionListener() { + public void actionPerformed(ActionEvent evt) { + Object src = evt.getSource(); + if (src == homeButton) { + resetToHome(); + circPanel.makeRepaint(); + } + else if (src == minusButton) circPanel.zoom(0.95); + else if (src == plusButton) circPanel.zoom(1.05); + else if (src == rotateRButton) circPanel.rotate(-circPanel.ARC_INC); + else if (src == rotateLButton) circPanel.rotate(circPanel.ARC_INC); + else if (src == scaleToggle) { + circPanel.bToScale = !circPanel.bToScale; + scaleToggle.setBackground(Jcomp.getBorderColor(circPanel.bToScale)); + circPanel.makeRepaint(); + } + else if (src == rotateToggle) { + circPanel.bRotateText = !circPanel.bRotateText; + rotateToggle.setBackground(Jcomp.getBorderColor(circPanel.bRotateText)); + circPanel.makeRepaint(); + } + else if (src == revToggle) { + circPanel.bRevRef = !circPanel.bRevRef; + revToggle.setBackground(Jcomp.getBorderColor(circPanel.bRevRef)); + + circPanel.reverse(); + circPanel.makeRepaint(); + } + else if (src == selfToggle){ + circPanel.bShowSelf = !circPanel.bShowSelf; + selfToggle.setBackground(Jcomp.getBorderColor(circPanel.bShowSelf)); + circPanel.makeRepaint(); + } + else if (src == saveButton) { + ImageViewer.showImage(""Circle"", circPanel); + } + else if (src == infoButton) { + popupHelp(); + } + setEnables(); + } + }; + private void setEnables() { + homeButton.setEnabled(!circPanel.isHome()); + } + private void resetToHome() { + rotateToggle.setBackground(Jcomp.getBorderColor(false)); + scaleToggle.setBackground(Jcomp.getBorderColor(false)); + circPanel.resetToHome(); // arc, zoom, rotate, scale + // The following are not part of Home: + // revToggle.setBackground(Jcomp.getBorderColor(false)); + // selfToggle.setBackground(Jcomp.getBorderColor(bIsSelf)); + // viewPopupButton.setText(invOptions[0]); + } + + ///////////////////////////////////////////////////////////////// + protected void setLastParams(int inv, boolean self, boolean rotate, boolean scale) { + viewPopupButton.setText(actOptions[inv]); + selfToggle.setSelected(self); selfToggle.setBackground(Jcomp.getBorderColor(self)); + scaleToggle.setSelected(scale); scaleToggle.setBackground(Jcomp.getBorderColor(scale)); + rotateToggle.setSelected(rotate); rotateToggle.setBackground(Jcomp.getBorderColor(rotate)); + + homeButton.setEnabled(!circPanel.isHome()); + } + public String getHelpText(MouseEvent event) { + Component comp = (Component)event.getSource(); + return comp.getName(); + } + private void popupHelp() { + String msg = ""Move the mouse cursor over project name and click "" + + ""\n to color the blocks by the project's chromosome colors."" + + ""\n\nClick on an arc to bring its blocks to the top. "" + + ""\nDouble-click an arc to only show its blocks. To undo, "" + + ""\n click an arc or a project name."" + + ""\n\nSee ? for details.\n""; + + Popup.displayInfoMonoSpace(this, ""Quick Circle Help"", msg, false); + } + private class ChgColor extends JDialog implements ActionListener { + private static final long serialVersionUID = 1L; + private JButton okButton, defButton, cancelButton, info2Button; + private JRadioButton set1Radio, set2Radio; + private JRadioButton orderRadio, reverseRadio, shuffleRadio, noneRadio; + private JCheckBox scaleBox; + private JTextField txtScale, txtShuffle; + private JButton editColorButton; + + private ChgColor() { + super(); + setModal(false); + setTitle(""Circle Colors""); + setResizable(true); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) {} + }); + JPanel optionPanel = Jcomp.createPagePanel(); + + JPanel row0 = Jcomp.createRowPanel(); + cdh.setCircle(); + editColorButton = Jcomp.createBorderIconButton(""/images/colorchooser.gif"", ""Edit the color settings""); + editColorButton.addActionListener(this); + row0.add(new JLabel(""Two-color all blocks: "")); + row0.add(editColorButton); + optionPanel.add(row0); + optionPanel.add(new JSeparator()); + + int h=5; + JPanel row1 = Jcomp.createRowPanel(); + set1Radio = Jcomp.createRadio(""Color Set 1"", ""Lighter colors""); + set2Radio = Jcomp.createRadio(""Color Set 2"", ""Darker colors""); + ButtonGroup grp = new ButtonGroup (); + grp.add(set1Radio); grp.add(set2Radio); + set1Radio.setSelected(circPanel.colorSet==1); + set2Radio.setSelected(circPanel.colorSet==2); + row1.add(set1Radio); row1.add(Box.createHorizontalStrut(h)); row1.add(set2Radio); + optionPanel.add(row1); optionPanel.add(Box.createVerticalStrut(3)); + + JPanel row2 = Jcomp.createRowPanel(); + scaleBox = Jcomp.createCheckBox(""Scale"", ""< 1 darker, >1 lighter"", circPanel.bScaleColors); + txtScale = Jcomp.createTextField(circPanel.scaleColors+"""", 3); + row2.add(scaleBox); row2.add(txtScale); + optionPanel.add(row2); optionPanel.add(Box.createVerticalStrut(3)); + + JPanel row3 = Jcomp.createRowPanel(); + orderRadio = Jcomp.createRadio(""Order"", ""Sorts the colors so the blue-green colors are shown first""); + reverseRadio = Jcomp.createRadio(""Reverse"", ""Sorts the colors so the yellow-red colors are shown first""); + + txtShuffle = Jcomp.createTextField(circPanel.seed+"""", 2); + shuffleRadio = Jcomp.createRadio(""Shuffle"", ""Randomize the colors""); + noneRadio = Jcomp.createRadio(""None"", ""No action""); + + row3.add(orderRadio); row3.add(Box.createHorizontalStrut(h)); + row3.add(reverseRadio); row3.add(Box.createHorizontalStrut(h)); + row3.add(shuffleRadio); row3.add(txtShuffle); row3.add(Box.createHorizontalStrut(h)); + row3.add(noneRadio); row3.add(Box.createHorizontalStrut(h)); + optionPanel.add(row3); optionPanel.add(Box.createVerticalStrut(8)); + + ButtonGroup grp3 = new ButtonGroup (); + grp3.add(orderRadio);grp3.add(reverseRadio);grp3.add(shuffleRadio);grp3.add(noneRadio); + if (circPanel.bOrder) orderRadio.setSelected(true); + else if (circPanel.bRevOrder) reverseRadio.setSelected(true); + else if (circPanel.bShuffle) shuffleRadio.setSelected(true); + else noneRadio.setSelected(true); + + // Save, cancel, Default + okButton = Jcomp.createButton(""Save"", ""Save and redisplay""); + okButton.addActionListener(this); + + cancelButton = Jcomp.createButton(""Cancel"", ""Cancel""); + cancelButton.addActionListener(this); + + defButton = Jcomp.createButton(""Defaults"", ""Set defaults""); + defButton.addActionListener(this); + + info2Button = Jcomp.createIconButton(null,helpPanel,buttonListener,""/images/info.png"", + ""Quick Circle Color Help"" ); + info2Button.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + popupHelp2(); + } + }); + JPanel row = new JPanel(); row.setBackground(Color.white); + row.add(okButton); + row.add(cancelButton); + row.add(defButton); + row.add(info2Button); + + JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.setBackground(Color.white); + buttonPanel.add(new JSeparator(), ""North""); + buttonPanel.add(row, ""Center""); + + Container cp = getContentPane(); + GridBagLayout gbl = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + cp.setLayout(gbl); + gbc.fill = 2; + gbc.gridheight = 1; + gbc.ipadx = 5; + gbc.ipady = 8; + int rem = GridBagConstraints.REMAINDER; + + addToGrid(cp, gbl, gbc, optionPanel, rem); + addToGrid(cp, gbl, gbc, buttonPanel, rem); + pack(); + + setModal(true); + setBackground(Color.white); + setResizable(false); + setAlwaysOnTop(true); // doesn't work on Ubuntu + setLocationRelativeTo(null); + setVisible(true); + } + private void addToGrid(Container c, GridBagLayout gbl, GridBagConstraints gbc, Component comp, int i) { + gbc.gridwidth = i; + gbl.setConstraints(comp,gbc); + c.add(comp); + } + public void actionPerformed(ActionEvent e) { + if (e.getSource() == editColorButton) { + cdh.showX(); + } + else if (e.getSource() == okButton) { + circPanel.colorSet = (set1Radio.isSelected()) ? 1 : 2; + + circPanel.bOrder = orderRadio.isSelected(); + circPanel.bRevOrder = reverseRadio.isSelected(); + + circPanel.bScaleColors = scaleBox.isSelected(); + if (circPanel.bScaleColors) { + double d = -1.0; + try { + d = Double.parseDouble(txtScale.getText()); + } catch (Exception ex) {d= -1;} + if (d<0) { + Popup.showErrorMessage(""Invalid 'Scale' value; must be a real positive number.""); + return; + } + circPanel.scaleColors = d; + } + circPanel.bShuffle = shuffleRadio.isSelected(); + if (circPanel.bShuffle) { + int s = 0; + try { + s = Integer.parseInt(txtShuffle.getText()); + } catch (Exception ex) {s = 0;} + if (s<=0) { + Popup.showErrorMessage(""Invalid 'Shuffle' value; must be positive integer.""); + return; + } + circPanel.seed = s; + } + circPanel.makeNewColorVec(); + circPanel.saveColors(); + circPanel.makeRepaint(); + setVisible(false); + } + else if (e.getSource() == defButton) { // same defaults as set in CircPanel + set1Radio.setSelected(true); + + noneRadio.setSelected(true); scaleBox.setSelected(false); + + txtScale.setText(""0.8""); txtShuffle.setText(""1""); + } + else if (e.getSource() == cancelButton) { + if (circPanel.colorSet==1) set1Radio.isSelected(); + else set2Radio.isSelected(); + + orderRadio.setSelected(circPanel.bOrder); + reverseRadio.setSelected(circPanel.bShuffle); + + shuffleRadio.setSelected(circPanel.bShuffle); + txtShuffle.setText(circPanel.seed+""""); + + scaleBox.setSelected(circPanel.bScaleColors); + txtScale.setText(circPanel.scaleColors+""""); + + setVisible(false); + } + } + private void popupHelp2() { + String msg = ""The 'Two-color all blocks' pull-down option:\n"" + + "" colors the inverted and non-inverted blocks different colors.\n"" + + "" Set the colors with the Color Wheel; this uses the Color Wheel 'Save' and\n"" + + "" the Circle Color 'Save'. The Wheel must be closed before the Circle Color.\n\n"" + + + ""Set 1 and Set 2 are two sets of 100 colors each.\n\n"" + + + ""Scale < 1 makes the colors darker, >1 makes them lighter.\n\n"" + + + ""Order sorts the colors so the blue-green colors are shown first.\n"" + + ""Reverse sorts the colors so the yellow-red colors are shown first.\n\n"" + + + ""Shuffle randomizes the 100 colors, where a different constant\n"" + + "" produces a different set.\n\n"" + + + ""The color settings are saved between sessions.\n"" + ; + + Popup.displayInfoMonoSpace(this, ""Quick Circle Help"", msg, false); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/circview/CircPanel.java",".java","30693","883","package circview; + +import java.sql.ResultSet; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import java.awt.geom.GeneralPath; +import java.awt.geom.Arc2D; +import java.awt.geom.AffineTransform; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import java.util.Vector; +import java.util.TreeMap; +import java.util.TreeSet; + +import database.DBconn2; +import props.PersistentProps; +import props.PropertiesReader; +import symap.Globals; +import symap.frame.HelpBar; +import symap.frame.HelpListener; +import symap.manager.Mproject; +import util.ErrorReport; +import util.Utilities; + +/************************************************************** + * Draws the circle view for Selected-2-WG and 2D-N-chr + */ +public class CircPanel extends JPanel implements HelpListener, MouseListener,MouseMotionListener { + private static final long serialVersionUID = -1711255873365895293L; + static private String propName=""SyMAPcircle""; + + // ControlPanelCirc has Info popup with this + private final String helpText = ""Click a project name to use its colors.\n"" + + ""Click an arc to bring its blocks to the top.""; + private final String helpName = ""Click a project name to use its colors for the blocks.""; + private final String helpArc = ""Click an arc to bring its blocks to the top."" + + ""\nDouble click an arc to only show its blocks.\n""; + protected final double ZOOM_DEFAULT = 1.0; + protected final int ARC_DEFAULT = 0, ARC_INC=5; + + // set from ControlPanelCirc; these defaults are also set in ControlPanelCirc + protected int invChoice = 0; + protected boolean bShowSelf = false, bRotateText = false, bRevRef = false; + protected boolean bToScale = false; // genome size + protected double zoom = ZOOM_DEFAULT; // +/- icons + private int arc0 = ARC_DEFAULT; // rotate icon + + // ControlPanelCirc color popup; default values, if changed, changed in Default button; saved in .symap_props + protected int colorSet=1; // ColorSet 1 or 2; + protected boolean bOrder=false, bRevOrder=false, bShuffle=false, bScaleColors=false; + protected double scaleColors=0.8; + protected int seed = 1; + + private CircFrame frame; + private DBconn2 dbc2; + private Vector colorVec; + + private Vector allProjVec; + private TreeMap idx2GrpMap; + private Vector priorityVec; + + private int rOuter, rInner, rBlock; // rOuter based on rotateText,; rInner=rOuter*0.933; rBlock=rOuter*0.917; + private int cX, cY; // both are rOuter+marginX; set at beginning and do not change + + private JScrollPane scroller; + private HelpBar helpPanel = null; + + private void dprt(String msg) {symap.Globals.dprt(""CP: "" + msg);} + + public CircPanel(CircFrame frame, DBconn2 dbc2, HelpBar hb, int[] projIdxList, int refIdx, + TreeSet selGrpSet, double [] lastParams) { // selGrpSet is for 2D + this.frame = frame; + this.dbc2 = dbc2; + this.helpPanel = hb; + + setBackground(Color.white); + + scroller = new JScrollPane(this); + scroller.setBackground(Color.white); + scroller.getViewport().setBackground(Color.white); + scroller.getVerticalScrollBar().setUnitIncrement(10); + + helpPanel.addHelpListener(this); + addMouseListener(this); + addMouseMotionListener(this); + + try { + if (selGrpSet!=null && selGrpSet.size()>1) setLastParams(lastParams); // use previous Home settings when same ref + if (!initDS(projIdxList, selGrpSet, refIdx)) return; // create allProjVec, idx2GrpMap, priortyVec + } + catch(Exception e) {ErrorReport.print(e, ""Create CircPanel"");} + } + /**************************************************************************** + * XXX Setup and database load; called in 2D every time left panel changes + **************************************************************************/ + private boolean initDS(int[] projIdxList, TreeSet selGrpSet, int refIdx) { + try { + // Projects and groups + allProjVec = new Vector(); + idx2GrpMap = new TreeMap (); + + for (int i = 0; i < projIdxList.length; i++){ //allProjVec, allGrpsVec,idx2GrpMap + if (projIdxList[i] > 0) { + addProject(projIdxList[i]); + } + } + + if (selGrpSet != null){ // From 2d - selected chromosomes + for (Group g : idx2GrpMap.values()){ + g.isSel = selGrpSet.contains(g.idx); + } + } + for (Project p : allProjVec) p.setTotalSize(); + + priorityVec = new Vector(); + priorityVec.add(refIdx); // initial reference has priority colors + for (Project p : allProjVec){ + if (p.idx!=refIdx) priorityVec.add(p.idx); + } + + setChrColorIdx(); // does not need colorVec, only allProjVec + if (!initColorsFromProps()) return false; // color params are saved in .symap_props + makeNewColorVec(); // create colorVec, use allGrpVec; + + // Blocks + loadBlocks(); + return true; + } + catch(Exception e) {ErrorReport.print(e, ""Init data structures""); return false;} + } + + private void addProject(int idx) { + try { + ResultSet rs; + rs = dbc2.executeQuery(""select name from projects where idx="" + idx); + if (!rs.next()) { + System.out.println(""Cannot find proj_idx="" + idx); + return; + } + + Project proj = new Project(idx, rs.getString(1), dbc2); // loads groups + allProjVec.add(proj); + + for (Group g : proj.grps) idx2GrpMap.put(g.idx, g); + } + catch(Exception e) {ErrorReport.print(e, ""Add project for Circle Panel"");} + } + // try to make them always with same color regardless of comparison + private void setChrColorIdx() { + try { + int maxGrps=0; + for (Project p : allProjVec) maxGrps = Math.max(maxGrps, p.grps.size()); + + if (allProjVec.size() <=4 && maxGrps<=25) { + int i=0; + int [] start = {0,24,49,74}; + for (Project p : allProjVec) { + int inc = start[i]; + for (Group g : p.grps) g.colorIdx= inc++; + i++; + } + } + else { + int inc=0; + for (Project p : allProjVec) { + for (Group g : p.grps) g.colorIdx= inc++; + } + } + } + catch(Exception e) {ErrorReport.print(e, ""Set colors"");} + } + // Get the blocks in both directions since order is unknown + private void loadBlocks() { + try { + ResultSet rs; + String sql = ""select grp1_idx, grp2_idx, start1, end1, start2, end2, corr from blocks ""; + + for (int i1 = 0; i1 < allProjVec.size(); i1++) { + Project p1 = allProjVec.get(i1); + + for (int i2 = i1; i2 < allProjVec.size(); i2++) { + Project p2 = allProjVec.get(i2); + + rs = dbc2.executeQuery(sql + "" where proj1_idx="" + p1.idx + "" and proj2_idx="" + p2.idx ); + while (rs.next()) { + addBlock(rs.getInt(1), rs.getInt(2), rs.getInt(3),rs.getInt(4),rs.getInt(5),rs.getInt(6),(rs.getFloat(7)<0)); + } + + if (p1.idx != p2.idx) { + rs = dbc2.executeQuery(sql + "" where proj1_idx="" + p2.idx + "" and proj2_idx="" + p1.idx ); + while (rs.next()) { + addBlock(rs.getInt(1), rs.getInt(2), rs.getInt(3),rs.getInt(4),rs.getInt(5),rs.getInt(6),(rs.getFloat(7)<0)); + } + } + } + } + } + catch(Exception e) {ErrorReport.print(e, ""Add project for Circle Panel"");} + } + private void addBlock(int gidx1, int gidx2, int s1, int e1, int s2, int e2, boolean inv) { + Block b = new Block(gidx1, gidx2, s1, e1, s2, e2, inv); + + Group grp = idx2GrpMap.get(gidx1); + grp.addBlock(b); + } + protected JScrollPane getScrollPane() {return scroller;} + + /***************************************************** + * Load/Save colors + */ + private boolean initColorsFromProps() { + try { + PersistentProps cookies = new PersistentProps(); + String propSaved = cookies.copy(propName).getProp(); + if (propSaved==null) return true; // use defaults + + String [] tok = propSaved.split("":""); + if (tok.length!=4) return true; // use defaults + + if (tok[0].equals(""1"")) colorSet=1; + else if (tok[0].equals(""2"")) colorSet=2; + + if (!tok[1].equals(""0"")) { + double s = Utilities.getDouble(tok[1]); + if (s>0) { + bScaleColors=true; + scaleColors = s; + } + } + if (!tok[2].equals(""0"")) { + if (tok[2].equals(""1"")) bOrder=true; + else if (tok[2].equals(""2"")) bRevOrder=true; + else if (tok[2].equals(""3"")) { + bShuffle=true; + int s = Utilities.getInt(tok[3]); + if (s>0) seed=s; + } + } + return true; + } + catch(Exception e) {ErrorReport.print(e, ""Init colors""); return false;} + } + protected void makeNewColorVec() { // ControlPanelCirc.ChgColor + colorVec = frame.getColorVec(colorSet, bScaleColors, scaleColors, bOrder, bRevOrder, bShuffle, seed);; + + int nColors = 0; + for (Project p : allProjVec) nColors += p.grps.size(); + while (colorVec.size() < nColors) colorVec.addAll(colorVec); // duplicates set if >100 chromosomes + } + // int invChoice; boolean bShowSelf, bRotateText, bToScale, bShowSelf; double zoom; int arc0 + // invChoice is set in ControlPanelCirc in CircFrame; the rest are directly used + protected double [] getLastParams() { // called from CircFrame to reuse in the next CircFrame + double [] lp = new double [7]; + lp[0] = (double) invChoice; + lp[1] = (bShowSelf) ? 1 : 0; + lp[2] = (bRotateText) ? 1 : 0; + lp[3] = (bToScale) ? 1 : 0; + lp[4] = (bShowSelf) ? 1 : 0; + lp[5] = zoom; + lp[6] = arc0; + + return lp; + } + protected void setLastParams(double [] lp) { + if (lp==null || lp.length!=7) return; + + invChoice = (int) lp[0]; + bShowSelf = (lp[1]==1); + bRotateText = (lp[2]==1); + bToScale = (lp[3]==1); + bShowSelf = (lp[4]==1); + zoom = lp[5]; + arc0 = (int) lp[6]; + } + protected void saveColors() { // on ControlPanelCirc.Save + PersistentProps cookies = new PersistentProps(); + PersistentProps allCook = cookies.copy(propName); + + String c=colorSet + "":""; + c += (bScaleColors) ? scaleColors + "":"" : ""0:""; + + if (bOrder) c += ""1:0""; + else if (bRevOrder) c+= ""2:0""; + else if (bShuffle) c+= ""3:"" + seed; + else c += ""0:0""; + + allCook.setProp(c); + } + + /******************************************************************* + * Control - toggles are directly changed from ControlPanel + *****************************************************************/ + protected void zoom (double f) { // -/= icons + zoom *= f; + if (zoom<0.3) zoom=0.3; + else if (zoom>2.5) zoom=2.5; + makeRepaint(); + } + protected void rotate(int da) { + arc0 += da; + if (Math.abs(arc0)>=360) arc0=0; + makeRepaint(); + } + protected void reverse() { // reverse reference; only available for 2 WG view + try { + Project p1 = allProjVec.get(0); + Project p2 = allProjVec.get(1); + allProjVec.clear(); + allProjVec.add(p2); + allProjVec.add(p1); + + setChrColorIdx(); + } + catch (Exception e) {ErrorReport.print(e, ""Reverse projects"");} + } + /*************************************************** + * XXX Mouse + */ + public void handleClick(long x, long y, boolean dbl) {} + + public void mouseClicked(MouseEvent evt) { // Click arc or project name + int xRel = (int)evt.getX() - cX; + int yRel = (int)evt.getY() - cY; + + int r = (int)Math.sqrt(xRel*xRel + yRel*yRel); + + int angle = -arc0 + (int)(180*Math.atan2(-yRel,xRel)/Math.PI); + if (angle < 0) angle += 360; + + Group grp = overGroupArc(r,angle); + + boolean dbl = (evt.getClickCount() > 1); + + if (grp != null) { // clicked the group arc + for (Group g1 : idx2GrpMap.values()) { + g1.onTop = false; + g1.onlyShow = false; + + if (g1 == grp) { + g1.onTop = true; + if (dbl) g1.onlyShow = true; + } + } + makeRepaint(); + return; + } + + Project p = overProjName(r,angle, (int)evt.getX(), (int)evt.getY()); + if (p == null) return; + + // click the project name; use priority projects colors + priorityVec.add(0,p.idx); + int i = 1; + for (; i < priorityVec.size();i++) { + if (priorityVec.get(i) == p.idx) break; + } + priorityVec.remove(i); + for (Project p1 : allProjVec) + for (Group g1 : p1.grps) g1.onTop=g1.onlyShow=false; + + makeRepaint(); + } + + public void mouseMoved(MouseEvent e) { + if (helpPanel == null) return; + + int xRel = (int)e.getX() - cX; + int yRel = (int)e.getY() - cY; + int r = (int)Math.sqrt(xRel*xRel + yRel*yRel); + int angle = -arc0 + (int)(180*Math.atan2(-yRel,xRel)/Math.PI); + if (angle < 0) angle += 360; + Group grp = overGroupArc(r,angle); + + if (grp != null) { + setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) ); + helpPanel.setHelp(helpArc,this); + } + else { + Project p = overProjName(r,angle,(int)e.getX(), (int)e.getY()); + if (p != null) { + setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) ); + helpPanel.setHelp(helpName, this); + } + else{ + setCursor( Cursor.getDefaultCursor() ); + helpPanel.setHelp(helpText, this); + } + } + } + private Group overGroupArc(int r, int angle) { // mouse over arc + if (r <= rOuter && r >= rInner) { + for (Group g : idx2GrpMap.values()){ + if (angle >= g.a1 && angle <= g.a2) return g; + } + } + return null; + } + private Project overProjName(int r, int angle, int x, int y){ + int x1 = (bRotateText) ? r : x; + int x2 = (bRotateText) ? angle : y; + + for (Project p : allProjVec){ + if (x1 >= p.labelR1 && x1 <= p.labelR2){ + if (x2 >= p.labelA1 && x2 <= p.labelA2) return p; + } + } + + return null; + } + public void mousePressed(MouseEvent e) {} + public void mouseReleased(MouseEvent e) {} + public void mouseDragged(MouseEvent e) {} + public void mouseEntered(MouseEvent e) { } + public void mouseExited(MouseEvent e) {setCursor( Cursor.getDefaultCursor() ); } + + /************************************************************************************ + * XXX Painting methods + ********************************************************************************/ + + protected void makeRepaint() {repaint();} // ControlPanelCirc + + // Note that circle angles are measured from the middle-right of the circle, going around counterclockwise. + // Hence, the right side of the circle is angle 0-90, plus angle 270-360. Arc0 is added to everything. + public void paintComponent(Graphics g) { + super.paintComponent(g); + + final int PROJ_EMPTY_ARC = 20; + + // Setup + Dimension d = new Dimension( (int)(scroller.getWidth()*zoom), (int)(scroller.getHeight()*zoom) ); + Dimension dimCircle = new Dimension(d.width-20, d.height-20); + + int maxNameW = 0; + FontMetrics fm = g.getFontMetrics(); + for (Project p : allProjVec) { + int nw = (int)(fm.getStringBounds(p.displayName,g).getWidth()) + + (int)(fm.getStringBounds(p.maxGrpName,g).getWidth()); + if (nw > maxNameW) maxNameW = nw; + } + + Dimension dd = new Dimension(d.width+maxNameW-20, d.height-20); + setPreferredSize(dd); + revalidate(); + scroller.getViewport().revalidate(); + + int center = Math.min(dimCircle.width, dimCircle.height)/2; + rOuter = center - 100; + rInner = (int)(rOuter*0.933); + rBlock = (int)(rOuter*0.917); + int off = (allProjVec.size()%2==1) ? (maxNameW/2) : 15; // 1,3,5... will use name + cX = center + off; + cY = center; + + int cXrOuter = cX-rOuter, cYrOuter = cY-rOuter; + int cXrInner = cX-rInner, cYrInner = cY-rInner; + int rOuter2 = rOuter*2, rInner2 = rInner*2; + + Graphics2D g2 = (Graphics2D) g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + + double totalSizeShown = 0; + int nEmpty = 0; + + for (Project prjObj : allProjVec) { + if (prjObj.projSizeShown == 0) nEmpty++; + else totalSizeShown += prjObj.projSizeShown; + } + if (totalSizeShown == 0) {System.out.println(""Nothing to show!"");return;} + + int curArc = 0, curColor = 0; // increments through projects + + // Loop through projects draw name, arc, ribbons + for (Project prjObj : allProjVec) { + int projArc = 360/allProjVec.size(); + + if (bToScale) { + if (prjObj.projSizeShown == 0) { + projArc = PROJ_EMPTY_ARC; + } + else { + double empty = (360.0 - ((double)(nEmpty*PROJ_EMPTY_ARC))); + projArc = (int) Math.floor((empty*prjObj.projSizeShown)/totalSizeShown); + } + } + + if (prjObj.projSizeShown == 0) { // on 2D, no chr selected for this project + g.drawArc(cXrOuter, cYrOuter, rOuter2, rOuter2, curArc, projArc-1);//x,y,w,h, rotate, extent + g.drawArc(cXrInner-1, cYrInner-1, rInner2+2, rInner2+2, curArc, projArc-1); + + g.drawLine((int) circX(cX, rInner, curArc), (int)circY(cY, rInner, curArc), + (int) circX(cX, rOuter, curArc), (int)circY(cY, rOuter, curArc)); + int endArc = curArc+projArc-1; + g.drawLine((int) circX(cX, rInner+1, endArc), (int)circY(cY, rInner+1, endArc), + (int) circX(cX, rOuter, endArc), (int)circY(cY, rOuter, endArc)); + } + + int nextArc = curArc + projArc; + if (nextArc > 360) nextArc = 360; + + // Project name + int sp = (bRotateText) ? 40 : 20; + int midArc = (curArc + nextArc)/2; + paintProjName(g, prjObj, midArc, rOuter + sp); // Sets font for name and chromosome numbers + + prjObj.setGrpArc(curArc, nextArc-1, curColor); // set start/end of grps; this makes a 1 degree gap between projects + + Font f = g.getFont(); + + // Loop through chromosomes to draw chr# and chr outer arc + for (Group grpObj : prjObj.grps) { + if (!grpObj.isSel) continue; + if (grpObj.colorIdx>=colorVec.size()) { + dprt(""Color out of range "" + grpObj.colorIdx + "" "" + colorVec.size()); + grpObj.colorIdx=colorVec.size()-1; + } + g.setColor(new Color(colorVec.get(grpObj.colorIdx))); + g.fillArc(cXrOuter, cYrOuter, rOuter2, rOuter2, arc0+grpObj.a1, grpObj.a2-grpObj.a1); + g.setColor(Color.black); + + double aMid = arc0 + (grpObj.a1 + grpObj.a2)/2; + + if (bRotateText) { + double rotAngle = 90 - aMid; + while (rotAngle > 360) {rotAngle -= 360;} + while (rotAngle < 0) {rotAngle += 360;} + + AffineTransform rot = AffineTransform.getRotateInstance(rotAngle*Math.PI/180); + Font fRot = g.getFont().deriveFont(rot); + g.setFont(fRot); + g.drawString(grpObj.grpName, (int)circX(cX,rOuter+10,aMid), (int)circY(cY,rOuter+10,aMid)); + g.setFont(f); + } + else { + while (aMid > 360) {aMid -= 360;} + while (aMid < 0) {aMid += 360;} + + // Make arc measure with zero point vertical + double vArc = aMid - 90; + while (vArc > 360) {vArc -= 360;} + while (vArc < 0) {vArc += 360;} + + double grW = fm.getStringBounds(grpObj.grpName,g).getWidth(); + + int pX = (int)circX(cX,rOuter+10,aMid); + int pY = (int)circY(cY,rOuter+10,aMid); + + pX -= (int)(grW* (1.0-Math.abs(aMid-180.0)/180.0)); // (((double)grW)*Math.sin(aMid*Math.PI/360)); + pY += (int)(10.0*(1.0-Math.abs(vArc-180.0)/180.0)); // 0 at the top, 10 at the bottom; + + g.drawString(grpObj.grpName, pX, pY); + } + } + + curColor += prjObj.grps.size(); + curArc = nextArc; + } // end loop through projects + + //////// Paint ribbons ///////// + g.setColor(Color.white); + g.fillArc(cXrInner, cYrInner, rInner2, rInner2, 0, 360); + + float alpha = 0.7f; + g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); + + boolean showOne = false, onTop = false; + for (Group grp : idx2GrpMap.values()) { + if (grp.onlyShow) { + showOne = onTop = true; + break; + } + else if (grp.onTop) onTop = true; + } + + // NOTE: blocks are assigned to only one chromosome of the ribbon pair + // Group Loop 1: paint the non-on-top groups. + if (!showOne) { + for (Group grp : idx2GrpMap.values()) { + if (!grp.isSel) continue; + + for (Block b : grp.blocks) { + if (invChoice == 1 && !b.inverted) continue; + if (invChoice == 2 && b.inverted) continue; + + Group grp1 = idx2GrpMap.get(b.gidx1); + Group grp2 = idx2GrpMap.get(b.gidx2); + + if (!bShowSelf && (grp1.proj_idx == grp2.proj_idx)) continue; + + if (!grp1.isSel || !grp2.isSel) continue; + + if (grp1.onTop || grp2.onTop) continue; + + paintGroupBlk(g, g2, grp1, grp2, b); + } + } + } + // Group Loop 2: paint the on-top group. + if (onTop) { + for (Group grp : idx2GrpMap.values()) { + if (!grp.isSel) continue; + + for (Block b : grp.blocks) { + if (invChoice == 1 && !b.inverted) continue; + if (invChoice == 2 && b.inverted) continue; + + Group grp1 = idx2GrpMap.get(b.gidx1); + Group grp2 = idx2GrpMap.get(b.gidx2); + if (!bShowSelf && (grp1.proj_idx == grp2.proj_idx)) continue; + + if (!grp1.isSel || !grp2.isSel) continue; + + if (grp.onTop || grp2.onTop) + paintGroupBlk(g, g2, grp1, grp2, b); + } + } + } + } + // Paint Block + private void paintGroupBlk(Graphics g, Graphics2D g2, Group grp1, Group grp2, Block blk) { + + int cidx = (colorFirstPriority(grp1.proj_idx, grp2.proj_idx) ? grp1.colorIdx : grp2.colorIdx); + if (invChoice != 3) g.setColor(new Color(colorVec.get(cidx))); + else g.setColor(blk.inverted ? blockN : blockP); + + int s1 = grp1.arcLoc(blk.s1); + int e1 = grp1.arcLoc(blk.e1); + int s2 = grp2.arcLoc(blk.s2); + int e2 = grp2.arcLoc(blk.e2); + int cXrBlk = cX-rBlock, cYrBlk = cY-rBlock, rBlk2 = 2*rBlock; + int s1arc0 = s1 + arc0, e1arc0 = e1 + arc0, s2arc0 = s2 + arc0, e2arc0 = e2 + arc0; + + GeneralPath gp = new GeneralPath(); + + gp.moveTo(circX(cX, rBlock, s1arc0), circY(cY, rBlock, s1arc0)); + + Arc2D arc1 = new Arc2D.Double(cXrBlk, cYrBlk, rBlk2, rBlk2, s1arc0, e1-s1, Arc2D.OPEN);//x,y,w,h,arc,extent + gp.append(arc1, true); + + gp.quadTo(circX(cX, 0, e1arc0), circY(cY, 0, e1arc0), circX(cX, rBlock, s2arc0), circY(cY, rBlock, s2arc0)); + + Arc2D arc2 = new Arc2D.Double(cXrBlk, cYrBlk, rBlk2, rBlk2, s2arc0, e2-s2, Arc2D.OPEN); + gp.append(arc2, true); + + gp.quadTo(circX(cX, 0, e2arc0), circY(cY, 0, e2arc0), circX(cX, rBlock, s1arc0), circY(cY, rBlock, s1arc0)); + + gp.closePath(); + g2.fill(gp); + } + // Paint project name + private void paintProjName(Graphics g, Project prjObj, int midArc, int locLabel) { + g.setColor(Color.black); + + Font f = g.getFont(); + f = setProjFont(0, f, prjObj.idx); + g.setFont(f); + + FontMetrics fm = g.getFontMetrics(); + int nameH = (int) (fm.getStringBounds(prjObj.displayName,g).getHeight()); + int nameW = (int) (fm.getStringBounds(prjObj.displayName,g).getWidth()); + + if (bRotateText) { + int unrotW = (int) (nameW/2); + int nameArcW = 0; + if (unrotW > 0 && unrotW < 200) // exclude pathological values + nameArcW = (int)((180/Math.PI) * Math.atan(((double)unrotW/(double)(locLabel)))); + else dprt(""Special case for "" + prjObj.displayName + "" "" + unrotW ); + + // Put the angle within 0-360 range for texts that do not work mod 360 + double rotAngle = 90 - midArc - arc0; + while (rotAngle > 360) {rotAngle -= 360;} + while (rotAngle < 0) {rotAngle += 360;} + + int arc = midArc + arc0 + nameArcW; + int nameX = (int) circX(cX, locLabel, arc); + int nameY = (int) circY(cY, locLabel, arc); + + AffineTransform rot = AffineTransform.getRotateInstance(rotAngle*Math.PI/180); + Font fRot = g.getFont().deriveFont(rot); + g.setFont(fRot); + g.drawString(prjObj.displayName, nameX, nameY); + g.setFont(f); + + // mouse over coords; finger occurs passed the name in all 4 directions, but also right on text. + prjObj.labelR1 = locLabel - nameH; + prjObj.labelR2 = locLabel + nameH; + prjObj.labelA1 = midArc - nameArcW; + prjObj.labelA2 = midArc + nameArcW; + } + else { + double correctedArc = midArc + arc0; + while (correctedArc > 360) {correctedArc -= 360;} + while (correctedArc < 0) {correctedArc += 360;} + + // Make arc measure with zero point vertical + double vArc = correctedArc - 90; + while (vArc > 360) {vArc -= 360;} + while (vArc < 0) {vArc += 360;} + + int nameX = (int) circX(cX, rOuter + 40, correctedArc); + int nameY = (int) circY(cY, rOuter + 40, correctedArc); + + int xOff = (int)(nameW*(1.0-Math.abs(correctedArc-180.0)/180.0)); // 0 at the right, 1 at the left + nameX -= xOff; + int yOff = (int)(10.0*(1.0-Math.abs(vArc-180.0)/180.0)); // 0 at the top, 10 at the bottom; + nameY += yOff; + + g.drawString(prjObj.displayName,nameX,nameY); + + // mouse-over coords; + prjObj.labelR1 = nameX - 1; + prjObj.labelR2 = nameX + nameW; + prjObj.labelA1 = nameY - nameH; // x,y is lower left + prjObj.labelA2 = nameY + 1; + } + f = setProjFont(1, f, prjObj.idx); + g.setFont (f); + } + // Set font based on priority; 2nd is italics because its colors are given used for project 2 to project 3. + private Font setProjFont(int i, Font f, int pidx) { + int x = (i==0) ? 16 : 14; + + if (priorityVec.get(0) == pidx) f = new Font (""Courier"", Font.BOLD | Font.ITALIC, x); + else if (priorityVec.size()>2 && priorityVec.get(1) == pidx) f = new Font (""Courier"", Font.ITALIC, x); + else f = new Font (""Courier"", Font.PLAIN, x); + + return f; + } + private int circX(int cX, int R, double arc){ + return cX + (int)(R * Math.cos(2*Math.PI*arc/360)); + } + private int circY(int cY, int R, double arc) { + return cY - (int)(R * Math.sin(2*Math.PI*arc/360)); // y increases down + } + // Click Project Name: returns true if first project has color priority, i.e. group colors are used for blocks + private boolean colorFirstPriority(int idx1, int idx2) { + for (int idx : priorityVec) { + if (idx == idx1) return true; + if (idx == idx2) return false; + } + return true; + } + ////////////////////////////////////////////////////////////// + protected void clear() {idx2GrpMap.clear();} + + protected void resetToHome() { + zoom = ZOOM_DEFAULT; + arc0 = ARC_DEFAULT; + bToScale = bRotateText = false; + } + protected boolean isHome() { + return zoom==ZOOM_DEFAULT && arc0==ARC_DEFAULT && !bToScale && !bRotateText; + } + public String getHelpText(MouseEvent event) { return helpText;} // frame.HelpBar + /************************************************************************ + * Classes + **********************************************************************/ + private class Project { + private int idx; + + private String displayName; // load from db + private Vector grps = new Vector(); // load from db + private String maxGrpName=""""; + private double projSizeShown = 0; // selected groups in 2D + + private int labelR1,labelR2,labelA1,labelA2; // mouse-over coords; set in paintProjText + + private Project(int idx, String name, DBconn2 dbc2) { + try { + this.idx = idx; + + ResultSet rs = dbc2.executeQuery(""select idx, name, length from xgroups join pseudos "" + + "" on pseudos.grp_idx=xgroups.idx where xgroups.proj_idx="" + idx + "" order by sort_order""); + + while (rs.next()){ + Group g = new Group(rs.getInt(3), rs.getInt(1), idx, rs.getString(2), name); + grps.add(g); + if (g.grpName.length()>maxGrpName.length()) maxGrpName=g.grpName; + } + + Mproject tProj = new Mproject(); + String display_name = tProj.getKey(tProj.sDisplay); + + displayName = name; + rs = dbc2.executeQuery(""select value from proj_props where name='""+display_name+""' and proj_idx="" + idx); + if (rs.next()) displayName = rs.getString(1); + } + catch (Exception e) {ErrorReport.print(e, ""Getting project"");} + } + + private void setTotalSize() { + for (Group g : grps){ + if (g.isSel) projSizeShown += ((double)g.size); + } + } + private void setGrpArc(int a1, int a2, int cidx){ + int cnt = 0, nShown = 0; + for (Group g : grps) + if (g.isSel) nShown++; + + double arcLen = a2 - a1; + double a = a1; + double grpSize = 0; + + for (Group g : grps) { + if (!g.isSel) continue; + + grpSize += g.size; + cnt++; + double grpEndPos = (arcLen*grpSize) / projSizeShown; + + long b; + if (cnt < nShown) b = a1 + (long)(Math.round(grpEndPos)); + else b = a2; + + g.a1 = (int) a; + g.a2 = (int) b; + + a = b; + } + } + }// end project class + + // Chromosome and respective blocks + private class Group { + private double size; + private int idx, proj_idx; + private String grpName; + private int a1, a2; // Assigned values in setGrpArc during paintComponent + private int colorIdx = -1; // index into color vector + private boolean isSel = true; // 2D is selected + private boolean onTop = false, onlyShow = false; // click, double click + private Vector blocks = new Vector (); + + private Group(int size, int idx, int proj_idx, String name, String pname){ + this.size = size; + this.idx = idx; + this.proj_idx = proj_idx; + this.grpName = name; // chromosome number + } + private void addBlock(Block b) {blocks.add(b);} + + private int arcLoc(double bpLoc) { // paintArc + double a = a2 - a1 + 1; + double arcLoc = ((a*bpLoc)/((double)size)); + return a1 + (int)arcLoc; + } + } + private class Block { + private int s1, e1, s2, e2; + private int gidx1, gidx2; + private boolean inverted; + + private Block(int gidx1, int gidx2, int s1, int e1, int s2, int e2, boolean inv) { + this.gidx1 = gidx1; this.gidx2 = gidx2; + this.s1 = s1; this.e1 = e1; + this.s2 = s2; this.e2 = e2; + this.inverted = inv; + } + } + /************************************************************ + * Two-color all blocks + */ + public static Color blockP; + public static Color blockN; + static { + PropertiesReader props = new PropertiesReader(Globals.class.getResource(""/properties/circle.properties"")); + blockP = props.getColor(""blockP""); + blockN = props.getColor(""blockN""); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/circview/CircFrame.java",".java","14004","337","package circview; + +import javax.swing.JFrame; +import javax.swing.WindowConstants; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Collections; +import java.util.Random; +import java.util.TreeSet; +import java.util.Vector; + +import database.DBconn2; +import symap.Globals; +import symap.frame.HelpBar; +import util.ErrorReport; + +/********************************************************* + * Draw circle view. + * Draws on screen size 825x900; set in ManagerFrame and ChrExpFrame after creation + */ +public class CircFrame extends JFrame { + private static final long serialVersionUID = 2371747762964367253L; + + private CircPanel circPanel; + private HelpBar helpPanel; + private boolean bIsWG = false, bHasSelf = false; + private ControlPanelCirc controls; + private DBconn2 tdbc2; + + /** Called by Manager Frame; 2-WG **/ + public CircFrame(String title, DBconn2 dbc2, int projXIdx, int projYIdx, boolean hasSelf) { + super(title); + int[] pidxList = {projXIdx, projYIdx}; + bHasSelf = hasSelf; + bIsWG=true; + tdbc2 = new DBconn2(""CircleG-"" + DBconn2.getNumConn(), dbc2); + build(pidxList, pidxList[0], null, null, null); + } + /** Called by ChrExpFrame; N-chromosomes **/ + public CircFrame(DBconn2 dbc2, int[] projIdxList, TreeSet selGrps, HelpBar hb, + int ref, boolean hasSelf, double [] lastParams) { + super(""SyMAP Circle "" + Globals.VERSION); + bHasSelf = hasSelf; + bIsWG=false; + this.tdbc2 = dbc2; // created in ChrExpFrame + build(projIdxList, ref, hb, selGrps, lastParams); + } + private void build(int[] projIdxList, int ref, HelpBar hb, TreeSet selGrps, double [] lastParams){ + if (projIdxList.length == 0) { + System.out.println(""Circle view called with no projects!""); + return; + } + try { + if (bIsWG) helpPanel = new HelpBar(-1, 17); + else helpPanel = hb; + // WG From CE + boolean isSelf = (projIdxList.length==2 && projIdxList[1]==0) || projIdxList.length==1; + + circPanel = new CircPanel(this, tdbc2, helpPanel, projIdxList, ref, selGrps, lastParams); + + controls = new ControlPanelCirc(circPanel, helpPanel, bIsWG, isSelf, bHasSelf); + if (lastParams!=null) controls.setLastParams((int)lastParams[0], + lastParams[1]==1, lastParams[2]==1, lastParams[3]==1); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) { + clear(); + } + }); + + // Dimensions are set in calling program; i.e. ManagerFrame and ChrExpFrame + setLayout( new BorderLayout() ); + add( controls, BorderLayout.NORTH ); + add( circPanel.getScrollPane(),BorderLayout.CENTER ); + if (bIsWG) add( helpPanel, BorderLayout.SOUTH ); + + Dimension dim = getToolkit().getScreenSize(); + setLocation(dim.width / 4,dim.height / 4); + } + catch(Exception e){ ErrorReport.print(e, ""Creating circle panel"");} + } + + public void clear() { + tdbc2.close(); + circPanel.clear(); + } + public double [] getLastParams() { return circPanel.getLastParams();} // use last settings; called from frame.ChrExpFrame + + /************************************************************** + * XXX Color control + */ + private double scale = 1.0; + private Vector mColors = new Vector (); + + protected Vector getColorVec(int set, boolean bScale, double scale, + boolean bOrder, boolean bRevOrder, boolean bShuffle, int seed) { + this.scale = (bScale) ? scale : 1.0; // used in rgbToInt + + if (set==1) createSet1Colors(); + else createSet2Colors(); + + if (bShuffle) Collections.shuffle(mColors, new Random(seed)); + if (bOrder || bRevOrder) Collections.sort(mColors); + if (bRevOrder) Collections.reverse(mColors); + + return mColors; + } + private int fromHexToInt(String hexCode) { + String hex = (hexCode.startsWith(""#"")) ? hexCode.substring(1) : hexCode; + int r = Integer.valueOf(hex.substring(0, 2), 16); + int g = Integer.valueOf(hex.substring(2, 4), 16); + int b = Integer.valueOf(hex.substring(4, 6), 16); + return rgbToInt(r,g,b); + } + private int rgbToInt(int R, int G, int B) { + if (scale!=1.0) { + R = (int) ((double)R * scale); + G = (int) ((double)G * scale); + B = (int) ((double)B * scale); + } + return (R<<16) + (G<<8) + B; + } + private void createSet1Colors() { + mColors.clear(); + + mColors.add(rgbToInt(255,0,0)); // 1 red + mColors.add(rgbToInt(0,0,255)); // 2 blue + mColors.add(rgbToInt(20,200,70)); // 3 sea green + mColors.add(rgbToInt(138,0,188)); // 4 purple + mColors.add(rgbToInt(255,165,0)); // 5 orange + mColors.add(rgbToInt(255,181,197)); // 6 light pink + mColors.add(rgbToInt(210, 180, 140)); // 7 beige + mColors.add(rgbToInt(64,224,208)); // 8 torquise + mColors.add(rgbToInt(165,42,42)); // 9 dark red + mColors.add(rgbToInt(0,255,255)); // 10 dark brown + mColors.add(rgbToInt(230,230,250)); // 11 pea green-yellowish + mColors.add(rgbToInt(255,255,0)); // 12 almost same as 3 + mColors.add(rgbToInt(85,107, 47)); // 13 blue, slightly lighter than 2 + mColors.add(rgbToInt(70,130,180)); // 14 forest green + mColors.add(rgbToInt(127,125,21)); // 15 green, slightly lighter than 14 + mColors.add(rgbToInt(207,137,97)); // 16 cornflower blue, close to 13 + mColors.add(rgbToInt(144,67,233)); + mColors.add(rgbToInt(199,189,70)); + mColors.add(rgbToInt(82,203,128)); + mColors.add(rgbToInt(120,202,102)); + mColors.add(rgbToInt(194,102,115)); + mColors.add(rgbToInt(20,17,118)); + mColors.add(rgbToInt(145,21,129)); + mColors.add(rgbToInt(109,62,232)); + mColors.add(rgbToInt(108,86,28)); + mColors.add(rgbToInt(185,206,7)); + mColors.add(rgbToInt(50,200,133)); + mColors.add(rgbToInt(46,102,237)); + mColors.add(rgbToInt(27,149,81)); + mColors.add(rgbToInt(114,155,241)); + mColors.add(rgbToInt(33,240,129)); + mColors.add(rgbToInt(117,170,160)); + mColors.add(rgbToInt(93,14,79)); + mColors.add(rgbToInt(129,210,166)); + mColors.add(rgbToInt(124,191,79)); + mColors.add(rgbToInt(188,55,188)); + mColors.add(rgbToInt(117,219,105)); + mColors.add(rgbToInt(11,142,235)); + mColors.add(rgbToInt(144,97,194)); + mColors.add(rgbToInt(215,77,161)); + mColors.add(rgbToInt(192,148,92)); + mColors.add(rgbToInt(197,86,215)); + mColors.add(rgbToInt(103,159,140)); + mColors.add(rgbToInt(42,80,186)); + mColors.add(rgbToInt(136,44,28)); + mColors.add(rgbToInt(59,207,239)); + mColors.add(rgbToInt(115,62,251)); + mColors.add(rgbToInt(136,179,26)); + mColors.add(rgbToInt(48,29,82)); + mColors.add(rgbToInt(31,187,116)); + mColors.add(rgbToInt(98,129,244)); + mColors.add(rgbToInt(214,198,72)); + mColors.add(rgbToInt(30,104,54)); + mColors.add(rgbToInt(11,240,45)); + mColors.add(rgbToInt(182,73,232)); + mColors.add(rgbToInt(181,116,173)); + mColors.add(rgbToInt(154,54,156)); + mColors.add(rgbToInt(157,62,134)); + mColors.add(rgbToInt(95,155,130)); + mColors.add(rgbToInt(1,49,242)); + mColors.add(rgbToInt(207,10,187)); + mColors.add(rgbToInt(62,82,11)); + mColors.add(rgbToInt(118,19,178)); + mColors.add(rgbToInt(168,242,211)); + mColors.add(rgbToInt(173,147,121)); + mColors.add(rgbToInt(67,38,212)); + mColors.add(rgbToInt(27,229,235)); + mColors.add(rgbToInt(9,82,242)); + mColors.add(rgbToInt(57,155,84)); + mColors.add(rgbToInt(114,18,40)); + mColors.add(rgbToInt(132,11,12)); + mColors.add(rgbToInt(33,22,144)); + mColors.add(rgbToInt(41,3,241)); + mColors.add(rgbToInt(164,18,247)); + mColors.add(rgbToInt(48,16,230)); + mColors.add(rgbToInt(220,101,8)); + mColors.add(rgbToInt(190,216,38)); + mColors.add(rgbToInt(135,190,4)); + mColors.add(rgbToInt(174,225,161)); + mColors.add(rgbToInt(60,218,203)); + mColors.add(rgbToInt(93,171,163)); + mColors.add(rgbToInt(106,58,113)); + mColors.add(rgbToInt(155,100,221)); + mColors.add(rgbToInt(92,208,48)); + mColors.add(rgbToInt(79,252,70)); + mColors.add(rgbToInt(47,6,104)); + mColors.add(rgbToInt(141,198,123)); + mColors.add(rgbToInt(195,19,156)); + mColors.add(rgbToInt(214,18,222)); + mColors.add(rgbToInt(28,110,137)); + mColors.add(rgbToInt(137,51,155)); + mColors.add(rgbToInt(167,54,22)); + mColors.add(rgbToInt(69,157,85)); + mColors.add(rgbToInt(146,24,202)); + mColors.add(rgbToInt(58,64,207)); + mColors.add(rgbToInt(216,108,174)); + mColors.add(rgbToInt(78,58,136)); + mColors.add(rgbToInt(146,82,91)); + mColors.add(rgbToInt(40,76,111)); + mColors.add(rgbToInt(80,34,231)); + mColors.add(rgbToInt(193,81,118)); + } + // from https://mokole.com/palette.html; some were too close visually so I changed + private void createSet2Colors() { + mColors.clear(); + mColors.add(fromHexToInt(""#4c1130""));//dark maroon + mColors.add(fromHexToInt(""#8b4513""));//saddlebrown + mColors.add(fromHexToInt(""#c15176""));//darkpink + mColors.add(fromHexToInt(""#2e8b57""));//seagreen + mColors.add(fromHexToInt(""#191970""));//midnightblue + mColors.add(fromHexToInt(""#800000""));//maroon + mColors.add(fromHexToInt(""#483d8b""));//darkslateblue + mColors.add(fromHexToInt(""#006400""));//darkgreen + mColors.add(fromHexToInt(""#708090""));//slategray + mColors.add(fromHexToInt(""#b22222""));//firebrick + mColors.add(fromHexToInt(""#5f9ea0""));//cadetblue + mColors.add(fromHexToInt(""#008000""));//green + mColors.add(fromHexToInt(""#3cb371"")); //mediumseagreen + mColors.add(fromHexToInt(""#bc8f8f""));//rosybrown + mColors.add(fromHexToInt(""#663399""));//rebeccapurple + mColors.add(fromHexToInt(""#b8860b""));//darkgoldenrod + mColors.add(fromHexToInt(""#d8bfd8""));//thistle + mColors.add(fromHexToInt(""#bdb76b""));//darkkhaki + mColors.add(fromHexToInt(""#008b8b""));//darkcyan + mColors.add(fromHexToInt(""#cd853f""));//peru + mColors.add(fromHexToInt(""#4682b4""));//steelblue + mColors.add(fromHexToInt(""#d2691e""));//chocolate + mColors.add(fromHexToInt(""#9acd32""));//yellowgreen + mColors.add(fromHexToInt(""#20b2aa""));//lightseagreen + mColors.add(fromHexToInt(""#cd5c5c""));//indianred + mColors.add(fromHexToInt(""#00008b""));//darkblue + mColors.add(fromHexToInt(""#980000""));// maroony orangered + mColors.add(fromHexToInt(""#4b0082""));//indigo + mColors.add(fromHexToInt(""#32cd32""));//limegreen + mColors.add(fromHexToInt(""#a0522d""));//sienna + mColors.add(fromHexToInt(""#daa520""));//goldenrod + mColors.add(fromHexToInt(""#7f007f""));//purple2 + mColors.add(fromHexToInt(""#8fbc8f""));//darkseagreen + mColors.add(fromHexToInt(""#b03060""));//maroon3 + mColors.add(fromHexToInt(""#66cdaa""));//mediumaquamarine + mColors.add(fromHexToInt(""#9932cc""));//darkorchid + mColors.add(fromHexToInt(""#ff0000""));//red + + mColors.add(fromHexToInt(""#00ced1""));//darkturquoise + mColors.add(fromHexToInt(""#808000""));//olive + mColors.add(fromHexToInt(""#f1c232""));// + mColors.add(fromHexToInt(""#ffd700""));//gold + mColors.add(fromHexToInt(""#6a5acd""));//slateblue + mColors.add(fromHexToInt(""#ffff00""));//yellow + mColors.add(fromHexToInt(""#c71585""));//mediumvioletred + mColors.add(fromHexToInt(""#0000cd""));//mediumblue + mColors.add(fromHexToInt(""#deb887""));//burlywood + mColors.add(fromHexToInt(""#40e0d0""));//turquoise + mColors.add(fromHexToInt(""#00ff00""));//lime + mColors.add(fromHexToInt(""#9400d3""));//darkviolet + mColors.add(fromHexToInt(""#ba55d3""));//mediumorchid + mColors.add(fromHexToInt(""#00fa9a""));//mediumspringgreen + mColors.add(fromHexToInt(""#8a2be2""));//blueviolet + mColors.add(fromHexToInt(""#00ff7f""));//springgreen + mColors.add(fromHexToInt(""#4169e1""));//royalblue + mColors.add(fromHexToInt(""#e9967a""));//darksalmon + mColors.add(fromHexToInt(""#dc143c""));//crimson + mColors.add(fromHexToInt(""#00ffff""));//aqua + mColors.add(fromHexToInt(""#00bfff""));//deepskyblue + mColors.add(fromHexToInt(""#f4a460""));//sandybrown + mColors.add(fromHexToInt(""#556b2f""));//darkolivegreen + mColors.add(fromHexToInt(""#9370db""));//mediumpurple + mColors.add(fromHexToInt(""#0000ff""));//blue + mColors.add(fromHexToInt(""#a020f0""));//purple3 + mColors.add(fromHexToInt(""#a64d79""));// + mColors.add(fromHexToInt(""#adff2f""));//greenyellow + mColors.add(fromHexToInt(""#ff6347""));//tomato + mColors.add(fromHexToInt(""#da70d6""));//orchid + mColors.add(fromHexToInt(""#a9a9a9""));//darkgray + mColors.add(fromHexToInt(""#ff00ff""));//fuchsia + mColors.add(fromHexToInt(""#2f4f4f""));//darkslategray + mColors.add(fromHexToInt(""#b0c4de""));//lightsteelblue + mColors.add(fromHexToInt(""#ff7f50""));//coral + mColors.add(fromHexToInt(""#1e90ff""));//dodgerblue + mColors.add(fromHexToInt(""#db7093""));//palevioletred + mColors.add(fromHexToInt(""#f0e68c""));//khaki + mColors.add(fromHexToInt(""#fa8072""));//salmon + mColors.add(fromHexToInt(""#eee8aa""));//palegoldenrod + mColors.add(fromHexToInt(""#134f5c"")); + mColors.add(fromHexToInt(""#6495ed""));//cornflower + mColors.add(fromHexToInt(""#dda0dd""));//plum + mColors.add(fromHexToInt(""#add8e6""));//lightblue + mColors.add(fromHexToInt(""#87ceeb""));//skyblue + mColors.add(fromHexToInt(""#ff1493""));//deeppink + mColors.add(fromHexToInt(""#6b8e23""));//olivedrab + mColors.add(fromHexToInt(""#7b68ee""));//mediumslateblue + mColors.add(fromHexToInt(""#ffa07a""));//lighsalmon + mColors.add(fromHexToInt(""#afeeee""));//paleturquoise + mColors.add(fromHexToInt(""#ee82ee""));//violet + mColors.add(fromHexToInt(""#98fb98""));//palegreen + mColors.add(fromHexToInt(""#560000""));// + mColors.add(fromHexToInt(""#7fffd4""));//aquamarine + mColors.add(fromHexToInt(""#ffdead""));//navajowhite + mColors.add(fromHexToInt(""#808080""));//gray + mColors.add(fromHexToInt(""#dd7e6b""));// + mColors.add(fromHexToInt(""#ff69b4""));//hotpink + mColors.add(fromHexToInt(""#a52a2a""));//brown + mColors.add(fromHexToInt(""#ffb6c1""));//lightpink + mColors.add(fromHexToInt(""#696969""));//dimgray + mColors.add(fromHexToInt(""#7fff00""));//chartreuse + mColors.add(fromHexToInt(""#c0c0c0""));//silver + mColors.add(fromHexToInt(""#ffa500""));//orange + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/ErrorCount.java",".java","211","20","package util; + +public class ErrorCount +{ + static int count = 0; + + public static void init() + { + count = 0; + } + public static void inc() + { + count++; + } + public static int getCount() + { + return count; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/FileDir.java",".java","4350","157","package util; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class FileDir { + /******************************************************************** + * XXX File ops + */ + + // Return the Files; if fromHome==true, relative to home directroy + public static File getFile(String name, boolean fromHome) { + if (name == null) return new File(""""); + if (fromHome) { + String dir = null; + try { + dir = System.getProperty(""user.home""); + } + catch (Exception e) {ErrorReport.print(e, ""Get file from users's directory"");} + return new File(dir,name); + } + return new File(name); + } + public static void deleteFile ( String strPath ){ + File theFile = new File ( strPath ); + theFile.delete(); + } + + public static void clearAllDir(File d){ // does not remove top directory d + if (d.isDirectory()){ + for (File f : d.listFiles()){ + if (f.isDirectory() && !f.getName().equals(""."") && !f.getName().equals("".."")) { + clearAllDir(f); + } + f.delete(); + } + } + } + public static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] subdir = dir.list(); + + if (subdir != null) { + for (int i = 0; i < subdir.length; i++) { + boolean success = deleteDir(new File(dir, subdir[i])); + if (!success) { + System.err.println(""Error deleting "" + dir.getAbsolutePath()); + return false; + } + } + } + } + System.gc(); // closes any file streams that were left open to ensure delete() succeeds + return dir.delete(); + } + public static boolean fileExists(String filepath) { + if (filepath == null) return false; + File f = new File(filepath); + return f.exists() && f.isFile(); + } + public static boolean dirExists(String filepath){ + if (filepath == null) return false; + File f = new File(filepath); + return f.exists() && f.isDirectory(); + } + public static boolean pathExists(String path) { + if (path == null) return false; + File f = new File(path); + return f.exists(); + } + public static int dirNumFiles(File d){ + int numFiles = 0; + for (File f : d.listFiles()){ + if (f.isFile() && !f.isHidden()) numFiles++; + } + return numFiles; + } + + public static File checkCreateDir(String dir, boolean bPrt) { + try { + File f = new File(dir); + if (f.exists() && f.isFile()) { + Popup.showErrorMessage(""Please remove file "" + f.getName() + + "" as SyMAP needs to create a directory at this path""); + return null; + } + if (!f.exists()) { + f.mkdir(); + if (bPrt) System.out.println(""Create directory "" + dir); + } + return f; + } + catch (Exception e) { + ErrorReport.print(e, ""Create dir "" + dir); + return null; + } + } + public static void checkCreateFile(String path, String trace){ + File f = new File(path); + if (f.exists()) { + f.delete(); + } + try { + f.createNewFile(); + } + catch (Exception e) { + ErrorReport.print(e, ""Create file "" + path); + } + } + + public static File checkCreateFile(File path, String name, String trace){ + File f = new File(path, name); + if (f.exists()) { + f.delete(); + } + try { + f.createNewFile(); + return f; + } + catch (Exception e) { + ErrorReport.print(e, ""Create file "" + path.getName() + "" "" + name); + return null; + } + } + + public static String fileOnly(String path) { + return path.substring(path.lastIndexOf(""/"")+1, path.length()); + } + + public static String fileDate(String path) { + try { + File f = new File(path); + if (f.exists()) { + long lastModified = f.lastModified(); + Date date = new Date(lastModified); + SimpleDateFormat formatter = new SimpleDateFormat(""dd-MMM-yyyy HH:mm""); + String formattedDate = formatter.format(date); + return formattedDate; + } + } + catch (Exception e) {ErrorReport.print(e, ""get file date "" + path); } + return """"; + } + // return path/file (not path//file or pathfile path/file/) + public static String fileNormalizePath(String path, String file) { + String p = path, f = file; + + if (path.endsWith(""/"") && file.startsWith(""/"")) p = p.substring(0, p.length()-1); + else if (!path.endsWith(""/"") && !file.startsWith(""/"")) f = ""/"" + f; + + if (file.endsWith(""/"")) f = f.substring(0, f.length()-1); + + return p + f; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/ImageViewer.java",".java","2910","88","package util; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.filechooser.FileNameExtensionFilter; + +import symap.Globals; + +/************************************************* + * Write image - used from the Printer Icon + * it was using org.freehep for images, which did not work past Java v8. + * Even though it does not use org.freehep explicitly, it still needs + * org.freehep.graphicsio.raw.RawImageWriterSpi + */ + +public class ImageViewer extends JDialog { + private static final long serialVersionUID = 1L; + private static String [] typeExt = {""jpeg"", ""png"", ""gif"", ""bmp""}; + private static String typeStr = "".png .gif .jpeg .bmp""; + + public static void showImage(String name, JPanel comp) { + String f = getFile(name + "".png""); + if (f==null) return; + + String type=null; + for (String t : typeExt) { + if (f.endsWith(t)) { + type=t; + break; + } + } + if (type==null) { + util.Popup.showWarningMessage(""Illegal File: "" + f + ""\nMust end in: "" + typeStr); + return; + } + saveImage(comp, type, f); + } + + private static String getFile(String fname) { + try { + String saveDir = Globals.getExport(); + + JFileChooser fc = new JFileChooser(saveDir); + FileNameExtensionFilter filter = new FileNameExtensionFilter(typeStr, typeExt); + fc.setFileFilter(filter); + fc.setSelectedFile(new File(fname)); + + int rc = fc.showSaveDialog(null); + if (rc!= JFileChooser.APPROVE_OPTION) return null; + + File f = fc.getSelectedFile(); + if (f.exists()) { + if (JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(null,""The file exists, do you want to overwrite it?"", + ""File exists"",JOptionPane.YES_NO_OPTION)) return null; + f.delete(); + } + return f.getAbsolutePath(); + } + catch(Exception e){ErrorReport.print(e,""Failed getting file""); return null;} + } + + static private void saveImage(JPanel dPanel, String type, String path) { + BufferedImage bImg = new BufferedImage(dPanel.getWidth(), dPanel.getHeight(), BufferedImage.TYPE_INT_RGB); + Graphics2D cg = bImg.createGraphics(); + dPanel.paintAll(cg); + try { + if (ImageIO.write(bImg, type, new File(path))) + System.out.println(""Saved "" + type + "" image to "" + path); + else System.out.println(""Failure: Could not write to "" + path); + } catch (IOException e) { ErrorReport.print(e, ""Write image to "" + path);} + } + + // Called to create the image (works for print, Home, etc) + public static ImageIcon getImageIcon(String strImagePath) { + java.net.URL imgURL = ImageViewer.class.getResource(strImagePath); + if (imgURL != null) return new ImageIcon(imgURL); + else return null; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/ErrorReport.java",".java","3094","108","package util; + +/******************************************** + * See util.ProgressDialog for write to logs/LOAD.log and progress window + * See backend.Log for write to alignment specific symap.log file + */ +import java.io.IOException; +import java.io.PrintWriter; +import java.io.FileWriter; +import java.text.SimpleDateFormat; +import java.util.Date; + +import database.DBconn2; +import symap.Globals; + +public class ErrorReport { + static final String strFileName = ""error.log""; + + public static void print(Throwable e, String debugInfo) { + reportError(e, ""Error: "" + debugInfo, false); + } + public static void print(String debugInfo) { + reportError(null, ""Error: "" + debugInfo, false); + } + + public static void print(String msg, String debugInfo) { + msg = ""Error: "" + msg; + + System.err.println(msg); + try { + PrintWriter pWriter = new PrintWriter(new FileWriter(strFileName, true)); + pWriter.println(""\n"" + getDate()); + pWriter.println(msg); + pWriter.println(debugInfo); + pWriter.close(); + System.err.println(""See "" + strFileName); + + } catch (IOException e1) { + System.err.println(""DebugInfo: "" + debugInfo); + System.err.println(""An error has occurred, however SyMAP was unable to create an error log file""); + return; + } + } + + public static void die(Throwable e, String debugInfo) { + DBconn2.shutConns(); + reportError(e, ""Fatal Error "" + Globals.VERDATE + ""\n "" + debugInfo, false); + System.exit(-1); + } + public static void die(String debugInfo) { + DBconn2.shutConns(); + reportError(null, ""Fatal Error "" + Globals.VERDATE + ""\n "" + debugInfo, false); + System.exit(-1); + } + public static void reportError(Throwable e, String msg, boolean replaceContents) { + System.err.println(msg); + if (e!=null && e.getMessage()!=null) { + String [] lines = e.getMessage().split(""\n""); + if (lines.length>5) { + System.err.println(lines[0]); + for (String l : lines) { + if (l.startsWith(""MESSAGE"")) { + System.err.println(l); + break; + } + } + } + else { + System.err.println(e.getMessage()); + } + } + + PrintWriter pWriter = null; + try { + if(replaceContents) { + pWriter = new PrintWriter(new FileWriter(strFileName)); + } + else { + pWriter = new PrintWriter(new FileWriter(strFileName, true)); + } + } catch (IOException e1) { + System.err.println(""An error has occurred, however SyMAP was unable to create an error log file""); + return; + } + + pWriter.println(""\n "" + Globals.VERDATE + "" run on "" + getDate()); + pWriter.println(msg + ""\n""); + if (e != null) { + e.printStackTrace(pWriter); + System.err.println(""See "" + strFileName); + } + pWriter.close(); + } + + static public String getDate ( ) + { + Date date=new Date(); + SimpleDateFormat sdf=new SimpleDateFormat(""dd-MMM-yy HH:mm:ss""); + return sdf.format(date); + } + static public void prtMem() { + long free = Runtime.getRuntime().freeMemory(); + long total = Runtime.getRuntime().totalMemory(); + long max = Runtime.getRuntime().maxMemory(); + System.out.format(""Memory: free %,d total %,d max %,d\n"", free, total, max); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/Jcomp.java",".java","17412","502","package util; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GraphicsConfiguration; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextArea; +import javax.swing.JTextField; + +import symap.frame.HelpBar; +import symap.frame.HelpListener; + +/*************************************************** + * Common sets of interface commands + * 1 Page and Row + * 2 Label + * 3 Button + * 4 CheckBox and Radio + * 5 TextField and TextArea + * 6 ComboBox + * 7 Width + * 8 Screen + */ +public class Jcomp { + public static final String ok = ""OK"", close = ""Close"", cancel=""Cancel""; // for buttons + + // XXX Page and Row + static public JPanel createPagePanel() { + JPanel page = new JPanel(); + page.setLayout(new BoxLayout(page, BoxLayout.PAGE_AXIS)); // Y_AXIS + page.setBackground(Color.white); + page.setAlignmentX(Component.LEFT_ALIGNMENT); + page.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0)); + + return page; + } + static public JPanel createPagePanelNB() { // The border adds extra space, so do not want it in Query forms + JPanel page = new JPanel(); + page.setLayout(new BoxLayout(page, BoxLayout.PAGE_AXIS)); // Y_AXIS + page.setBackground(Color.white); + page.setAlignmentX(Component.LEFT_ALIGNMENT); + return page; + } + static public JPanel createRowPanel() { + JPanel row = new JPanel(); + row.setLayout(new BoxLayout(row, BoxLayout.LINE_AXIS)); // X_AXIS + row.setBackground(Color.white); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + + return row; + } + + static public JPanel createRowPanelGray() { + JPanel row = new JPanel(); + row.setLayout(new BoxLayout(row, BoxLayout.LINE_AXIS)); // X_AXIS + row.setAlignmentX(Component.LEFT_ALIGNMENT); + + return row; + } + static public JPanel createPlainPanel() { // this leaves more room above/below than Line_axis + JPanel row = new JPanel(); + row.setBackground(Color.white); + return row; + } + // Manager Frame to layout a row + static public Component createHorizPanel( Component[] comps, int gapWidth, int extra ) { + JPanel panel = new JPanel(); + panel.setLayout( new BoxLayout ( panel, BoxLayout.X_AXIS ) ); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + + for (Component c : comps) { + if (c != null) { + panel.add( c ); + if (gapWidth > 0)panel.add( Box.createHorizontalStrut(gapWidth) ); + } + else if (extra > 0)panel.add( Box.createHorizontalStrut(extra) ); + } + panel.add( Box.createHorizontalGlue() ); + + return panel; + } + /* This centers the row: buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT); or + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(sPane,BorderLayout.CENTER); + getContentPane().add(buttonPanel,BorderLayout.SOUTH); + pack(); + */ + + // XXX Label + public static JLabel createLabel(String text, int fontStyle, int fontSize) { + JLabel label = new JLabel(text); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setFont( new Font(label.getFont().getName(), fontStyle, fontSize) ); + return label; + } + static public JLabel createLabel(String label) { + JLabel tmp = new JLabel(label); + tmp.setBackground(Color.white); + tmp.setOpaque(true); // allows the color to be changed on Mac + tmp.setEnabled(true); + return tmp; + } + static public JLabel createLabel(String label, String tip) { + JLabel tmp = new JLabel(label); + tmp.setToolTipText(tip); + tmp.setBackground(Color.white); + tmp.setOpaque(true); // allows the color to be changed on Mac + tmp.setEnabled(true); + return tmp; + } + static public JLabel createLabelGray(String label, String tip) { + JLabel tmp = new JLabel(label); + tmp.setToolTipText(tip); + tmp.setEnabled(true); + return tmp; + } + static public JLabel createLabel(String label, String tip, boolean enable) { + JLabel tmp = new JLabel(label); + tmp.setToolTipText(tip); + tmp.setBackground(Color.white); + tmp.setOpaque(true); // allows the color to be changed on Mac + tmp.setEnabled(enable); + return tmp; + } + static public JLabel createVentanaLabel(String label, int sz) { + JLabel lab = new JLabel(label); + lab.setFont(new Font(""Verdana"",0,sz)); + lab.setBackground(Color.white); + return lab; + } + static public JLabel createMonoLabel(String label, int sz) { + JLabel lab = new JLabel(label); + lab.setFont(new Font(Font.MONOSPACED,Font.PLAIN, sz)); + lab.setBackground(Color.white); + return lab; + } + static public JLabel createMonoLabelGray(String label, String t) { + JLabel lab = new JLabel(label); + lab.setFont(new Font(Font.MONOSPACED,Font.PLAIN,13)); //lab.getFont().getName() + lab.setToolTipText(t); + return lab; + } + static public JLabel createHtmlLabel(String text) { + String html = """" + text + """"; + JLabel l = new JLabel(html); + return l; + } + static public JLabel createHtmlLabel(String text, String t) { + String html = """" + text + """"; + JLabel l = new JLabel(html); + l.setToolTipText(t); + return l; + } + static public JLabel createBoldLabel(String label, int sz) {// for Instructions + JLabel lab = new JLabel(label); + lab.setFont(new Font(Font.MONOSPACED,Font.BOLD, sz)); + lab.setBackground(Color.white); + return lab; + } + static public JLabel createItalicsLabel(String label, int sz) {// for Instructions + JLabel lab = new JLabel(label); + lab.setFont(new Font(Font.MONOSPACED,Font.ITALIC, sz)); + lab.setBackground(Color.white); + return lab; + } + static public JLabel createItalicsBoldLabel(String label, int sz) {// for Instructions + JLabel lab = new JLabel(label); + lab.setFont(new Font(Font.MONOSPACED,Font.ITALIC | Font.BOLD, sz)); + lab.setBackground(Color.white); + return lab; + } + // XXX Button + public static JButton createIconButton(HelpListener parent, HelpBar bar, ActionListener l, String path, String tip) { + Icon icon = ImageViewer.getImageIcon(path); + JButton button = new JButton(icon); + button.setMargin(new Insets(0,0,0,0)); + + if (l != null) button.addActionListener(l); + + button.setToolTipText(tip); + button.setName(tip); + if (bar != null) bar.addHelpListener(button,parent); + + return button; + } + public static JButton createBorderIconButton(String path, String tip) { + Icon icon = ImageViewer.getImageIcon(path); + JButton button = new JButton(icon); + button.setMargin(new Insets(0,0,0,0)); + + button.setToolTipText(tip); + button.setName(tip); + + return button; + } + public static JButton createIconButton(String path, String tip) { + Icon icon = ImageViewer.getImageIcon(path); + JButton button = new JButton(icon); + button.setBorder(null); // necessary or it gets a border + + button.setToolTipText(tip); + button.setName(tip); + + return button; + } + // if (isSelected) scaleToggle.setBackground(Color.white); else scaleToggle.setBackground(Color.gray); + public static JButton createBorderIconButton(HelpListener parent, HelpBar bar, ActionListener l, String path, String tip) { + Icon icon = ImageViewer.getImageIcon(path); // new ImageIcon(path); works in zTest but not here + JButton button = new JButton(icon); + button.setBorder(BorderFactory.createRaisedBevelBorder()); + + if (l != null) button.addActionListener(l); + + button.setToolTipText(tip); + button.setName(tip); + if (bar != null) bar.addHelpListener(button,parent); + + return button; + } + // This is to be used as toggle with getBorderColor! Has border and smaller + public static JButton createBorderButton(HelpListener parent, HelpBar bar, ActionListener l, String label, String tip) { + JButton button = new JButton(label); + button.setBackground(Color.white); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + button.setFont(new Font(button.getFont().getName(),Font.PLAIN,11)); + button.setBorder(BorderFactory.createRaisedBevelBorder()); + + button.setMinimumSize(button.getPreferredSize()); + button.setMaximumSize(button.getPreferredSize()); + + if (l != null) button.addActionListener(l); + + button.setToolTipText(tip); + button.setName(tip); + if (bar != null) bar.addHelpListener(button,parent); + + return button; + } + public static Color getBorderColor(boolean isSelect) { + if (isSelect) return Color.gray; + else return Color.white; + } + public static JButton createButtonGray(HelpListener parent, HelpBar bar, ActionListener l, String label, String tip) { + JButton button = new JButton(label); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + + button.setMinimumSize(button.getPreferredSize()); + button.setMaximumSize(button.getPreferredSize()); + + if (l != null) button.addActionListener(l); + + button.setToolTipText(tip); + button.setName(tip); + if (bar != null) bar.addHelpListener(button,parent); + + return button; + } + + static public JButton createButtonGray(String s, String t) { + JButton jbutton = new JButton(s); + jbutton.setMargin(new Insets(1,3,1,3)); + jbutton.setToolTipText(t); + return jbutton; + } + static public JButton createButton(String s, String t) { + JButton jbutton = new JButton(s); + jbutton.setBackground(Color.white); + jbutton.setMargin(new Insets(1,3,1,3)); + jbutton.setToolTipText(t); + return jbutton; + } + static public JButton createButton(String s, boolean b) { + JButton jbutton = new JButton(s); + jbutton.setBackground(Color.white); + jbutton.setMargin(new Insets(1,3,1,3)); + jbutton.setEnabled(b); + return jbutton; + } + static public JButton createPlainButton(String label, String tip) { + JButton button = new JButton(label); + button.setBackground(Color.white); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + button.setMargin(new Insets(0, 0, 0, 0)); + button.setFont(new Font(button.getFont().getName(),Font.PLAIN,10)); + button.setToolTipText(tip); + return button; + } + static public JButton createBoldButton(String label, String tip) { // for xToSymap + JButton button = new JButton(label); + button.setToolTipText(tip); + button.setBackground(Color.white); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + button.setMargin(new Insets(0, 0, 0, 0)); + button.setFont(new Font(button.getFont().getName(),Font.BOLD,12)); + return button; + } + static public JButton createMonoButton(String s, String t) {// for 2D filters + JButton jbutton = new JButton(s); + jbutton.setFont(new Font(Font.MONOSPACED,Font.PLAIN,13)); + jbutton.setMargin(new Insets(1,3,1,3)); + jbutton.setToolTipText(t); + jbutton.setBackground(Color.white); + return jbutton; + } + static public JButton createMonoButtonSmGray(String s, String t) { + JButton jbutton = new JButton(s); + jbutton.setFont(new Font(Font.MONOSPACED,Font.PLAIN,11)); + jbutton.setMargin(new Insets(0,0,0,0)); + jbutton.setToolTipText(t); + return jbutton; + } + // XXX CheckBox and Radio + public static JCheckBox createCheckBox(HelpListener parent, HelpBar bar, ActionListener l, String label, String tip) { + JCheckBox box = new JCheckBox(label); + box.setBackground(Color.white); + box.setMinimumSize(box.getPreferredSize()); + box.setMaximumSize(box.getPreferredSize()); + + if (l != null) box.addActionListener(l); + + box.setToolTipText(tip); + box.setName(tip); + if (bar != null) bar.addHelpListener(box,parent); + + return box; + } + static public JCheckBox createCheckBox(String label, String tip, boolean def) { + JCheckBox box = new JCheckBox(label, def); + box.setToolTipText(tip); + box.setBackground(Color.white); + box.setMinimumSize(box.getPreferredSize()); + box.setMaximumSize(box.getPreferredSize()); + return box; + } + static public JCheckBox createCheckBox(String label, boolean def) { + JCheckBox box = new JCheckBox(label, def); + box.setBackground(Color.white); + box.setMinimumSize(box.getPreferredSize()); + box.setMaximumSize(box.getPreferredSize()); + return box; + } + static public JCheckBox createCheckBoxGray(String label, String tip) { + JCheckBox box = new JCheckBox(label); + box.setToolTipText(tip); + box.setMinimumSize(box.getPreferredSize()); + box.setMaximumSize(box.getPreferredSize()); + return box; + } + static public JRadioButton createRadio(HelpListener parent, HelpBar bar, ActionListener l, String label, String tip) { + JRadioButton button = new JRadioButton(label); button.setBackground(Color.white); + button.setMargin(new Insets(0,0,0,0)); + + if (l != null) button.addActionListener(l); + + button.setToolTipText(tip); + button.setName(tip); + if (bar != null) bar.addHelpListener(button,parent); + + return button; + } + public static JRadioButton createRadio(String label, String tip) { + JRadioButton button = new JRadioButton(label); button.setBackground(Color.white); + button.setToolTipText(tip); + button.setMargin(new Insets(0,0,0,0)); + button.setMinimumSize(button.getPreferredSize()); + button.setMaximumSize(button.getPreferredSize()); + return button; + } + public static JRadioButton createRadioGray(String label, String tip) { // filters use gray background + JRadioButton button = new JRadioButton(label); + button.setToolTipText(tip); + button.setMargin(new Insets(0,0,0,0)); + button.setMinimumSize(button.getPreferredSize()); + button.setMaximumSize(button.getPreferredSize()); + return button; + } + + // XXX TextField and TextArea + public static JTextField createTextField(String defVal, int size) { + JTextField txt = new JTextField(defVal, size); + txt.setBackground(Color.white); + txt.setMinimumSize(txt.getPreferredSize()); + txt.setMaximumSize(txt.getPreferredSize()); + return txt; + } + public static JTextField createTextField(String defVal, String tip, int size) { + JTextField txt = new JTextField(defVal, size); + txt.setToolTipText(tip); + txt.setBackground(Color.white); + txt.setMinimumSize(txt.getPreferredSize()); + txt.setMaximumSize(txt.getPreferredSize()); + return txt; + } + public static JTextField createTextField(String defVal, String tip, int size, boolean def) { + JTextField txt = new JTextField(defVal, size); + txt.setToolTipText(tip); + txt.setEnabled(def); + txt.setBackground(Color.white); + txt.setMinimumSize(txt.getPreferredSize()); + txt.setMaximumSize(txt.getPreferredSize()); + return txt; + } + public static JTextArea createTextArea(String text, Color bg, boolean bWrap) { + JTextArea textArea = new JTextArea(text); + + textArea.setAlignmentX(Component.LEFT_ALIGNMENT); + if (bg==null) textArea.setBackground(Color.white); // for query instructions + else textArea.setBackground(bg); + textArea.setEditable(false); + textArea.setLineWrap(bWrap); + textArea.setWrapStyleWord(true); + + return textArea; + } + // XXX ComboBox + public static JComboBox createComboBox(String [] options, String tip, int def) { + JComboBox comboBox = new JComboBox (options); + comboBox.setToolTipText(tip); + comboBox.setSelectedIndex(def); + comboBox.setBackground(Color.WHITE); + comboBox.setMinimumSize(comboBox.getPreferredSize()); + comboBox.setMaximumSize(comboBox.getPreferredSize()); + return comboBox; + } + // XXX Width + public static boolean isWidth(int width, JLabel lab) { + return (width > lab.getPreferredSize().width); + } + public static int getWidth(int width, JLabel lab) {// use with Box.createHorizontalStrut for spacing + if (isWidth(width, lab)) return width - lab.getPreferredSize().width; + return 0; + } + public static boolean isWidth(int width, JComponent lab) { + return (width > lab.getPreferredSize().width); + } + public static int getWidth(int width, JComponent lab) {// use with Box.createHorizontalStrut for spacing + return width - lab.getPreferredSize().width; + } + // XXX Screen + // attempts to find the screen bounds from the screen insets. + public static Rectangle getScreenBounds(Window window) { + GraphicsConfiguration config = window.getGraphicsConfiguration(); + Rectangle b = config.getBounds(); + Insets inset = Toolkit.getDefaultToolkit().getScreenInsets(config); + if (inset.left != 0 || inset.right != 0 || inset.top != 0 || inset.bottom != 0) + b.setBounds(b.x+inset.left,b.y+inset.top,b.width-inset.left-inset.right,b.height-inset.top-inset.bottom); + + return b; + } + // sets the window to the full size of the available screen or it's preferred + // size, whichever is smaller, using the other methods in this class. + public static void setFullSize(Window window, Container view, int max) { + window.pack(); + + Dimension pref = window.getPreferredSize(); + Rectangle b = getScreenBounds(window); + + pref.width = Math.min(pref.width,b.width); + pref.width = Math.min(pref.width, max); + pref.height = Math.min(pref.height,b.height); + + setWinSize(window,b,pref,view); + } + private static void setWinSize(Window window, Rectangle screenBounds, Dimension pref, Container view) { + Point loc = window.getLocation(); + if (pref.width+loc.x > screenBounds.width) loc.x = screenBounds.x; + if (pref.height+loc.y > screenBounds.height) loc.y = screenBounds.y; + + window.setLocation(loc); + window.setSize(pref); + + if (view != null) view.invalidate(); + window.validate(); + } + public static void setCursorBusy(Component c, boolean busy) { + if (busy) c.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ); + else c.setCursor( Cursor.getDefaultCursor() ); + } + +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/Popup.java",".java","6837","191","package util; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import javax.swing.BorderFactory; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.WindowConstants; + +import symap.sequence.Annotation; + +public class Popup { + /************************************************************** + * XXX Popups + */ + // isModal=true means that everything is frozen until the window is closed + // these allow formatted messages, but only have OK at the bottom of window + public static void showMonoWarning(Component parent, String message) { + displayInfoMonoSpace(parent, ""Warning"", message, true); + } + public static void showMonoError(Component parent, String message) { + displayInfoMonoSpace(parent, ""Error"", message, true); + } + public static void showMonoError(Component parent, String title, String message) { + displayInfoMonoSpace(parent, title, message, true); + } + public static void displayInfoMonoSpace(Component parentFrame, String title, + String theMessage, boolean isModal) { + JOptionPane pane = new JOptionPane(); + + JTextArea messageArea = new JTextArea(theMessage); + + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.BOLD, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + pane.setMessage(sPane); + pane.setMessageType(JOptionPane.PLAIN_MESSAGE); + + JDialog helpDiag = pane.createDialog(parentFrame, title); + helpDiag.setModal(isModal); + helpDiag.setResizable(true); + + helpDiag.setVisible(true); + } + // not used + public static JOptionPane displayInfoMonoSpace(Component parentFrame, String title, + String theMessage, Dimension d, Annotation aObj) + { + // scrollable selectable message area + JTextArea messageArea = new JTextArea(theMessage); + JScrollPane sPane = new JScrollPane(messageArea); + messageArea.setFont(new Font(""monospaced"", Font.BOLD, 12)); + messageArea.setEditable(false); + messageArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + // put scrollable pane in option pane + JOptionPane optionPane = new JOptionPane(sPane, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); + + // add dialog, which has title + JDialog helpDiag = optionPane.createDialog(parentFrame, title); + helpDiag.setModal(false); // true - freeze other windows + helpDiag.setResizable(true); + if (helpDiag.getWidth() >= d.width || helpDiag.getHeight() >= d.height) helpDiag.setSize(d); + helpDiag.setVisible(true); + helpDiag.setAlwaysOnTop(true); + + helpDiag.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + helpDiag.addWindowListener(new WindowAdapter() { + public void windowClosed(WindowEvent e) { + aObj.setIsPopup(false); + } + }); + + optionPane.addPropertyChangeListener( + new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent e) { + aObj.setIsPopup(false); + } + } + ); + + return optionPane; + } + + public static void showInfoMsg(String title, String msg) { + JOptionPane.showMessageDialog(null, msg, title, JOptionPane.WARNING_MESSAGE); + } + public static void showWarning(String msg) { + JOptionPane.showMessageDialog(null, msg, ""Warning"", JOptionPane.WARNING_MESSAGE); + } + + public static void showInfoMessage(String title, String msg) { + System.out.println(msg); + JOptionPane.showMessageDialog(null, msg, title, JOptionPane.WARNING_MESSAGE); + } + + public static void showWarningMessage(String msg) { + System.out.println(msg); + JOptionPane.showMessageDialog(null, msg, ""Warning"", JOptionPane.WARNING_MESSAGE); + } + + public static void showErrorMsg(String msg) { + JOptionPane.showMessageDialog(null, msg, ""Error"", JOptionPane.ERROR_MESSAGE); + } + + public static void showErrorMessage(String msg) { + System.err.println(msg); + JOptionPane.showMessageDialog(null, msg, ""Error"", JOptionPane.ERROR_MESSAGE); + } + + public static void showErrorMessage(String msg, int exitStatus) { + showErrorMessage(msg); + System.out.println(""Exiting SyMAP""); + System.exit(exitStatus); + } + static public boolean showYesNo (String title, String msg) { + String [] options = {""No"", ""Yes""}; + int ret = JOptionPane.showOptionDialog(null, + msg, + title, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + if (ret == 0) return false; + return true; + } + static public boolean showContinue (String title, String msg) { + String [] options = {""Cancel"", ""Continue""}; + int ret = JOptionPane.showOptionDialog(null, + msg + ""\nContinue?"", + title, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + if (ret == 0) return false; + return true; + } + + // Cancel is false + public static boolean showConfirm2(String title, String msg) { + String [] options = {""Cancel"", ""Confirm""}; + int ret = JOptionPane.showOptionDialog(null, + msg, + title, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + if (ret == 0) return false; + else return true; + } + + // three possible actions; used to (1) remove from database (2) and disk + public static int showConfirm3(String title, String msg) { + String [] options = {""Cancel"", ""Only"", ""All""}; + return JOptionPane.showOptionDialog(null, + msg, title, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[1]); + } + public static int showConfirmFile(String filename) { + String [] options = {""Cancel"", ""Overwrite"", ""Append""}; + String title = ""File exists""; + String msg = ""File '"" + filename + ""' exists.\nDo you want to overwrite it or append to it?""; + return JOptionPane.showOptionDialog(null, + msg, title, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, null, options, options[2]); + } + public static void showOutOfMemoryMessage(Component parent) { + System.err.println(""Not enough memory.""); + JOptionPane optionPane = new JOptionPane(""Not enough memory - increase 'mem' in symap script."", JOptionPane.ERROR_MESSAGE); + + LinkLabel label = new LinkLabel(""Click to open the Troubleshooting Guide."", Jhtml.TROUBLE_GUIDE_URL); + label.setAlignmentX(Component.CENTER_ALIGNMENT); + optionPane.add(new JLabel("" ""), 1); + optionPane.add(label, 2); + optionPane.add(new JLabel("" ""), 3); + + JDialog dialog = optionPane.createDialog(parent, ""Error""); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setVisible(true); + optionPane.getValue(); // Wait on user input + } + + public static void showOutOfMemoryMessage() { showOutOfMemoryMessage(null); } + +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/Jhtml.java",".java","11020","321","package util; + +import java.awt.Color; +import java.awt.Container; +import java.awt.Desktop; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JScrollPane; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; + +/********************************************************* + */ +public class Jhtml { + public static final String BASE_HELP_URL_prev51 = ""http://www.agcol.arizona.edu/software/symap/doc/""; // not used + public static final String BASE_HELP_URL = ""https://csoderlund.github.io/SyMAP/""; + public static final String TROUBLE_GUIDE_URL = BASE_HELP_URL + ""TroubleShoot.html""; + public static final String macVerify = ""#macos""; + + public static final String SYS_GUIDE_URL = BASE_HELP_URL + ""SystemGuide.html""; + public static final String create = ""#create""; + public static final String ext = ""#ext""; + + public static final String SYS_HELP_URL = BASE_HELP_URL + ""SystemHelp.html""; + public static final String build = ""#build""; + public static final String param1 = ""#projParams""; + public static final String param2Align = ""#align2""; + public static final String param2Clust = ""#clust""; + public static final String param2Syn = ""#syn""; + + public static final String USER_GUIDE_URL = BASE_HELP_URL + ""UserGuide.html""; + public static final String view = ""#views""; + public static final String circle = ""#circle""; + public static final String dotplot = ""#dotplot_display""; + public static final String align2d = ""#alignment_display_2d""; + public static final String colorIcon = ""#wheel""; + public static final String control = ""#control""; + public static final String hitfilter = ""#hitfilter""; + public static final String seqfilter = ""#sequence_filter""; + public static final String dotfilter = ""#dotplot_filter""; + + public static final String QUERY_GUIDE_URL = BASE_HELP_URL + ""Query.html""; + public static final String query = ""#query""; + public static final String result = ""#result""; + + public static final String CONVERT_GUIDE_URL = BASE_HELP_URL + ""input/index.html""; + + public static JButton createHelpIconSysSm(String main, String id) { + return createHelpIcon(""/images/helpSm.png"", main + id); + } + + public static JButton createHelpIconUserLg(String id) { + return createHelpIcon(""/images/help.gif"", USER_GUIDE_URL + id); + } + public static JButton createHelpIconUserSm(String id) { + return createHelpIcon(""/images/helpSm.png"", USER_GUIDE_URL + id); + } + public static JButton createHelpIconQuery(String id) { + return createHelpIcon(""/images/helpSm.png"", QUERY_GUIDE_URL + id); + } + private static JButton createHelpIcon(String img, String url) { + Icon icon = ImageViewer.getImageIcon(img); + JButton button = new JButton(icon); + + button.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (!tryOpenURL(url) ) + System.err.println(""Error opening URL: "" + url); + } + }); + button.setToolTipText(""Help: Online documentation.""); + return button; + } + public static void onlineHelp(String id) { // Used from 2D control drop-down + String url = USER_GUIDE_URL + id; + if (!tryOpenURL(url) ) + System.err.println(""Error opening URL: "" + url); + } + + public static boolean tryOpenURL (String theLink ) { + if (theLink == null) return false; + + try { + new URI(theLink); + } + catch (URISyntaxException e) { + ErrorReport.print(e, ""URI Syntax: "" + theLink); + return false; + } + if (isMac()) return tryOpenMac(theLink); + else return tryOpenLinux(theLink); + } + + private static boolean tryOpenMac(String theLink) { + Desktop desktop = java.awt.Desktop.getDesktop(); + URI oURL; + try { + oURL = new URI(theLink); + } + catch (URISyntaxException e) { + ErrorReport.print(e, ""URI Syntax: "" + theLink); + return false; + } + try { + desktop.browse(oURL); + return true; + } catch (IOException e) { + ErrorReport.print(e, ""URL desktop error on Mac: "" + theLink); + } + return false; + } + + public static boolean tryOpenLinux (String theLink) { + // Copied this from: http://www.centerkey.com/java/browser/ + try { + if (isWindows()) { + String [] x = {""rundll32 url.dll,FileProtocolHandler"", theLink}; + Runtime.getRuntime().exec(x); // no idea if this works on Windows + return true; + } + else { + String [] browsers = {""firefox"", ""opera"", ""konqueror"", ""epiphany"", ""mozilla"", ""netscape"", + ""google-chrome"", ""conkeror"", ""midori"", ""kazehakase"", ""x-www-browser""}; + String browser = null; + for (int count = 0; count < browsers.length && browser == null; count++) + if (Runtime.getRuntime().exec( new String[] {""which"", browsers[count]}).waitFor() == 0) + browser = browsers[count]; + if (browser == null) + return false; + else { + Runtime.getRuntime().exec(new String[] {browser, theLink}); + return true; + } + } + } + catch (Exception e) {ErrorReport.print(e, ""URL error on Linux: "" + theLink);} + return false; + } + /******************************************************************** + * 1. The following provides popups for java/src/html + * 2. The Try methods provide direct links to http URLs + * 3. The ProjectManagerFrameCommon.createInstructionsPanel shows the main page + */ + /** Instance stuff - only class methods **/ + private static Class resClass = null; // store this so help pages can be loaded from anywhere + private static Frame helpParentFrame = null; + + public static void setResClass(Class c) + { + resClass = c; + } + public static void setHelpParentFrame(Frame f) + { + helpParentFrame = f; + } + public static void showHTMLPage(JDialog parent, String title, String resource) { + if (resClass == null) { + System.err.println(""Help can't be shown.\nDid you call setResClass?""); + return; + } + JDialog dlgRoot = (parent == null ? new JDialog(helpParentFrame,title,false) + : new JDialog(parent,title,false)); + dlgRoot.setPreferredSize(new Dimension(800,800)); + Container dlg = dlgRoot.getContentPane(); + dlg.setLayout(new BoxLayout(dlg,BoxLayout.Y_AXIS)); + + StringBuffer sb = new StringBuffer(); + try { + InputStream str = resClass.getResourceAsStream(resource); + + int ci = str.read(); + while (ci != -1) { + sb.append((char)ci); + ci = str.read(); + } + } + catch(Exception e){ErrorReport.print(e, ""Show HTML page"");} + + String html = sb.toString(); + + JEditorPane jep = new JEditorPane(); + jep.setContentType(""text/html""); + jep.setEditable(false); + + jep.addHyperlinkListener(new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if (!tryOpenURL(e.getURL().toString()) ) + System.err.println(""Error opening URL: "" + e.getURL().toString()); + } + } + }); + jep.setText(html); + jep.setVisible(true); + jep.setCaretPosition(0); + JScrollPane jsp = new JScrollPane(jep); + dlg.add(jsp); + + dlgRoot.pack(); + dlgRoot.setVisible(true); + dlgRoot.toFront(); + dlgRoot.requestFocus(); + } + + public static boolean isLinux() { + return System.getProperty(""os.name"").toLowerCase().contains(""linux""); + } + + public static boolean isWindows() { + return System.getProperty(""os.name"").toLowerCase().contains(""windows""); + } + + public static boolean isMac() { + return System.getProperty(""os.name"").toLowerCase().contains(""mac""); + } + + public static boolean is64Bit() { + return System.getProperty(""os.arch"").toLowerCase().contains(""64""); + } + // ManagerFrame initial view + public static JComponent createInstructionsPanel(InputStream str, Color background) { + StringBuffer sb = new StringBuffer(); + try { + //InputStream str = this.getClass().getResourceAsStream(HTML); + + int ci = str.read(); + while (ci != -1) { + sb.append((char)ci); + ci = str.read(); + } + } + catch(Exception e){ErrorReport.print(e, ""Show instructions"");} + + JEditorPane editorPane = new JEditorPane(); + editorPane.setEditable(false); + editorPane.setBackground(background); + editorPane.setContentType(""text/html""); + editorPane.setText(sb.toString()); + + JScrollPane scrollPane = new JScrollPane(editorPane); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); + scrollPane.setBackground(background); + + editorPane.addHyperlinkListener(new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if ( !Jhtml.tryOpenURL(e.getURL().toString()) ) + System.err.println(""Error opening URL: "" + e.getURL().toString()); + } + } + }); + + return scrollPane; + } + // TableReport; for Query report + public static void showHtmlPanel(JDialog parent, String title, String html) { + JDialog dlgRoot = new JDialog(parent,title,false); // works if sent null, and does not bounce other frames around + dlgRoot.setPreferredSize(new Dimension(800,800)); + Container dlg = dlgRoot.getContentPane(); + dlg.setLayout(new BoxLayout(dlg,BoxLayout.Y_AXIS)); + + JEditorPane jep = new JEditorPane(); + jep.setContentType(""text/html""); + jep.setEditable(false); + + jep.addHyperlinkListener(new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if (!tryOpenURL(e.getURL().toString()) ) + System.err.println(""Error opening URL: "" + e.getURL().toString()); + } + } + }); + jep.setText(html); + jep.setVisible(true); + jep.setCaretPosition(0); + JScrollPane jsp = new JScrollPane(jep); + dlg.add(jsp); + + dlgRoot.pack(); + dlgRoot.setVisible(true); + } + // for TableReport + public static String wrapLine(String line, int lineLength, String lineBreak) { + if (line.length() == 0) return """"; + if (line.length() <= lineLength) return line; + + String[] words = line.split("" ""); + StringBuilder allLines = new StringBuilder(); + StringBuilder trimmedLine = new StringBuilder(); + + for (String word : words) { + if (trimmedLine.length()+1+word.length() <= lineLength) { + trimmedLine.append(word).append("" ""); + } else { + if (trimmedLine.length()>0) allLines.append(trimmedLine).append(lineBreak); + trimmedLine = new StringBuilder(); + if (word.length()>lineLength) word = word.substring(0, lineLength-2) + ""...""; + trimmedLine.append(word).append("" ""); + } + } + if (trimmedLine.length() > 0) allLines.append(trimmedLine); + return allLines.toString().trim(); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/ProgressDialog.java",".java","8058","294","package util; + +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Font; +import java.awt.Insets; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseAdapter; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JLabel; +import javax.swing.JTextArea; +import javax.swing.JScrollPane; +import javax.swing.JDialog; +import javax.swing.JButton; +import javax.swing.text.DefaultCaret; + +import symap.Globals; + +import java.io.FileWriter; + +/*************************************************************** + * Used by ManagerFrame for popup dialog tracking progress + */ +public class ProgressDialog extends JDialog { + private static final long serialVersionUID = 1L; + + private static final int MIN_DISPLAY_TIME = 1500; // milliseconds + + private JProgressBar progressBar; + private JTextArea textArea; + private JPanel panel; + private JButton button; + private long startTime; + private Thread userThread = null; + private boolean bCancelled = false, bCloseWhenDone = false, bCloseIfNoErrors = false, bDone = false; + private FileWriter logFileW = null; + + public ProgressDialog(final Frame owner, String strTitle, String strMessage, + boolean hasCancel, + FileWriter logW) // LOAD.log or symap.log (2nd also written to by backend.Log) + { + super(owner, strTitle, true); + Cancelled.init(); + logFileW = logW; + boolean isDeterminate=false; + + msgToFileOnly(""-----------------------------------------------------------------""); + String x = "" Running Java v"" + System.getProperty(""java.version"") + "" on "" + ErrorReport.getDate(); + msgToFileOnly("">>> SyMAP "" + Globals.VERDATE + x + "" <<<""); + + // Label + JLabel label = new JLabel(strMessage); + label.setAlignmentX(Component.CENTER_ALIGNMENT); + label.setFont( new Font(label.getFont().getName(), Font.PLAIN, 12) ); + + // Progress Bar + progressBar = new JProgressBar(); + progressBar.setIndeterminate(!isDeterminate); + if (isDeterminate) { + progressBar.setMinimum(0); + progressBar.setMaximum(100); + progressBar.setValue(0); + } + progressBar.setStringPainted(true); + progressBar.setString(""""); // set height + + textArea = new JTextArea(15, 80); + textArea.setMargin(new Insets(5,5,5,5)); + textArea.setEditable(false); + textArea.setFont(new Font(""monospaced"", Font.PLAIN, 10)); + //textArea.setWrapStyleWord(true); + textArea.setLineWrap(true); + ((DefaultCaret)textArea.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); // enable auto-scroll + + button = new JButton(""Cancel""); + button.setAlignmentX(Component.CENTER_ALIGNMENT); + button.addActionListener( handleButton ); + + // Add everything to top-level panel + panel = new JPanel(); + panel.setLayout( new BoxLayout ( panel, BoxLayout.Y_AXIS ) ); + panel.setBorder( BorderFactory.createEmptyBorder(15, 10, 10, 10) ); + panel.setAlignmentX(Component.CENTER_ALIGNMENT); + panel.add( label ); + panel.add( Box.createVerticalStrut(5) ); + panel.add( progressBar ); + panel.add( Box.createVerticalStrut(1) ); + + panel.add( new JScrollPane(textArea, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) ); + + if (hasCancel) { + panel.add( Box.createVerticalStrut(10) ); + panel.add( button ); + } + panel.add( Box.createVerticalStrut(5) ); + + // Setup dialog + setContentPane(panel); + pack(); + setLocationRelativeTo(owner); + setCursor( new Cursor(Cursor.WAIT_CURSOR) ); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent we) { + if (!bDone) cancel(); + } + }); + + addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() >= 2 + && (!getLocation().equals(owner.getLocation()) + || !getSize().equals(owner.getSize()))) + { + setLocation(owner.getLocation()); + setSize(owner.getSize()); + } + } + }); + + startTime = System.currentTimeMillis(); // must be here and not in start() for some reason + } + public void start(Thread thread) { + this.userThread = thread; + + thread.start(); + + setVisible(true); // blocking + } + + public void start() { + setVisible(true); // blocking + } + public void closeIfNoErrors(){ + ErrorCount.init(); + bCloseIfNoErrors = true; + } + + public void closeWhenDone(){ + bCloseWhenDone = true; + } + + public void finish(boolean success) { + if (bCloseWhenDone) { + finishAndClose(success); + return; + } + if (bCloseIfNoErrors) { + setCursor( Cursor.getDefaultCursor() ); + progressBar.setIndeterminate(false); + + if (ErrorCount.getCount() > 0) { + progressBar.setString(""Completed, click 'Done' to continue ...""); + msg(""Some errors occurred, check text in this window, terminal or view logs/[dbName]_load.log.""); + button.setText(""Done (Error Occurred)""); + } + else { + finishAndClose(success); + return; + } + } + else { + long runTime = System.currentTimeMillis() - startTime; + if (runTime < MIN_DISPLAY_TIME) // ensure dialog is visible + try { Thread.sleep(MIN_DISPLAY_TIME - runTime); } + catch (Exception e) { } + setCursor( Cursor.getDefaultCursor() ); + if (button != null ) { + progressBar.setIndeterminate(false); + if (success) { + bDone = true; + progressBar.setString(""Completed, click 'Done' to continue ...""); + button.setText(""Done""); // Wait for user to close + } + else { + progressBar.setString(""Error occurred, click 'Cancel' to abort ...""); + } + } + else { + dispose(); + } + } + } + public void finishAndClose(boolean success) { + long runTime = System.currentTimeMillis() - startTime; + if (runTime < MIN_DISPLAY_TIME) // ensure dialog is visible + try { Thread.sleep(MIN_DISPLAY_TIME - runTime); } + catch (Exception e) { } + + try { + setCursor( Cursor.getDefaultCursor() ); + dispose(); // Close this dialog + } + catch (Exception e) {} + + if (logFileW != null) + try { + logFileW.close(); + logFileW=null;} + catch (Exception e) {} + } + public void setCancelled() { + try { + if (logFileW!=null) logFileW.append(""Cancel""); + bCancelled = true; + } + catch (Exception e) {} + } + private void cancel() { + bCancelled = true; + Cancelled.cancel(); + if (userThread != null) + userThread.interrupt(); + while (userThread != null && userThread.isAlive()) { + try{Thread.sleep(100);} catch(Exception e){} + } + } + public boolean wasCancelled() { return bCancelled; } + + public void addActionListener(ActionListener listener) { + button.removeActionListener( handleButton ); + button.addActionListener( listener ); + } + + private ActionListener handleButton = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (button.getText().equals(""Cancel"")) + cancel(); + ProgressDialog.this.setVisible(false);//ProgressDialog.this.dispose(); + } + }; + /************************************************************/ + + public synchronized void updateText(String search, String newText) { + if (textArea==null) return; + String text = textArea.getText(); + + int pos = text.lastIndexOf(search); + if (pos < 0) + textArea.append(search + newText); + else { + text = text.substring(0, pos) + search + newText; + textArea.setText(text); + } + } + + public void msg(String msg) { + appendText(msg); + } + + public synchronized void appendText(String s) { + if (!s.endsWith(""\n"")) s += ""\n""; + + msgToFile(s); + + if (textArea!=null) textArea.append(s); + } + + public void msgOnly(String s) { + if (!s.endsWith(""\n"")) s += ""\n""; + if (textArea!=null) textArea.append(s); + } + + public void msgToFile(String s) { + if (!s.endsWith(""\n"")) s += ""\n""; + System.out.print(s); + + msgToFileOnly(s); + } + + public void msgToFileOnly(String s) { + if (!s.endsWith(""\n"")) s += ""\n""; + if (logFileW != null) { + try { + logFileW.write(s); + logFileW.flush(); + } + catch (Exception e) {} + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/Utilities.java",".java","12557","424","package util; + +import java.util.Date; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.text.SimpleDateFormat; + +import symap.Globals; + +/** + * Time + * basic array and string ops + * text + */ +public class Utilities { + public static void sleep(int milliseconds) { + try{ Thread.sleep(milliseconds); } + catch (InterruptedException e) { } + } + /********************************************************** + * XXX Time methods + */ + static public String getNormalizedDate(String nDate) {// date from NOW() 'year-mo-dy time' + String time=""""; + if (Globals.TRACE || Globals.INFO) { + String [] tok1 = nDate.split("" ""); + if (tok1.length==2) { + if (tok1[1].contains("":"")) time = tok1[1].substring(0, tok1[1].lastIndexOf("":"")); + } + } + String d = nDate.substring(0, nDate.indexOf("" "")); + String [] tok = d.split(""-""); + if (tok.length!=3) return nDate; + + int m = getInt(tok[1]); + String ms=""Jan""; + if (m==2) ms=""Feb""; + else if (m==3) ms=""Mar""; + else if (m==4) ms=""Apr""; + else if (m==5) ms=""May""; + else if (m==6) ms=""Jun""; + else if (m==7) ms=""Jul""; + else if (m==8) ms=""Aug""; + else if (m==9) ms=""Sep""; + else if (m==10) ms=""Oct""; + else if (m==11) ms=""Nov""; + else if (m==12) ms=""Dec""; + + return tok[2] + ""-"" + ms + ""-"" + tok[0] + "" "" + time; + } + + public static String reformatAnnotDate(String adate) { // For Project - show on left of manager (see DB project.annotdate) + try { + String dt; + if (adate.indexOf("" "")>0) dt = adate.substring(0, adate.indexOf("" "")); + else if (adate.startsWith(""20"")) dt = adate; + else return ""???""; + + SimpleDateFormat sdf=new SimpleDateFormat(""yyyy-MM-dd""); + Date d = sdf.parse(dt); + sdf = new SimpleDateFormat(""ddMMMyy""); + return sdf.format(d); + } + catch (Exception e) {return ""???"";} + } + static public String getDateTime ( ){ + Date date=new Date(); + SimpleDateFormat sdf=new SimpleDateFormat(""dd-MMM-yy HH:mm""); + return sdf.format(date); + } + static public String getDateOnly ( ) { + Date date=new Date(); + SimpleDateFormat sdf=new SimpleDateFormat(""dd-MMM-yy""); + return sdf.format(date); + } + // System.currentTimeMillis() + public static String getDurationString(long duration) { // milliseconds + duration /= 1000; + long min = duration / 60; + long sec = duration % 60; + long hr = min / 60; + min = min % 60; + long day = hr / 24; + hr = hr % 24; + + return (day > 0 ? day+""d:"" : """") + (hr > 0 ? hr+""h:"" : """") + (min > 0 ? min+""m:"" : """") + sec + ""s""; + } + static public long getNanoTime () { + return System.nanoTime(); + } + static public String getNanoTimeStr(long startTime) { + long et = System.nanoTime()-startTime; + long sec = et /1000000000; + return timerStr2(sec); + } + static public void printElapsedNanoTime(String msg, long startTime) { + long et = System.nanoTime()-startTime; + long sec = et /1000000000; + String t = timerStr2(sec); + System.out.format(""%-20s %s\n"", msg, t); + } + + static public String timerStr2(long et) { + long day = et/86400; //24*3600 + long time = et%86400; + long hr = time/3600; + + time %= 3600; + long min = time/60; + long sec = time%60; + + String str = "" ""; + if (day > 0) str += day + ""d:""; + if (hr > 0 ) str += hr + ""h:""; + str += min + ""m:"" + sec + ""s""; + return str; + } + + + /******************************************************************* + * XXX basic array and string ops + */ + public static String pad(String s, int width){ + width -= s.length(); + while (width-- > 0) s += "" ""; + return s; + } + public static String getCommaSepString(int[] ints) { + if (ints == null || ints.length == 0) return """"; + StringBuffer ret = new StringBuffer().append(ints[0]); + for (int i = 1; i < ints.length; i++) ret.append("","").append(ints[i]); + return ret.toString(); + } + public static double getDouble(String i) { + try { + double x = Double.parseDouble(i); + return x; + } + catch (Exception e) {return -1.0;} + } + public static int getInt(String i) { + try { + int x = Integer.parseInt(i); + return x; + } + catch (Exception e) {return -1;} + } + + public static boolean isEmpty(String s) { + return (s == null || s.length() == 0); + } + public static boolean isOverlap(int start1, int end1, int start2, int end2) { + if ((start1 >= start2 && start1 <= end2) || (end1 >= start2 && end1 <= end2) + || (start2 >= start1 && start2 <= end1) || (end2 >= start1 && end2 <= end1)) return true; + + return false; + } + + /***************************************************************************** + * XXX Format + */ + // HitData; + public static String coordsStr(boolean isStrandPos, int start, int end) { + String o = (isStrandPos) ? ""+"" : ""-""; + return String.format(""%s(%,d - %,d) %,dbp"", o, start, end, (end-start+1)) ; + } + + // for writing to log + static public String kMText(long len) { + double d = (double) len; + String x = len+""""; + if (len>=1000000000) { + d = d/1000000000.0; + x = String.format(""%.2fB"", d); + } + else if (len>=1000000) { + d = d/1000000.0; + x = String.format(""%.2fM"", d); + } + else if (len>=1000) { + d = d/1000.0; + x = String.format(""%.1fk"", d); + } + return x; + } + static public String kMText(int len) {// for xToSymap summary; + double d = (double) len; + String x = len+""""; + if (len>=1000000000) { + d = d/1000000000.0; + x = String.format(""%dB"", (int) d); + } + else if (len>=1000000) { + d = d/1000000.0; + x = String.format(""%dM"", (int) d); + } + else if (len>=1000) { + d = d/1000.0; + x = String.format(""%dk"", (int) d); + } + return x; // <1000 + } + static public String kText(int len) { + if (len>=10000) { + double d = Math.round(((double) len)/1000.0); + return String.format(""%dk"", (int) d); + } + else { + return String.format(""%,4d"", len); // <10000 + } + } + + /***************************************************** + * XXX Tag; The following are to parse the gene tag (I made a mess of this) + * v544 DB: 992.a (1 746) + * v542 DB: Gene #992a (9 1,306bp) + * Exon tag created in Annotation class + */ + public static String convertTag(String tag) { + if (!tag.startsWith(""Gene"")) return tag; + + String dbtag = tag.replace(""bp"",""""); + Pattern pat1 = Pattern.compile(""Gene #(\\d+)([a-z]+[0-9]*)(.*)$""); + Matcher m = pat1.matcher(dbtag); // pre-CAS543 Gene #2 (9 1,306bp) or Gene #2b (9 1,306bp) + if (m.matches()) { + String d = m.group(1); + String s = m.group(2); + String p = m.group(3); + return d + ""."" + s + "" "" + p; + } + Pattern pat2 = Pattern.compile(""Gene #(\\d+)(.*)$""); + m = pat2.matcher(dbtag); + if (m.matches()) { + String d = m.group(1); + String p = m.group(2); + return d + ""."" + "" "" + p; + } + return dbtag; + } + // Annotation class; create fullTag for hover + static public String createFullTagFromDBtag(String tag) { + String [] tok = tag.split(""\\(""); + + if (tok.length!=2) { // this should not happen but maybe very old db + if (tag.startsWith(""Gene"")) return tag; + else return Globals.geneTag + tag; + } + + tok[1] = ""(#Exon="" + tok[1]; + if (!tag.startsWith(""Gene"")) { + tok[0] = Globals.geneTag + tok[0]; + tok[1] = tok[1].replace("")"",""bp)""); + } + return tok[0] + "" "" + tok[1]; + } + // Annotation.popupDesc; e.g 1563.w (15 2164) + // return tok[0]=Gene #1563.w and tok[1]=#Exons=15 2,164bp + static public String [] getGeneExonFromTag(String tag) { + String [] ret = new String [2]; + String [] tok = tag.split(""\\(""); + + if (tok.length!=2) { + System.out.println(""SyMAP Error parsing tag: "" + tag); + ret[0] = Globals.geneTag + tag; + ret[1] = Globals.exonTag + "" 0 0""; + return ret; + } + + ret[0] = tok[0]; + tok[1] = tok[1].replace("")"",""""); + ret[1] = exonNum() + tok[1].replace("")"",""""); + + if (!tag.startsWith(""Gene"")) { // v543 992.a (1 746) old version started with Gene + ret[0] = Globals.geneTag + tok[0].trim(); + ret[1] = ret[1] + ""bp""; + } + return ret; + } + // exonTag = ""Exon #""; returns #Exons= + public static String exonNum() { + return ""#"" + Globals.exonTag.substring(0, Globals.exonTag.indexOf("" "")) + ""s=""; + } + // Created in backend.AnchorsPost.Gene; return ""d.[a]"" + static public String getGenenumFromDBtag(String tag) { + if (!tag.startsWith(""Gene"")) { // CAS544 '2 (9 1306)' or '2.b (9 1306)' + String [] tok = tag.split("" \\(""); + if (tok.length==2) return tok[0].trim(); + else return tag; // shouldn't happen + } + + Pattern pat1 = Pattern.compile(""Gene #(\\d+)([a-z]+[0-9]*)(.*)$""); + Matcher m = pat1.matcher(tag); // pre-CAS544 Gene #2 (9 1,306bp) or Gene #2b (9 1,306bp) + if (m.matches()) { + String y = m.group(1); + String z = m.group(2); + return y + ""."" + z; + } + + Pattern pat2 = Pattern.compile(""Gene #(\\d+)(.*)$""); + m = pat2.matcher(tag); + if (m.matches()) { + String y = m.group(1); + return y + "".""; + } + else return tag; + } + // symapQuery.DBdata.passFilters; return number only + static public String getGenenumIntOnly(String tag) { + if (tag==""-"") return """"; + + String gn = tag.contains(""("") ? getGenenumFromDBtag(tag) : tag; // the () has already been removed + + String [] tok = gn.split(""\\.""); + if (tok.length>0) return tok[0]; + else return gn; + } + // symap.QueryPanel + public static boolean isValidGenenum(String gn) { + String n=gn, s=null; + if (gn.contains(""."")) { + String [] tok = gn.split(""\\.""); + if (tok.length==0 || tok.length>2) return false; + n = tok[0]; + if (tok.length==2) s=tok[1]; + } + try { + Integer.parseInt(n); + } + catch (Exception e) { return false;} + if (s!=null) { + try { + Integer.parseInt(s); + return false; + } + catch (Exception e) { return true;} + } + return true; + } + // remove leading zeros before making full block name + static public String blockStr(String c1, String c2, int block) { + String x1 = (c1.startsWith(""0"") && c1.length()>1) ? c1.substring(1) : c1; + String x2 = (c2.startsWith(""0"") && c2.length()>1) ? c2.substring(1) : c2; + return x1 + ""."" + x2 + ""."" + block; + } + /******************************************************* + * XXX Table maker copied from TCW + */ + public static String makeTable( + int nCol, int nRow, String[] fields, int [] justify, String [][] rows) + { + Vector lines = new Vector (); + makeTable(lines, nCol, nRow, fields, justify, rows); + String x=""""; + for (String l : lines) x += l + ""\n""; + return x; + } + public static void makeTable( + Vector lines, int nCol, int nRow, String[] fields, int [] justify, String [][] rows) + { + int c, r; + String line; + String space = "" ""; + + // compute column lengths + int []collen = new int [nCol]; + for (c=0; c < nCol; c++) collen[c] = 0; + + for (c=0; c< nCol; c++) { // longest value + for (r=0; r collen[c]) + collen[c] = rows[r][c].length(); + } + } + if (fields != null) { // heading longer than any value? + for (c=0; c < nCol; c++) { + if (collen[c] > 0) { + if (fields[c] == null) fields[c] = """"; + if (fields[c].length() > collen[c]) + collen[c]=fields[c].length(); + } + } + // output headings + line = space; // length of space in front + for (c=0; c< nCol; c++) + if (collen[c] > 0) + line += pad(fields[c],collen[c], 1) + space; + lines.add(line); + } + // output rows + for (r=0; r 0) + line += pad(rows[r][c],collen[c],justify[c]) + space; + rows[r][c] = """"; // so wouldn't reuse in next table + } + lines.add(line); + } + } + + private static String pad(String s, int width, int o){ + if (s == null) return "" ""; + if (s.length() > width) { + String t = s.substring(0, width-1); + System.out.println(""'"" + s + ""' truncated to '"" + t + ""'""); + s = t; + s += "" ""; + } + else if (o == 0) { // left + String t=""""; + width -= s.length(); + while (width-- > 0) t += "" ""; + s = t + s; + } + else { + width -= s.length(); + while (width-- > 0) s += "" ""; + } + return s; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/LinkLabel.java",".java","2633","90","package util; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.JLabel; + +/** + * LinkLabel creates a JLabel with its text underlined and a + * transparent background that changes foreground color when the mouse enters and exits. + * Only used by ManagerFrame, ChrExpFrame, sequence.TextBox + */ + +public class LinkLabel extends JLabel implements MouseListener { + private static final long serialVersionUID = 1L; + + private static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR); + + private Color defaultColor; + private Color hoverColor; + private String url; + + public LinkLabel(String text, Color color, Color hoverColor) { + super(text); + this.defaultColor = color; + this.hoverColor = hoverColor; + if (this.defaultColor == null) this.defaultColor = getForeground(); + if (this.hoverColor == null) this.hoverColor = getForeground(); + + if (defaultColor != null) setTheColor(defaultColor); + setOpaque(false); + addMouseListener(this); + } + + public LinkLabel(String text) { + this(text, Color.blue.darker().darker(), Color.blue); + } + + public LinkLabel(String text, Color color, Color hoverColor, String url) { + this(text, color, hoverColor); + this.url = url; + } + + public LinkLabel(String text, String url) { + this(text, Color.blue.darker().darker(), Color.blue, url); + } + + public void setColor(Color color) { + defaultColor = color; + } + public void setHoverColor(Color color) { + hoverColor = color; + } + + public void paint(Graphics g) { + super.paint(g); + Rectangle r = getBounds(); + g.drawLine(0, r.height - this.getFontMetrics(this.getFont()).getDescent() + 1, + this.getFontMetrics(this.getFont()).stringWidth(this.getText()), + r.height - this.getFontMetrics(this.getFont()).getDescent() + 1); + } + public void setupLink() { + FontMetrics fm = this.getFontMetrics(this.getFont()); + setSize(fm.stringWidth(this.getText()),fm.getMaxAscent()+fm.getMaxDescent()); + } + public void mouseEntered(MouseEvent e) { + setTheColor(hoverColor); + setCursor(HAND_CURSOR); + } + public void mouseExited(MouseEvent e) { + setTheColor(defaultColor); + setCursor(null); + } + public void mouseClicked(MouseEvent e) { + if (url != null) util.Jhtml.tryOpenURL(url); + } + public void mouseReleased(MouseEvent e) { } + public void mousePressed(MouseEvent e) { } + + private void setTheColor(Color c) { + setForeground(c); + setBackground(c); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/util/Cancelled.java",".java","335","13","package util; + +// Purpose - provide a way to tell threads they are cancelled b/c +// Java doesn't have a good way +public class Cancelled +{ + static boolean cancelled = false; + + public static boolean isCancelled() { return cancelled;} + public static void cancel() { cancelled = true;} + public static void init() { cancelled = false;} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/database/DBconn2.java",".java","21208","649","package database; + +/*********************************************************** + * Used by all for database connections + */ +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.sql.ResultSet; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.util.HashMap; + +import symap.Ext; +import symap.Globals; +import util.ErrorReport; + +// WARNING: Does not work for nested queries (because it uses one Statement for all queries). +// To do a query within the read loop of a previous query, use a second DBConn object. + +public class DBconn2 { + private final int maxTries = 10; + private final boolean TRACE = symap.Globals.DEBUG && symap.Globals.TRACE; + + static private String chrSQL = ""characterEncoding=utf8""; // utf8mb4 + static private String driver = ""com.mysql.cj.jdbc.Driver""; // add .cj for new driver + + // 1. Connections are associated with unique panels or view from CE (where dp, circle, 2d are reused). + // 2. Manager is the only one that stays open. The rest close when the window closes. + // 3. Multiple circles, etc can be opened; they each have there own connection, + // and will have their own suffix number. + // 4. connMap is for debugging to make sure connections are closed when done with. + // The following are the existing labels; they are only meaningful for debugging + // Process Label alt label + // ManagerFrame Manager + // Block Whole BlocksG-num Chr BlocksC-num (separate window) + // DotPlot DotplotG-num from CE DotplotE-num + // Circle CircleG-num from CE CircleE-num + // SyMAP2d CE SyMAP2dE-num popup SyMAP2dP-num + + static private HashMap connMap = new HashMap (); + static private int numConn=0; + static public int getNumConn() { + if (connMap.size()<=1) numConn=0; + return numConn++; + } + + private String mUser, mPass, mUrl, mHost, mDBname, pName; + + private Connection mConn = null; + private Statement mStmt = null; + + // used for manager dbc2 + public DBconn2(String name, String host, String dbname, String user, String pass) { + pName = name; + mHost = host; + mDBname = dbname; + mUser = user; + mPass = pass; + + mUrl = createDBstr(host, dbname); + mUrl += ""&useServerPrepStmts=false&rewriteBatchedStatements=true""; //TCW used, but symap was not + + if (renew()) { + connMap.put(pName, mConn); + prtNumConn(); + } + } + // others copy from manager dbc2 + public DBconn2(String name, DBconn2 db) { // pname is process + pName = name; + mUser = db.getUserid(); + mPass = db.getPassword(); + mHost = db.getHost(); + mDBname = db.getDBname(); + mUrl = db.getURL(); // contains host and database name + + if (renew()) { + connMap.put(pName, mConn); + prtNumConn(); + } + } + public void close() { + try { + if (mStmt!=null) mStmt.close(); + mStmt = null; + + connMap.remove(pName, connMap.get(pName)); + + if (mConn!=null && !mConn.isClosed()) mConn.close(); + mConn = null; + + if (TRACE) prt(""Close "" + pName); + } + catch (Exception e) {ErrorReport.print(e, ""Closing connection"");} + } + public void shutdown() { + try { + for (String n : connMap.keySet()) { + Connection c = connMap.get(n); + if (!c.isClosed()) { + if (TRACE) prt(""Close "" + n); + c.close(); + } + } + if (TRACE) { + Runtime rt = Runtime.getRuntime(); + long total_mem = rt.totalMemory(); + long free_mem = rt.freeMemory(); + long used_mem = total_mem - free_mem; + String mem = String.format(""%,dk"", (int) Math.round(used_mem/1000)); + + prt(String.format(""Memory %-20s\n\n"", mem)); + } + } + catch (Exception e) {ErrorReport.print(""Closing connections"");}; + } + public static void shutConns() { // called from ErrorReport - not tested + try { + for (String n : connMap.keySet()) { + Connection c = connMap.get(n); + if (!c.isClosed()) { + prt(""Close "" + n); + c.close(); + } + } + } + catch (Exception e) {ErrorReport.print(""Closing connections"");}; + } + public void prtNumConn() { + try { + if (connMap.size()==1) numConn=0; // Manager only, which has no number + if (connMap.size()>100) + System.err.println(""Warning: Too many MySQL connections are open. To be safe, restart SyMAP.""); + + if (!TRACE) return; + + ResultSet rs = executeQuery(""show status where variable_name='threads_connected'""); + while (rs.next()) prt(rs.getString(1) + "" "" + rs.getInt(2)); + rs.close(); + + for (String n : connMap.keySet()) prt("" Open "" + n); + } + catch (Exception e) {ErrorReport.print(e, ""Closing connection"");} + } + public String getURL() {return mUrl;} + public String getUserid() { return mUser; } + public String getPassword() { return mPass; } + public String getHost() { return mHost; } + public String getDBname() { return mDBname; } + public Connection getDBconn() { return mConn;} + + public boolean renew() { + try { + Class.forName(driver); + + if (mConn != null && !mConn.isClosed()) return true; + + if (mStmt!=null && !mStmt.isClosed()) mStmt.close(); + mStmt = null; + + for (int i = 0; i <= maxTries; i++) { + try { + mConn = DriverManager.getConnection(mUrl, mUser,mPass); + break; + } + catch (SQLException e) { + if (i == maxTries) + ErrorReport.die(e, ""Unable to connect to "" + mUrl + ""\nJava Exception: "" + e.getMessage()); + } + Thread.sleep(100); + } + return true; + } catch (Exception e) {ErrorReport.print(e, ""Renew connection""); return false;} + } + /****************************************** + * Main query code + */ + + public Statement createStatement() throws Exception { + return mConn.createStatement(); + } + public PreparedStatement prepareStatement(String st) throws SQLException { + return mConn.prepareStatement(st); + } + + private Statement getStatement() throws Exception { + if (mStmt == null) mStmt = mConn.createStatement(); + return mStmt; + } + + public int executeUpdate(String sql) throws Exception { + if (mConn == null || mConn.isClosed()) renew(); + Statement stmt = getStatement(); + int ret = 0; + try { + ret = stmt.executeUpdate(sql); + } + catch (Exception e) { + System.err.println(""Query failed, retrying:"" + sql); + mStmt.close(); + mStmt = null; + renew(); + stmt = getStatement(); + ret = stmt.executeUpdate(sql); + } + return ret; + } + + public ResultSet executeQuery(String sql) throws Exception { + if (mConn == null || mConn.isClosed()) renew(); + + Statement stmt = getStatement(); + ResultSet rs = null; + try { + rs = stmt.executeQuery(sql); + } + catch (Exception e) { + try { + mStmt.close(); + mStmt = null; + renew(); + stmt = getStatement(); + rs = stmt.executeQuery(sql); + } + catch (SQLException ee) { + System.err.println(""Query failed: "" + sql); + System.err.println(ee.getMessage()); + } + } + return rs; + } + public int executeCount(String sql) { + try { + ResultSet rs = executeQuery(sql); + int n = (rs.next()) ? rs.getInt(1) : -1; + rs.close(); + return n; + } + catch (Exception e) {ErrorReport.print(e, ""Getting counts""); return -1;} + } + public int executeInteger(String sql) {return executeCount(sql);} + public int getIdx(String sql) {return executeCount(sql);} + + public boolean executeBoolean(String sql) throws Exception { + try { + int cnt = executeCount(sql); + if (cnt==0) return false; + else return true; + } + catch (Exception e) {ErrorReport.print(e, ""Getting boolean""); return false;} + } + + public long executeLong(String sql) throws Exception { + try { + ResultSet rs = executeQuery(sql); + rs.next(); + long n = rs.getLong(1); + rs.close(); + return n; + } + catch (Exception e) {ErrorReport.print(e, ""Getting long""); return -1;} + } + public float executeFloat(String sql) throws Exception{ + try { + ResultSet rs = executeQuery(sql); + rs.next(); + float n = rs.getFloat(1); + rs.close(); + return n; + } + catch (Exception e) {ErrorReport.print(e, ""Getting float""); return -1;} + } + public String executeString(String sql) throws Exception { + try { + ResultSet rs = executeQuery(sql); + if (!rs.next()) return null; + String n = rs.getString(1); + rs.close(); + return n; + } + catch (Exception e) {ErrorReport.print(e, ""Getting string"");return null;} + } + + /************ + * table operations + *******************************************************/ + public boolean tablesExist() throws Exception { + boolean ret = false; + ResultSet rs = executeQuery(""show tables""); + if (rs!=null && rs.next()) ret = true; + if (rs!=null) rs.close(); + return ret; + } + public boolean tableExists(String name) throws Exception { + ResultSet rs = executeQuery(""show tables""); + while (rs.next()) { + if (rs.getString(1).equals(name)) { + rs.close(); + return true; + } + } + if (rs!=null) rs.close(); + return false; + } + public boolean tableColumnExists(String table, String column) throws Exception { + ResultSet rs = executeQuery(""show columns from "" + table); + while (rs.next()) { + if (rs.getString(1).equals(column)) { + rs.close(); + return true; + } + } + if (rs!=null) rs.close(); + return false; + } + public boolean tableDrop(String table) { + try { + if (tableExists(table)) { + executeUpdate (""DROP TABLE "" + table); + return true; + } + else return false; + } + catch (Exception e) {ErrorReport.print(e, ""Cannot drop table "" + table); return false;} + } + public boolean tableRename(String otab, String ntab) { + try { + if (tableExists(otab)) { + executeUpdate (""RENAME TABLE "" + otab + "" to "" + ntab); + return true; + } + else return false; + } + catch (Exception e) {ErrorReport.print(e, ""Cannot rename table "" + otab); return false;} + } + public void tableDelete(String table) { + try { // finding 'status' fails when 'show tables' succeeds (incorrectly) + ResultSet rs = executeQuery(""show table status like '"" + table + ""'""); + if (!rs.next()) { + rs.close(); + return; + } + executeUpdate (""TRUNCATE TABLE "" + table); // this resets auto-increment + } + catch(Exception e) { + System.err.println(""*** Database is probably corrupted""); + System.err.println(""*** MySQL finds table but then cannot delete from it.""); + ErrorReport.die(e,""Fatal error deleting table "" + table); + System.exit(-1); + } + } + public boolean tableCheckAddColumn(String table, String col, String type, String aft) throws Exception { + String cmd = ""alter table "" + table + "" add "" + col + "" "" + type ; + try { + if (!tableColumnExists(table,col)) { + if (aft!=null && !aft.trim().equals("""")) + cmd += "" after "" + aft; + executeUpdate(cmd); + return true; + } + return false; + } + catch(Exception e){ErrorReport.print(e, ""MySQL error: "" + cmd);} + return false; + } + public void tableCheckDropColumn(String table, String col) throws Exception { + if (tableColumnExists(table,col)){ + String cmd = ""alter table "" + table + "" drop "" + col; + executeUpdate(cmd); + } + } + + public void tableCheckRenameColumn(String table, String oldCol, String newCol, String type) throws Exception{ + if (tableColumnExists(table,oldCol)){ + String cmd = ""alter table "" + table + "" change column `"" + oldCol + ""` "" + newCol + "" "" + type ; + executeUpdate(cmd); + } + } + + public void tableCheckModifyColumn(String table, String col, String type) throws Exception{ + if (tableColumnExists(table,col)){ + String curDesc = tableGetColDesc(table,col); + if (!curDesc.equalsIgnoreCase(type)){ + String cmd = ""alter table "" + table + "" modify "" + col + "" "" + type ; + executeUpdate(cmd); + } + } + else {PrtWarn(""Tried to change column "" + table + ""."" + col + "", which does not exist"");} + } + + // Change column to new definition, if it doesn't already match. + // Note, the definition must be given exactly as seen in the ""show table"" listing, + // e.g. mediumint(8) and not just mediumint. + // If defs don't match, it will re-change the column, wasting time. + public void tableCheckChangeColumn(String table, String col, String type) throws Exception { + if (tableColumnExists(table,col)){ + String curDesc = tableGetColDesc(table,col); + if (!curDesc.equalsIgnoreCase(type)){ + String cmd = ""alter table "" + table + "" change "" + col + "" "" + col + "" "" + type ; + executeUpdate(cmd); + } + } + else {PrtWarn(""Tried to change column "" + table + ""."" + col + "", which does not exist"");} + } + public String tableGetColDesc(String tbl, String col){ + String ret = """"; + try { + ResultSet rs = executeQuery(""describe "" + tbl); + while (rs.next()) { + String fld = rs.getString(""Field""); + String desc = rs.getString(""Type""); + if (fld.equalsIgnoreCase(col)){ + ret = desc; + break; + } + } + } + catch(Exception e){ErrorReport.print(e, ""checking column description for "" + tbl + ""."" + col); + } + return ret; + } + + // NOT THREAD SAFE unless each thread is using its own DB connection. + public Integer lastID() throws Exception { + String st = ""select last_insert_id() as id""; + ResultSet rs = executeQuery(st); + int i = 0; + if (rs.next()) i = rs.getInt(""id""); + rs.close(); + return i; + } + + /***************************************************************************/ + public void resetAllIdx() { + try { + resetIdx(""idx"", ""annot_key""); + resetIdx(""idx"", ""blocks""); + resetIdx(""idx"", ""pairs""); + resetIdx(""idx"", ""projects""); + resetIdx(""idx"", ""pseudo_annot""); + resetIdx(""idx"", ""pseudo_hits""); + resetIdx(""idx"", ""xgroups""); + } + catch (Exception e) {ErrorReport.print(e, ""Reset auto-crement for all tables"");} + } + public void resetIdx(String idx, String table) { + try { + int cnt = getIdx(""select count(*) from "" + table); + if (cnt==0) { + executeUpdate(""ALTER TABLE "" + table + "" AUTO_INCREMENT = 1""); + } + else { + int max = getIdx(""select max("" + idx + "") from "" + table); + executeUpdate(""alter table "" + table + "" AUTO_INCREMENT="" + max); + } + } + catch (Exception e) {ErrorReport.print(e, ""Reset auto-increment for "" + table);} + } + /**************************************************************************** + * Check database settings when mysql database is created + */ + public void checkVariables(boolean prt) { + try{ + System.err.println(""\nCheck MySQL variables""); + int cntFlag=0; + + ResultSet rs = executeQuery(""show variables like 'max_allowed_packet'""); + if (rs.next()) { + long packet = rs.getLong(2); + + if (prt) System.err.println("" max_allowed_packet="" + packet); + if (packet<4194304) { + cntFlag++; + System.err.println("" Suggest: set global max_allowed_packet=4194304; # or greater""); + } + } + + rs = executeQuery(""show variables like 'innodb_buffer_pool_size'""); + if (rs.next()) { + long packet = rs.getLong(2); + + if (prt) System.err.println("" innodb_buffer_pool_size="" + packet); + if (packet< 134217728) { + cntFlag++; + System.err.println("" Suggest: set global innodb_buffer_pool_size=134217728; # or greater""); + } + } + + rs = executeQuery(""show variables like 'innodb_flush_log_at_trx_commit'""); + if (rs.next()) { + int b = rs.getInt(2); + if (prt) System.err.println("" innodb_flush_log_at_trx_commit="" + b); + if (b==1) { + cntFlag++; + System.err.println("" Suggest: set global innodb_flush_log_at_trx_commit=0""); + } + } + // CAS579c add to see if database search 'like %string%' will be case insensitive + if (Globals.INFO) { + rs = executeQuery(""SELECT DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA""); + if (rs.next()) { + String x = rs.getString(1); + if (x.endsWith(""_ci"")) System.err.println("" Database is search case-insensitive '"" + x +""'""); + else System.err.println("" Database is search case-sensitive '"" + x +""'""); + } + else System.err.println("" Cannot determine if database is case-insensitive""); + } + if (cntFlag>0) { + System.err.println(""For details: see "" + util.Jhtml.TROUBLE_GUIDE_URL); + } + else System.err.println("" MySQL variables are okay ""); + + Ext.checkExt(); + } + catch (Exception e) {ErrorReport.print(e, ""Getting system variables""); } + } + /************************************************************** + * Static methods + * ******************************************/ + + /************************************************************* + * Create database; + */ + public static int createDatabase(String hostname, String dbname, String username, String password) { + checkHost(hostname,username,password); + + int rc=0; // 0 create, -1 fail, 1 exist + Connection conn; + String dburl = createDBstr(hostname, dbname); + String hosturl = createDBstr(hostname, """"); + + try { // In case database exists without tables, i.e. failed earlier + conn = DriverManager.getConnection(dburl, username, password); + + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(""show tables""); + if (rs==null) { + System.out.println(""Create schema '"" + dbname + ""' ("" + dburl + "").""); + new Schema(conn); + } + stmt.close(); rs.close(); conn.close(); + rc=1; + } + catch (SQLException e) { // Create database + try { + System.out.println(""Creating database '"" + dbname + ""' ("" + dburl + "").""); + conn = DriverManager.getConnection(hosturl, username, password); + + Statement stmt = conn.createStatement(); + stmt.executeUpdate(""CREATE DATABASE "" + dbname); + stmt.close(); conn.close(); + + conn = DriverManager.getConnection(dburl, username, password); + new Schema(conn); + conn.close(); + rc = 0; + } + catch (SQLException e2) { + ErrorReport.print(e,""Error creating database '"" + dbname + ""'.""); + rc = -1; + } + } + return rc; + } + /*********************************************************** + * Database exists for the read only viewSymap + */ + public static boolean existDatabase(String hostname, String dbname, String username, String password) { + checkHost(hostname,username,password); + + try { + String hosturl = createDBstr(hostname, """"); + Connection conn = DriverManager.getConnection(hosturl, username, password); + + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(""SHOW DATABASES LIKE '"" + dbname + ""'""); + boolean b = (rs.next()) ? true : false; + stmt.close(); conn.close(); + return b; + } + catch (Exception e) {ErrorReport.print(e, ""Checking for database "" + dbname); return false;} + } + private static void checkHost(String hostname, String username, String password) { + try { + Class.forName(driver); + } + catch(Exception e) { ErrorReport.die(""Unable to find MySQL driver: "" + driver);} + + try { + String hosturl = createDBstr(hostname, """"); + Connection conn = DriverManager.getConnection(hosturl, username, password); + + SQLWarning warn = conn.getWarnings(); + while (warn != null) { + System.out.println(""SQLState: "" + warn.getSQLState()); + System.out.println(""Message: "" + warn.getMessage()); + System.out.println(""Error: "" + warn.getErrorCode()); + System.out.println(""""); + warn = warn.getNextWarning(); + } + + hasInnodb(conn); + conn.close(); + } + catch(Exception e) { + System.err.println(""Unable to connect to the mysql database on "" + hostname + ""; are username and password correct?""); + System.err.println("" Host: "" + hostname + "" Username: "" + username + "" Password: "" + password); + ErrorReport.die(e, ""Cannot connect to mysql""); + } + + } + private static void hasInnodb(Connection conn) throws Exception { + boolean has = false; + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(""show engines""); + while (rs.next()) { + String engine = rs.getString(1); + String status = rs.getString(2); + + if (engine.equalsIgnoreCase(""innodb"") && + (status.equalsIgnoreCase(""yes"") || status.equalsIgnoreCase(""default"")) ) { + has = true; + break; + } + } + if (!has) { + System.err.println(""The database does not support Innodb tables. Check the mysql error log problems.""); + System.exit(-1); + } + return; + } + + private static String createDBstr(String host, String db) { + if (db==null) { + String h = host.replace("";"", """"); // in case a ';' is at end of localhost in HOSTs.cfg + return ""jdbc:mysql://"" + h + ""?"" + chrSQL; + } + else { + String h = host.replace("";"", """"); + return ""jdbc:mysql://"" + h + ""/"" + db + ""?"" + chrSQL; + } + } + + static void PrtWarn(String msg) {System.out.println(""Warning: "" + msg);} + static void prt(String msg) {System.out.println(""+++ "" + msg);} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/database/Version.java",".java","16356","448","package database; + +/***************************************************** + * Schema update: select value from props where name='DBVER' + * Pair update: select idx, syVer from pairs + */ +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.HashSet; + +import backend.Utils; +import symap.Globals; +import util.ErrorReport; +import util.Popup; +import util.Utilities; + +public class Version { + public int dbVer = Globals.DBVER; + public String strVer = Globals.DBVERSTR; // db7 + public boolean dbdebug = Globals.DBDEBUG; // -dbd + + private DBconn2 dbc2=null; + + public Version(DBconn2 dbc2) { + this.dbc2 = dbc2; + } + public void check() { + checkForSchemaUpdate(); + checkForContentUpdate(); + + if (dbdebug) updateDEBUG(); + else removeDEBUG(); + } + public boolean isVerLt(int pairIdx, int vnum) { + try { + String v = dbc2.executeString(""select syVer from pairs where idx="" + pairIdx); + String vx = v.substring(1).replace(""."", """"); + int n = util.Utilities.getInt(vx); + if (n == -1) { // possible ending char + if (vx.length()>2) { + vx = vx.substring(0, vx.length()-1); // was using v instead of vx; CAS579c + n = util.Utilities.getInt(vx); + } + else Globals.prt(""Incorrect version: "" + v); + } + if (ndbVer) { + Popup.showWarningMessage(""This database schema is "" + strDBver + ""; this SyMAP version uses "" + strVer + + ""\nThis may not be a problem.....""); + return; + } + + if (!Popup.showYesNo(""DB update"", + ""Database schema needs updating from "" + strDBver + "" to "" + strVer +""\nProceed with update?"")) return; + + System.out.println(""Updating schema from "" + strDBver + "" to "" + strVer); + + if (idb==1) { + updateVer1(); + idb=2; + } + if (idb==2) { + updateVer2(); + idb=3; + } + if (idb==3) { + updateVer3(); + idb=4; + } + if (idb==4) { + updateVer4(); + idb=5; + } + if (idb==5) { + updateVer5(); + idb=6; + } + if (idb==6) { + updateVer6(); + idb=7; + } + } + catch (Exception e) {ErrorReport.print(e, ""Error checking database version"");} + } + private void updateVer1() { + try { + if (dbc2.tableRename(""groups"", ""xgroups"")) + updateProps(); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + // CAS512 gather all columns added with 'alter' + private void updateVer2() { + try { + dbc2.tableCheckDropColumn(""pseudo_annot"", ""text""); // lose 512 + dbc2.tableCheckAddColumn(""pseudo_annot"", ""genenum"", ""INTEGER default 0"", null); // added in SyntenyMain + dbc2.tableCheckAddColumn(""pseudo_annot"", ""gene_idx"", ""INTEGER default 0"", null); // new 512 + dbc2.tableCheckAddColumn(""pseudo_annot"", ""tag"", ""VARCHAR(30)"", null); // new 512 + dbc2.tableCheckAddColumn(""pseudo_hits"", ""runsize"", ""INTEGER default 0"", null); // checked in SyntenyMain + dbc2.tableCheckAddColumn(""pairs"", ""params"", ""VARCHAR(128)"", null); // added 511 + dbc2.tableCheckAddColumn(""blocks"", ""corr"", ""float default 0"", null); // SyMAPExp was checking for + + updateProps(); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + // v5.20.0 + private void updateVer3() { + try { + dbc2.executeUpdate(""alter table pseudo_hits modify countpct integer""); // Remove from AnchorsMain, 169 + dbc2.tableCheckAddColumn(""pseudo_hits"", ""runnum"", ""integer default 0"", null); + dbc2.tableCheckAddColumn(""pseudo_hits"", ""hitnum"", ""integer default 0"", null); + dbc2.tableCheckAddColumn(""pseudo_annot"", ""numhits"", ""tinyint unsigned default 0"", null); + + dbc2.tableCheckAddColumn(""pairs"", ""params"", ""tinytext"", null); // added in earlier version, but never checked + dbc2.tableCheckAddColumn(""pairs"", ""syver"", ""tinytext"", null); + dbc2.tableCheckAddColumn(""projects"", ""syver"", ""tinytext"", null); + + updateProps(); + + System.err.println(""For pre-v519 databases, reload annotation ""); + System.err.println(""For pre-v520 databases, recompute synteny ""); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + // v5.3.0 (code has v522, but major change) + private void updateVer4() { + try { + dbc2.tableDrop(""mrk_clone""); + dbc2.tableDrop(""mrk_ctg""); + dbc2.tableDrop(""clone_remarks_byctg""); + dbc2.tableDrop(""bes_block_hits""); + dbc2.tableDrop(""mrk_block_hits""); + dbc2.tableDrop(""fp_block_hits""); + dbc2.tableDrop(""shared_mrk_block_hits""); + dbc2.tableDrop(""shared_mrk_filter""); + + dbc2.tableDrop(""clones""); + dbc2.tableDrop(""markers""); + dbc2.tableDrop(""bes_seq""); + dbc2.tableDrop(""mrk_seq""); + dbc2.tableDrop(""clone_remarks""); + dbc2.tableDrop(""bes_hits""); + dbc2.tableDrop(""mrk_hits""); + dbc2.tableDrop(""fp_hits""); + dbc2.tableDrop(""ctghits""); + dbc2.tableDrop(""contigs""); + + dbc2.tableDrop(""mrk_filter""); + dbc2.tableDrop(""bes_filter""); + dbc2.tableDrop(""fp_filter""); + dbc2.tableDrop(""pseudo_filter""); // never used + + dbc2.tableCheckDropColumn(""blocks"", ""level""); + dbc2.tableCheckDropColumn(""blocks"", ""contained""); + dbc2.tableCheckDropColumn(""blocks"", ""ctgs1""); + dbc2.tableCheckDropColumn(""blocks"", ""ctgs2""); + + updateProps(); + System.err.println(""FPC tables removed from Schema. No user action necessary.\n"" + + "" Older verion SyMAP will not work with this database.""); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + // v5.4.3; however, these updates will be used in v5.4.4 + private void updateVer5() { + try { + dbc2.tableCheckAddColumn(""pseudo_hits"", ""htype"", ""tinyint unsigned default 0"", ""evalue"");// has to take evalue place + dbc2.tableCheckDropColumn(""pseudo_hits"", ""evalue""); + dbc2.tableCheckAddColumn(""pseudo_hits_annot"", ""htype"", ""tinyint unsigned default 0"", null); + + updateProps(); + + System.err.println(""To use the v5.4.3 hit-gene assignment upgrade, recompute synteny ""); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + // v5.4.6; htype was not being used; it is now with anchor2, but used as text + private void updateVer6() { + try { + dbc2.tableCheckModifyColumn(""pseudo_hits"", ""htype"", ""tinytext""); + dbc2.tableCheckAddColumn(""pseudo_hits_annot"", ""exlap"", ""tinyint default 0"", null); + dbc2.tableCheckAddColumn(""pseudo_hits_annot"", ""annot2_idx"", ""integer default 0"", null); + + updateProps(); + } + catch (Exception e) {ErrorReport.print(e, ""Could not update database"");} + } + + /**************************************************** + * -dbd + */ + private void updateDEBUG() { + try { + if (dbc2.tableColumnExists(""pairs"", ""proj_names"")) return; + + long time = Utils.getTime(); + System.out.println(""Update DB debug""); + +// projs + HashMap projIdxName = new HashMap (); + ResultSet rs = dbc2.executeQuery(""select idx, name from projects""); + while (rs.next()) projIdxName.put(rs.getInt(1), rs.getString(2)); + +// grps + HashMap grpIdxName = new HashMap (); + rs = dbc2.executeQuery(""select idx, name, proj_idx from xgroups""); + while (rs.next()) grpIdxName.put(rs.getInt(1), rs.getString(2)); + +// pairs pairsProjs = new HashMap (); + rs = dbc2.executeQuery(""select idx, proj1_idx, proj2_idx from pairs""); + while (rs.next()) { + int idx1 = rs.getInt(2); + int idx2 = rs.getInt(3); + String key = projIdxName.get(idx1) + "":"" + projIdxName.get(idx2); + pairsProjs.put(rs.getInt(1), key); + } + + // add pairs.proj_names + if (!dbc2.tableColumnExists(""pairs"", ""proj_names"")) { + dbc2.tableCheckAddColumn(""pairs"", ""proj_names"", ""tinytext"", ""proj2_idx""); + for (int pidx : pairsProjs.keySet()) { + dbc2.executeUpdate(""update pairs set proj_names='"" + pairsProjs.get(pidx) + ""' where idx="" + pidx); + } + System.out.println(""Update pairs""); + } + // add xgroups.proj_name + if (!dbc2.tableColumnExists(""xgroups"", ""proj_name"")) { + dbc2.tableCheckAddColumn(""xgroups"", ""proj_name"", ""tinytext"", ""fullname""); + for (int pidx : projIdxName.keySet()) { + dbc2.executeUpdate(""update xgroups set proj_name='"" + projIdxName.get(pidx) + ""' where proj_idx="" + pidx); + } + System.out.println(""Update xgroups""); + } + // add blocks.proj_names, grp1name, grp2name + if (!dbc2.tableColumnExists(""blocks"", ""proj_names"")) { + dbc2.tableCheckAddColumn(""blocks"", ""proj_names"", ""tinytext"", ""pair_idx""); + for (int pidx : pairsProjs.keySet()) { + dbc2.executeUpdate(""update blocks set proj_names='"" + pairsProjs.get(pidx) + ""' where pair_idx="" + pidx); + } + System.out.println(""Update blocks.pairs""); + } + if (!dbc2.tableColumnExists(""blocks"", ""grp1"")) { + dbc2.tableCheckAddColumn(""blocks"", ""grp1"", ""tinytext"", ""proj_names""); + dbc2.tableCheckAddColumn(""blocks"", ""grp2"", ""tinytext"", ""grp1""); + for (int gidx : grpIdxName.keySet()) { + dbc2.executeUpdate(""update blocks set grp1='"" + grpIdxName.get(gidx) + ""' where grp1_idx="" +gidx); + dbc2.executeUpdate(""update blocks set grp2='"" + grpIdxName.get(gidx) + ""' where grp2_idx="" +gidx); + } + System.out.println(""Update blocks.grps""); + } + + // -dbd add pseudo_annot_hit.pair_idx THIS IS SLOW + HashSet annotSet = new HashSet (); + HashSet hitSet = new HashSet (); + rs = dbc2.executeQuery(""select hit_idx, annot_idx from pseudo_hits_annot""); + while (rs.next()) { + hitSet.add(rs.getInt(1)); + annotSet.add(rs.getInt(2)); + } + System.out.println(""hits to genes: "" + hitSet.size() + "" "" + annotSet.size()); + + HashMap hitPairMap = new HashMap (); + rs = dbc2.executeQuery(""select idx, pair_idx from pseudo_hits""); + while (rs.next()) { + int idx = rs.getInt(1); + if (hitSet.contains(idx)) + hitPairMap.put(idx, rs.getInt(2)); + } + System.out.println(""Hits to process for xpair_idx: "" + hitPairMap.size()); + + dbc2.tableCheckAddColumn(""pseudo_hits_annot"", ""xpair_idx"", ""integer"", null); + int cnt=0; + for (int hidx : hitPairMap.keySet()) { + cnt++; + if (cnt%5000==0) System.out.print("" added "" + cnt + "" ....""); + dbc2.executeUpdate(""update pseudo_hits_annot set xpair_idx="" + hitPairMap.get(hidx) + "" where hit_idx="" +hidx); + } + hitPairMap.clear(); hitSet.clear(); + Globals.rprt(""Update pseudo_hits_annot.pair_idx""); + + // -dbd add pseudo_annot_hit.grp_idx and proj_idx + + HashMap annotGrpMap = new HashMap (); // annot_idx, grp_idx + + rs = dbc2.executeQuery(""select idx, grp_idx from pseudo_annot""); + while (rs.next()) { + int idx = rs.getInt(1); + if (annotSet.contains(idx)) + annotGrpMap.put(idx, rs.getInt(2)); + } + System.out.println(""Annot to process for xgrp_idx: "" + annotGrpMap.size()); + + dbc2.tableCheckAddColumn(""pseudo_hits_annot"", ""xgrp_idx"", ""integer"", null); + + cnt=0; + for (int aidx : annotGrpMap.keySet()) { + cnt++; + if (cnt%5000==0) Globals.rprt(""added "" + cnt); + int gidx = annotGrpMap.get(aidx); + dbc2.executeUpdate(""update pseudo_hits_annot set xgrp_idx="" + gidx + "" where annot_idx="" +aidx); + } + annotGrpMap.clear(); + + rs.close(); + System.out.println(""Update pseudo_hits_annot.grp_idx""); + Utils.prtMsgTimeDone(null, ""Update "", time ); + + }catch (Exception e) {ErrorReport.print(e, ""Could not update database for debug"");} + } + private void removeDEBUG() { + try { + if (!dbc2.tableColumnExists(""blocks"", ""proj_names"")) return; + + dbc2.tableCheckDropColumn(""pairs"", ""proj_names""); + dbc2.tableCheckDropColumn(""xgroups"",""proj_name""); + dbc2.tableCheckDropColumn(""blocks"", ""proj_names""); + dbc2.tableCheckDropColumn(""blocks"", ""grp1""); + dbc2.tableCheckDropColumn(""blocks"", ""grp2""); + dbc2.tableCheckDropColumn(""pseudo_hits_annot"", ""xpair_idx""); + dbc2.tableCheckDropColumn(""pseudo_hits_annot"", ""xgrp_idx""); + System.out.println(""Remove blocks.grp1/2, and blocks/pairs/xgroups proj_names, and pseudo_hits_annot proj/pair_idx""); + }catch (Exception e) {ErrorReport.print(e, ""Could not remove debug"");} + } + + /************************************************************************ + * if only DB content needs updating per project, do it here + */ + private void checkForContentUpdate() { + try { + // can only check version by making it intege + HashMap pairVer = new HashMap (); + ResultSet rs = dbc2.executeQuery(""select idx, syVer from pairs""); + while (rs.next()) { + int idx = rs.getInt(1); + String ver = rs.getString(2); + if (ver!=null) { // v5.5.2c + String x= ver.replaceAll(""([a-z])"", """"); + x = x.replaceAll(""\\."", """"); + int y = Utilities.getInt(x); + pairVer.put(idx, y); + } + } + + int chg=0; + for (int idx : pairVer.keySet()) { + int ver = pairVer.get(idx); + if (ver<548) { + int algo1 = dbc2.executeCount(""select value from pair_props where name='algo1' and pair_idx="" + idx); + + if (algo1==1) { + chg++;// gene_overlap% and pseudo_hits_annot.annot2_idx (for multi query) + System.err.println(getProjNames(idx) + "": Synteny for needs to be rerun for v548 Algo1 new features""); + } + else { + chg++;// gene and exon overlap, plus improved assignments + System.err.println(getProjNames(idx) + "": Synteny for needs to be rerun for v548 Algo2 new features""); + } + } + else if (ver<556) { + chg++; + System.err.println(getProjNames(idx) + "": Collinear sets for needs to be rerun for v556 improvements""); + } + } + + if (chg>0) { + System.err.println("" See https://csoderlund.github.io/SyMAP/SystemGuide.html#update for how to update.""); + } + } + catch (Exception e) {ErrorReport.print(e, ""Check For Content update"");} + } + private String getProjNames(int pairIdx) { + try { + int p1 = dbc2.executeCount(""select proj1_idx from pairs where idx="" + pairIdx); + int p2 = dbc2.executeCount(""select proj2_idx from pairs where idx="" + pairIdx); + String n1 = dbc2.executeString(""select name from projects where idx="" + p1); + String n2 = dbc2.executeString(""select name from projects where idx="" + p2); + return n1 + "" vs "" + n2; + } + catch (Exception e) {ErrorReport.print(e, ""Get project name""); return ""error"";} + } + + /*************************************************************** + * Run after every version update. + * The props table values of DBVER and UPDATE are hardcoded in Schema. + * + * if screw up, force update: update props set value=1 where name=""DBVER"" + */ + private void updateProps() { + try { + replaceProps(""UPDATE"", Utilities.getDateOnly()); + + replaceProps(""VERSION"",Globals.VERSION); + + replaceProps(""DBVER"", Globals.DBVERSTR); + System.err.println(""Complete schema update to "" + Globals.DBVERSTR + "" for SyMAP "" + Globals.VERSION ); + } + catch (Exception e) {ErrorReport.print(e, ""Error updating props"");} + } + /************************************************************* + * Any update from ManagerFrame calls this + */ + public void updateReplaceProp() { + try { + replaceProps(""UPDATE"", Utilities.getDateOnly()); + + replaceProps(""VERSION"",Globals.VERSION); + } + catch (Exception e) {ErrorReport.print(e, ""Error replacing props"");} + } + private void replaceProps(String name, String value) { + String sql=""""; + try { + ResultSet rs = dbc2.executeQuery(""select value from props where name='"" + name + ""'""); + if (rs.next()) { + sql = ""UPDATE props set value='"" + value + ""' where name='"" + name + ""'; ""; + } + else { + sql = ""INSERT INTO props (name,value) VALUES "" + ""('"" + name + ""','"" + value + ""'); ""; + } + dbc2.executeUpdate(sql); + } + catch (Exception e) {ErrorReport.print(e, ""Replace props: "" + sql);} + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/database/Schema.java",".java","12471","288","package database; + +import java.sql.Connection; +import java.sql.Statement; + +import symap.Globals; +import util.ErrorReport; +import util.Utilities; + +/*** +* The term pseudo is used for pseudo molecules to distinguish from fpc_ tables that are removed +* The term is also used for Numbered Pseudos as a type in pseudo_annot +* +* CHAR: tinytext 1 byte, text 2 byte, mediumtext 2 byte +* max 256 char 65k char 16M char +* use VARCHAR for fields that need to be searched +* INT tinyint 1 byte, smallint 2 byte, mediumint 3 byte, int 4 byte, bigint 8 byte +* max 256 65k 16M 4394M +* float 4 byte, double 8 byte +*****/ + +public class Schema { + + public Schema(Connection conn) { + mConn = conn; +// Projects + String sql = ""CREATE TABLE props ("" + + ""name VARCHAR(40) NOT NULL,"" + + ""value VARCHAR(255) NOT NULL"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE projects ("" + + ""idx INTEGER NOT NULL AUTO_INCREMENT,"" + // proj_idx + ""type enum('fpc','pseudo') NOT NULL,"" + + ""name VARCHAR(40) NOT NULL,"" + + ""hasannot boolean default 0,"" + + ""annotdate datetime,"" + // date of load sequence and/or annotation + ""loaddate datetime,"" + // db create, update synteny + ""syver tinytext,"" + // version of load sequence and/or annotation + ""PRIMARY KEY (idx),"" + + ""UNIQUE INDEX (name),"" + + ""INDEX (type)"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE proj_props ("" + + ""proj_idx INTEGER NOT NULL,"" + + ""name VARCHAR(40) NOT NULL,"" + // key:value parameters, etc + ""value VARCHAR(255) NOT NULL,"" + + ""UNIQUE INDEX (proj_idx,name),"" + + ""FOREIGN KEY (proj_idx) REFERENCES projects (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE xgroups ("" + // groups is a mysql reserved word, hence, xgroups + ""idx INTEGER NOT NULL AUTO_INCREMENT,"" + // grp_idx + ""proj_idx INTEGER NOT NULL,"" + + ""name VARCHAR(40) NOT NULL,"" + + ""fullname VARCHAR(40) NOT NULL,"" + + ""sort_order INTEGER UNSIGNED NOT NULL,"" + + ""flipped BOOLEAN default 0,"" + + ""PRIMARY KEY (idx),"" + + ""UNIQUE INDEX (proj_idx,name),"" + + ""FOREIGN KEY (proj_idx) REFERENCES projects (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + +// Pairs + sql = ""CREATE TABLE pairs ("" + + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + + ""proj1_idx INTEGER NOT NULL,"" + + ""proj2_idx INTEGER NOT NULL,"" + + ""aligned BOOLEAN default 0,"" + + ""aligndate datetime,"" + // update date; used by summary (added Mpairs.saveUpdate) + ""syver tinytext,"" + // update version; version of load sequence and/or annotation + ""params text,"" + // parameters used for MUMmer; + ""summary text, "" + // full summary + ""UNIQUE INDEX (proj1_idx,proj2_idx),"" + + ""FOREIGN KEY (proj1_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj2_idx) REFERENCES projects (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE pair_props ("" + + ""pair_idx INTEGER NOT NULL,"" + + ""proj1_idx INTEGER NOT NULL,"" + + ""proj2_idx INTEGER NOT NULL,"" + + ""name VARCHAR(400) NOT NULL,"" + // key: value parameters, etc + ""value VARCHAR(255) NOT NULL,"" + + ""UNIQUE INDEX(proj1_idx,proj2_idx,name),"" + + ""INDEX (proj2_idx),"" + + ""FOREIGN KEY (pair_idx) REFERENCES pairs (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj1_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj2_idx) REFERENCES projects (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + +// Sequence + sql = ""CREATE TABLE pseudos ("" + // These are chromosome, scaffolds, etc (from pseudomolecule) + ""grp_idx INTEGER NOT NULL,"" + + ""file TEXT NOT NULL,"" + + ""length INTEGER NOT NULL,"" + + ""PRIMARY KEY (grp_idx),"" + + ""FOREIGN KEY (grp_idx) REFERENCES xgroups (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE pseudo_seq2 ( "" + + ""grp_idx INTEGER NOT NULL,"" + + ""chunk INTEGER NOT NULL,"" + + ""seq LONGTEXT NOT NULL,"" + + ""INDEX (grp_idx),"" + + ""FOREIGN KEY (grp_idx) REFERENCES xgroups (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB; ""; + executeUpdate(sql); + +// Annotation + sql = ""CREATE TABLE pseudo_annot ("" + + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // annot_idx + ""grp_idx INTEGER NOT NULL,"" + // xgroups.idx + ""type VARCHAR(20) NOT NULL,"" + // gene, exon, centromere, gap, pseudo (Numbered but not annotated gene); + ""genenum INTEGER default 0,"" + + // Gene: genenum.{suffix} (#Exons len); Exon: exon# + ""tag VARCHAR(30),"" + + ""gene_idx INTEGER default 0,"" + // gene idx for exon + // numhits for Gene: # of hits across all pairs for Query; Updated in AnchorMain; + // numhits for Pseudo: pairIdx for remove Number Pseudo; Updated in AnchorMain; + ""numhits INTEGER unsigned default 0,"" + //used for Pseudo for pairIdx; + ""name TEXT NOT NULL,"" + // description, list of keyword=value + ""strand ENUM('+','-') NOT NULL,"" + + ""start INTEGER NOT NULL,"" + + ""end INTEGER NOT NULL,"" + + ""INDEX (grp_idx,type),"" + + ""FOREIGN KEY (grp_idx) REFERENCES xgroups (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB; ""; + executeUpdate(sql); + + // keywords for project annotation + sql = ""CREATE Table annot_key ( "" + + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // not reference + ""proj_idx INTEGER NOT NULL, "" + + ""keyname TEXT, "" + + ""count BIGINT DEFAULT 0, "" + + ""FOREIGN KEY (proj_idx) REFERENCES projects (idx) ON DELETE CASCADE "" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + +// Hits + sql = ""CREATE TABLE pseudo_hits ("" + + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // hit_id + ""hitnum INTEGER default 0,""+ // relative to location along chr + ""pair_idx INTEGER NOT NULL,"" + + ""proj1_idx INTEGER NOT NULL,"" + // proj_props.proj_idx + ""proj2_idx INTEGER NOT NULL,"" + // proj_props.proj_idx + ""grp1_idx INTEGER NOT NULL,"" + // xgroups.idx + ""grp2_idx INTEGER NOT NULL,"" + // xgroups.idx + + ""start1 INTEGER NOT NULL,"" + + ""end1 INTEGER NOT NULL,"" + + ""start2 INTEGER NOT NULL,"" + + ""end2 INTEGER NOT NULL, "" + + + ""annot1_idx INTEGER default 0,"" + // can have>0 when pseudo_annot.type='pseudo' + ""annot2_idx INTEGER default 0,"" + + ""strand TEXT NOT NULL,"" + + ""refidx INTEGER default 0,"" + // used in self-synteny + ""runnum INTEGER default 0,"" + // number for collinear group + ""runsize INTEGER default 0,"" + // size of collinear set + ""gene_overlap TINYINT NOT NULL, "" + // 0,1,2; pseudo can be on one side only, for this to be 1 + + ""pctid TINYINT UNSIGNED NOT NULL,"" + // avg %id mummer Col6 + ""cvgpct TINYINT UNSIGNED NOT NULL,"" + // avg %sim mummer Col7 + ""countpct INTEGER UNSIGNED default 0,"" + // number of merged + ""score INTEGER NOT NULL,"" + // summed length + ""htype TINYTEXT,"" + // algo2: EE, EI, IE, En, nE, II, In, nI, nn; algo1: g2, g1, g0 + + ""query_seq MEDIUMTEXT NOT NULL,"" + // start-end of each merged hit + ""target_seq MEDIUMTEXT NOT NULL,"" + + + ""INDEX (proj1_idx,proj2_idx,grp1_idx,grp2_idx),"" + + ""FOREIGN KEY (pair_idx) REFERENCES pairs (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj1_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj2_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (grp1_idx) REFERENCES xgroups (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (grp2_idx) REFERENCES xgroups (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB; ""; + executeUpdate(sql); + + sql = ""CREATE TABLE pseudo_hits_annot ("" + + ""hit_idx INTEGER NOT NULL,"" + // pseudo_hits.idx + ""annot_idx INTEGER NOT NULL,"" + // pseudo_annot.idx + ""olap INTEGER default 0,"" + // gene overlap; algo1 basepairs; algo2 percent + ""exlap tinyint default 0,"" + // exon percentoverlap + ""annot2_idx INTEGER default 0,"" + // not present for type pseudo; + ""UNIQUE (hit_idx, annot_idx),"" + + ""INDEX (annot_idx),"" + + ""FOREIGN KEY (hit_idx) REFERENCES pseudo_hits (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (annot_idx) REFERENCES pseudo_annot (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB; ""; + executeUpdate(sql); + +// Blocks + // Finally fixed so that Self-synteny does not require order of fields; CAS575 + sql = ""CREATE TABLE blocks ("" + + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // block_idx + ""pair_idx INTEGER NOT NULL,"" + + ""proj1_idx INTEGER NOT NULL,"" + + ""proj2_idx INTEGER NOT NULL,"" + + + ""grp1_idx INTEGER NOT NULL,"" + + ""grp2_idx INTEGER NOT NULL,"" + + ""blocknum INTEGER NOT NULL,"" + + ""start1 INTEGER NOT NULL,"" + + ""end1 INTEGER NOT NULL,"" + + ""start2 INTEGER NOT NULL,"" + + ""end2 INTEGER NOT NULL,"" + + + ""score INTEGER default 0,"" + // number of hits in blocsk + ""corr float default 0,"" + // <0 is inverted + ""avgGap1 INTEGER default 0,"" + // for report; + ""avgGap2 INTEGER default 0,"" + // in report; calc approx if not exist + ""ngene1 integer default 0,"" + + ""ngene2 integer default 0,"" + + ""genef1 float default 0,"" + + ""genef2 float default 0,"" + + ""comment TEXT NOT NULL,"" + + + ""INDEX (proj1_idx,grp1_idx),"" + + ""INDEX (proj2_idx,grp2_idx),"" + + ""FOREIGN KEY (pair_idx) REFERENCES pairs (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj1_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (proj2_idx) REFERENCES projects (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (grp1_idx) REFERENCES xgroups (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (grp2_idx) REFERENCES xgroups (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + + sql = ""CREATE TABLE pseudo_block_hits ("" + + ""hit_idx INTEGER NOT NULL,"" + + ""block_idx INTEGER NOT NULL,"" + + ""INDEX (hit_idx),"" + + ""INDEX (block_idx),"" + + ""FOREIGN KEY (hit_idx) REFERENCES pseudo_hits (idx) ON DELETE CASCADE,"" + + ""FOREIGN KEY (block_idx) REFERENCES blocks (idx) ON DELETE CASCADE"" + + "") ENGINE = InnoDB;""; + executeUpdate(sql); + +// Other + sql = ""SET FOREIGN_KEY_CHECKS = 1;""; + executeUpdate(sql); + + String date = Utilities.getDateOnly(); + + // never change + sql = ""INSERT INTO props (name,value) VALUES ('INIT', '"" + date + ""'); ""; + executeUpdate(sql); + + sql = ""INSERT INTO props (name,value) VALUES ('INITV','"" + Globals.VERSION + ""'); ""; + executeUpdate(sql); + + sql = ""INSERT INTO props (name,value) VALUES ('INITDB','"" + Globals.DBVERSTR + ""'); ""; + executeUpdate(sql); + + // updated in Version + sql = ""INSERT INTO props (name,value) VALUES ('UPDATE', '"" + date + ""'); ""; + executeUpdate(sql); + + sql = ""INSERT INTO props (name,value) VALUES ('VERSION','"" + Globals.VERSION + ""'); ""; + executeUpdate(sql); + + sql = ""INSERT INTO props (name,value) VALUES ('DBVER','"" + Globals.DBVERSTR + ""'); ""; + executeUpdate(sql); + } + private int executeUpdate(String sql) { + int ret=0; + try{ + Statement stmt = mConn.createStatement(); + ret = stmt.executeUpdate(sql); + stmt.close(); + } + catch (Exception e){ErrorReport.die(e, ""Query failed:"" + sql);} + + return ret; + } + private Connection mConn; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/Split.java",".java","6892","226","package toSymap; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.HashSet; + +import backend.Constants; +import backend.Utils; +import util.ErrorReport; +import util.FileDir; + +/********************************************************* + * Splits converted files into chromosome files. Must be converted files. + */ +public class Split { + private final String header = ""### Written by SyMAP Convert""; + private String logFileName = ""/xSplit.log""; + + //output - the projDir gets appended to the front - predefined names, do not change + private String seqDir = Constants.seqSeqDataDir; // Default sequence directory for symap + private String annoDir = Constants.seqAnnoDataDir; // Default annotation directory for symap + private String inFaFile = ""genomic""; // tries .fna and .fa (constant in Convert methods) + private String inGffFile = ""anno""; // tries .gff and .gff3 (constant in Convert methods) + + private String seqScafFile = ""scaf.fna""; + private String seqSuffix = "".fna""; + private String annoScafFile = ""scaf.gff""; + private String annoSuffix = "".gff""; + + // From ConvertNCBI and ConvertEnsembl + private String chrPrefix=""Chr"", chrPrefix2 = ""C"", chrType=""chromosome""; // changed to ""C"" if scaffolds too + + private String projDir=""""; + + private HashSet chrSet = new HashSet (); + + private PrintWriter logFile=null; + + protected Split(String dirName) { + projDir = dirName; + + prt(""""); + prt(""------ Split files for "" + dirName + "" ------""); + createLog(); + + splitFasta(); + splitAnno(); + + prt(""----- Finish split for "" + dirName + "" -------""); + if (logFile!=null) logFile.close(); + } + /*************************************************************************/ + private void splitFasta() { + try { + String seqDirName = projDir + seqDir; + if (!FileDir.pathExists(seqDirName)) { + util.Popup.showWarningMessage(""Directory does not exist: "" + seqDirName); + return; + } + File sf = new File(seqDirName, inFaFile + "".fna""); + if (!sf.exists()) { + sf = new File(seqDirName, inFaFile + "".fa""); + if (!sf.exists()) { + prt(""No sequence file called "" + seqDirName + inFaFile + "".fna or .fa""); + return; + } + } + /////////////////////////////////////////////////////// + BufferedReader fin = Utils.openGZIP(sf.getAbsolutePath()); + if (fin==null) return; + String line = fin.readLine(); + if (!line.startsWith(header)) { + prt(""Incorrect 1st line: "" + line); + prt(""The line should start with: "" + header); + return; + } + String xHead = line; + boolean isScaf=false; + + PrintWriter fhOut=null; + String filename=""file""; + int seqLen=0, badLines=0; + + while ((line = fin.readLine()) != null) { + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().isEmpty()) continue; + + if (line.startsWith("">"")) { + if (fhOut!=null && !isScaf) { + fhOut.close(); + prt(String.format(""Write %-10s %,d"", filename, seqLen)); + seqLen=0; + } + String line1 = line.substring(1).trim(); + String [] tok = line1.split(""\\s+""); + if (tok.length==0) { + prt(""****"" + line); + if (badLines++>3) return; + continue; + } + String chr = tok[0]; + if (line.contains(chrType) || chr.startsWith(chrPrefix) || chr.startsWith(chrPrefix2)) { + filename = chr + seqSuffix; + fhOut = new PrintWriter(new FileOutputStream(seqDirName + filename, false)); + fhOut.println(xHead); + chrSet.add(chr); + } + else if (!isScaf) { + filename = seqScafFile; + fhOut = new PrintWriter(new FileOutputStream(seqDirName + filename, false)); + fhOut.println(xHead); + isScaf = true; + } + fhOut.println(line); + } + else { + seqLen += line.length(); + fhOut.println(line); + } + } + if (fhOut!=null) { + fhOut.close(); + prt(String.format(""Write %-10s %,d"", filename, seqLen)); + } + fin.close(); + /////////////////////////////////////////////////////// + // Delete original + prt(""Delete "" + sf.getName()); + sf.delete(); + } + catch (Exception e) {ErrorReport.print(e, ""Split Read FASTA "");} + } + /*************************************************************************/ + private void splitAnno() { + try { + if (chrSet.size()==0) { + prt(""No sequences read from /sequence directory""); + return; + } + String annoDirName = projDir + annoDir; + if (!FileDir.pathExists(annoDirName)) { + prt(""Directory does not exist: "" + annoDirName); + return; + } + File af = new File(annoDirName, inGffFile + "".gff""); + if (!af.exists()) { + af = new File(annoDirName, inGffFile + "".gff3""); + if (!af.exists()) { + prt(""No annotation file called "" + annoDirName + inGffFile + "".gff or .gff3""); + return; + } + } + /////////////////////////////////////////////////////// + BufferedReader fin = Utils.openGZIP(af.getAbsolutePath()); + if (fin==null) return; + + String line = fin.readLine(); + if (!line.startsWith(header)) { + prt(""Incorrect 1st line: "" + line); + prt(""The line should start with: "" + header); + return; + } + String xHead = line, lastChr=null, filename=""""; + boolean isScaf=false; + PrintWriter ghOut=null; + int cntLines=0, badLines=0; + + while ((line = fin.readLine()) != null) { + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().isEmpty()) continue; + cntLines++; + String [] tok = line.split(""\\s+""); + if (tok.length==0) { + prt(""****"" + line); + if (badLines++>3) return; + continue; + } + String chr = tok[0]; + + if (chr.equals(lastChr) || isScaf) { + ghOut.println(line); + continue; + } + + if (ghOut!=null) { + ghOut.close(); + prt(String.format(""Write %-10s %,d lines"", filename, cntLines)); + cntLines=0; + } + if (chrSet.contains(chr)) { + lastChr = chr; + filename = chr + annoSuffix; + } + else { + isScaf = true; + filename = annoScafFile; + } + ghOut = new PrintWriter(new FileOutputStream(annoDirName + filename, false)); + ghOut.println(xHead); + ghOut.println(line); + } + if (ghOut!=null) ghOut.close(); + fin.close(); + + /////////////////////////////////////////////////////// + prt(""Delete "" + af.getName()); + af.delete(); + } + catch (Exception e) {ErrorReport.print(e, ""Split Read anno "");} + } + /*************************************************************************/ + private void createLog() { + logFileName = projDir + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {ErrorReport.print(""Cannot open "" + logFileName); logFile=null;} + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/Lengths.java",".java","4989","172","package toSymap; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.Vector; + +import backend.Utils; +import util.ErrorReport; +import util.Popup; +import util.FileDir; + +/************************************************ + * Print lengths of sequences from converted files + */ +public class Lengths { + private final String seqSubDir = backend.Constants.seqSeqDataDir; + private String logFileName = ""/xLengths.log""; + + private final int [] cutoffs = {10,20,30,40,50,60,70,80,90,100}; + private final String [] fastaFile = {"".fa"", "".fna""}; // converted files + private final int maxLenForPrt=500; + + private PrintWriter logFile=null; + private String projDir="""", seqDirName=""""; + private Vector seqFiles = new Vector (); + + private Vector lenVec = new Vector (); + + protected Lengths(String projDir) { + this.projDir = projDir; + + seqDirName = FileDir.fileNormalizePath(projDir, seqSubDir); + if (!FileDir.pathExists(seqDirName)) { + Popup.showWarningMessage(""Path for sequence files does not exist: "" + seqDirName); + return; + } + getSeqFiles(); + if (seqFiles.size()==0) { + Popup.showWarningMessage(""No .fa or .fna files in: "" + seqDirName); + return; + } + prt(""""); + prt(""------ Output lengths for "" + seqDirName + "" ------""); + createLog(); + + readFasta(); + findCutoff(); + + prt(""----- Finish lengths for "" + seqDirName + "" -------""); + if (logFile!=null) logFile.close(); + } + /*********************************************************/ + private void readFasta() { + try { + if (seqFiles.size()>1) prt(""FASTA files "" + seqFiles.size()); + + int cntSeq=0, cntLen=0; + long total=0; + prt(String.format(""\n%5s %-10s %s"", ""Seq#"", ""Length"", ""Seqid"")); + + for (File f : seqFiles) { + BufferedReader fh = Utils.openGZIP(f.getAbsolutePath()); + if (fh==null) { + prt(""Cannot open "" + f.getAbsolutePath()); + return; + } + String line, grpFullName="""", saveLine=""""; + int len=0; + + while ((line = fh.readLine()) != null) { + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().isEmpty()) continue; + + if (line.startsWith("">"")) { + if (len>0) { + cntSeq++; + if (len>maxLenForPrt) prt(String.format(""%5d %,10d %s"", cntSeq, len, saveLine)); + else { + cntLen++; + if (cntLen%1000==0) System.out.print(cntLen + "" short sequences....\r""); + } + lenVec.add(len); + total += len; + } + len=0; + saveLine = line; + grpFullName = Utils.parseGrpFullName(line); + + if (grpFullName==null || grpFullName.equals("""")){ + Popup.showWarningMessage(""Unable to parse group name from:"" + line); + return; + } + } + else len += line.length(); + } + if (len>0) { + cntSeq++; + if (len>maxLenForPrt) prt(String.format(""%5d %,10d %s"", cntSeq, len, saveLine)); + else { + cntLen++; + if (cntLen%1000==0) System.out.print(cntLen + "" short sequences....\r""); + } + lenVec.add(len); + total += len; + } + } + System.out.print("" \r""); + if (cntLen>0) prt(String.format(""#Seqs<%d %,d"", maxLenForPrt, cntLen)); + prt(String.format(""Total %,d"", total)); + } + catch (Exception e) {ErrorReport.print(""Length Read FASTA "");} + } + /******************************************************/ + private void findCutoff() { + try { + if (lenVec.size()=lenVec.size()) break; + + prt(String.format(""%,5d %,8d"", x, lenVec.get(x-1))); + } + } + catch (Exception e) {ErrorReport.print(""Length Summary "");} + } + /******************************************************/ + private void getSeqFiles() { + try { + File sdf = new File(seqDirName); + if (!sdf.exists() || !sdf.isDirectory()) { + prt(""Incorrect directory name: "" + seqDirName); + return; + } + + for (File f2 : sdf.listFiles()) { + String name = f2.getAbsolutePath(); + for (String suf : fastaFile) { + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + seqFiles.add(f2); + break; + } + } + } + } + catch (Exception e) {ErrorReport.print(e, ""Cannot get sequence files"");} + } + private void createLog() { + logFileName = projDir + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {ErrorReport.print(""Cannot open "" + logFileName); logFile=null;} + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/ConvertNCBI.java",".java","37745","1038","package toSymap; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.zip.GZIPInputStream; +import java.util.TreeMap; +import java.util.HashMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/************************************************************* + * ConvertNCBI: NCBI genome files formatted for SyMAP + * See https://csoderlund.github.io/SyMAP/input/ncbi.html + * + * Called from xToSymap, but can be used stand-alone. + * + * This assumes input of the project directory, which has either + * 1. The ncbi_dataset.zip unzipped, .e.g + * /data/seq/Arab/ncbi_dataset/data/GCF_000001735.4 + * or the .fna and .gff files directly under the project directory + * + * Note: I am no expert on NCBI GFF format, so I cannot guarantee this is 100% correct mapping for all input. + * Your sequences/annotations may have other variations. + * Hence, you may want to edit this to customize it for your needs -- its simply written so easy to modify. + * See https://csoderlund.github.io/SyMAP/input/ncbi.html#edit + * + * From NCBI book and confirm by https://ftp.ncbi.nlm.nih.gov/refseq/release/release-notes/RefSeq-release225.txt + * AC_ Genomic Complete genomic molecule, usually alternate assembly (or linkage) + * NC_ Genomic Complete genomic molecule, usually reference assembly (or linkage) - use sequence unless Prefix only disqualifies + * NG_ Genomic Incomplete genomic region + * NT_ Genomic Contig or scaffold, clone-based or WGS - use sequence if scaffold + * NW_ Genomic Contig or scaffold, primarily WGS - use sequence if scaffold + * NZ_ Genomic Complete genomes and unfinished WGS data + * + Gene attributes written: ID=geneID; Name=(if not contained in geneID); + rnaID= first mRNA ID (cnt of number of mRNAs) + desc=gene description or 1st mRNA product + protein-ID=1st CDS for 1st mRNA + */ + +public class ConvertNCBI { + static private boolean isToSymap=true; + static private int defGapLen=30000; + + private final String header = ""### Written by SyMAP ConvertNCBI""; // Split expects this to be 1st line + private String logFileName = ""/xConvertNCBI.log""; + private final String plus =""+"", star=""*""; + + //output - the projDir gets appended to the front + private String seqDir = ""sequence""; // Default sequence directory for symap + private String annoDir = ""annotation""; // Default annotation directory for symap + private final String outFaFile = ""/genomic.fna""; // Split expects this name + private final String outGffFile = ""/anno.gff""; // Split expects this name + private final String outGapFile = ""/gap.gff""; + + // downloaded via NCBI Dataset link + private final String ncbi_dataset=""ncbi_dataset""; + private final String ncbi_data= ""/data""; + private final String faSuffix = "".fna""; + private final String gffSuffix = "".gff""; + private String subDir=null; + + // args (can be set from command line) + private boolean INCLUDESCAF = false; + private boolean INCLUDEMtPt = false; + private boolean MASKED = false; + private boolean ATTRPROT = false; + private boolean VERBOSE = false; + + // args (if running standalone, change in main) + private int gapMinLen; // Print to gap.gff if #N's is greater than this + private String prefixOnly=null; // e.g. NC + + // Changed for specific input; if unknown and prefixOnly, no suffix + private String chrPrefix=""Chr"", chrPrefix2=""C"", chrType=""chromosome""; // These are checked in Split + private String scafPrefix=""s"", scafType=""scaffold""; // single letter is used because the ""Chr"" is usually removed to save space + private String unkPrefix=""Unk"", unkType=""unknown""; + + private int traceNum=5; // if verbose, change to 20 + private final int traceScafMaxLen=10000; // All scaffold are printed to fasta file, but only summarized if >scafMax + private final int traceNumGenes=3; // Only print sequence if at least this many genes + + // types + private final String geneType = ""gene""; + private final String mrnaType = ""mRNA""; + private final String exonType = ""exon""; + private final String cdsType = ""CDS""; + + // attribute keywords + private final String idAttrKey = ""ID""; + private final String nameAttrKey = ""Name""; + private final String biotypeAttrKey = ""gene_biotype""; + private final String biotypeAttr = ""protein_coding""; + private final String parentAttrKey = ""Parent""; + private final String productAttrKey = ""product""; + private final String descAttrKey = ""description""; + private final String exonGeneAttrKey = ""gene""; + private final String cdsProteinAttrKey = ""protein_id""; + + private final String PROTEINID = ""proteinID=""; // keywords for gene attributes + private final String MRNAID = ""rnaID=""; // ditto + private final String DESC = ""desc=""; // ditto + private final String RMGENE = ""gene-""; + private final String RMRNA = ""rna-""; + + // input + private String projDir = null; + private String inFaFile = null; + private String inGffFile = null; + + // Other global variables + private TreeMap chr2id = new TreeMap (); + private TreeMap id2chr = new TreeMap (); + private TreeMap id2scaf = new TreeMap (); + private TreeMap cntChrGene = new TreeMap (); + private TreeMap cntScafGene = new TreeMap (); + + // Summary + private TreeMap allTypeCnt = new TreeMap (); + private TreeMap allGeneBiotypeCnt = new TreeMap (); + private TreeMap allGeneSrcCnt = new TreeMap (); + private int cntChrGeneAll=0, cntScafGeneAll=0, cntGeneNotOnSeq=0, cntScafSmall=0; + + private int nChr=0, nScaf=0, nMt=0, nUnk=0, nGap=0; // for numbering output seqid and totals + private int cntChr=0, cntScaf=0, cntMtPt=0, cntUnk=0, cntOutSeq=0, cntNoOutSeq=0; + private long chrLen=0, scafLen=0, mtptLen=0, unkLen=0, totalLen=0; + + private PrintWriter fhOut, ghOut; + private PrintWriter logFile=null; + + private int cntMask=0; + private TreeMap cntBase = new TreeMap (); + private HashMap hexMap = new HashMap (); + + // anno per gene + private String geneLine=""""; + private String geneID="""", gchr="""", gproteinAt="""", gmrnaAt="""", gproductAt=""""; + private String mrnaLine="""", mrnaID=""""; + private Vector exonVec = new Vector (); + private int cntUseGene=0, cntUseMRNA=0, cntUseExon=0, cntThisGeneMRNA=0; + + private boolean bSuccess=true; + private final int PRT = 10000; + + public static void main(String[] args) { + isToSymap=false; + new ConvertNCBI(args, defGapLen, null); + } + protected ConvertNCBI(String [] args, int gapLen, String prefix) { + if (args.length==0) { // command line + checkArgs(args); + return; + } + gapMinLen = gapLen; + prefixOnly = prefix; + + projDir = args[0]; + prt(""\n------ ConvertNCBI "" + projDir + "" ------""); + if (!checkInitFiles() || !bSuccess) return; + + //hexMap.put(""%09"", "" ""); // tab - break on this + hexMap.put(""%3D"", ""-""); // = but cannot have these in attr, so use dash + hexMap.put(""%0A"", "" ""); // newline + hexMap.put(""%25"", ""%""); // % + hexMap.put(""%2C"", "",""); // , + hexMap.put(""%3B"", "",""); // ; but cannot have these in attr, so use comma + hexMap.put(""%26"", ""&""); // & + + createLog(args); if (!bSuccess) return; + checkArgs(args); if (!bSuccess) return; + + rwFasta(); if (!bSuccess) return; + + rwAnno(); if (!bSuccess) return; + + printSummary(); + + prt(""""); + printSuggestions(); + prt(""------ Finish ConvertNCBI "" + projDir + "" ------""); + if (logFile!=null) logFile.close(); + } + private void printSuggestions() { + boolean isChr = true; + if (chr2id.size()>0) { + for (String c : chr2id.keySet()) { + if (!c.startsWith(chrPrefix)) { + isChr=false; + break; + } + } + if (isChr && !INCLUDESCAF) prt(""Suggestion: Set SyMAP project parameter 'Group prefix' to 'Chr'.""); + } + + if (cntOutSeq==0) prt(""Are these NCBI files? Should scaffolds be included? Should 'Prefix only' be set?""); + else + if (cntOutSeq>30) prt( ""Suggestion: There are "" + String.format(""%,d"",cntOutSeq) + "" sequences. "" + + ""Set SyMAP project parameter 'Minimum length' to reduce number loaded.""); + } + + /*************************************************************************** + * * Fasta file example: + * >NC_016131.2 Brachypodium distachyon strain Bd21 chromosome 1, Brachypodium_distachyon_v2.0, whole genome shotgun sequence + * >NW_014576703.1 Brachypodium distachyon strain Bd21 unplaced genomic scaffold, Brachypodium_distachyon_v2.0 super_11, whole genome shotgun sequence * + * NOTE: NCBI files are soft-masked, which is used to compute the gaps. + * If its then hard-masked (soft->N's), gaps and hard-masked appear the same + */ + private void rwFasta() { + try { + fhOut = new PrintWriter(new FileOutputStream(seqDir + outFaFile, false)); + fhOut.println(header); + ghOut = new PrintWriter(new FileOutputStream(annoDir + outGapFile, false)); + ghOut.println(header); + + char [] base = {'A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'}; + for (char b : base) cntBase.put(b, 0); + + // Process file + rwFasta(inFaFile); if (!bSuccess) return; + + fhOut.close(); ghOut.close(); + + // 1st part of summary + String xx = (VERBOSE) ? ""("" + star + "")"" : """"; + prt(String.format(""Sequences not output: %,d %s"", cntNoOutSeq, xx)); + prt(""Finish writing "" + seqDir + outFaFile + "" ""); + + prt(""""); + prt( String.format(""A %,11d a %,11d"", cntBase.get('A'), cntBase.get('a')) ); + prt( String.format(""T %,11d t %,11d"", cntBase.get('T'), cntBase.get('t')) ); + prt( String.format(""C %,11d c %,11d"", cntBase.get('C'), cntBase.get('c')) ); + prt( String.format(""G %,11d g %,11d"", cntBase.get('G'), cntBase.get('g')) ); + prt( String.format(""N %,11d n %,11d"", cntBase.get('N'), cntBase.get('n') )); + String other=""""; + for (char b : cntBase.keySet()) { + boolean found = false; + for (char x : base) if (x==b) {found=true; break;} + if (!found) other += String.format(""%c %,d "", b, cntBase.get(b)); + } + if (other!="""") prt(other); + cntBase.clear(); + prt(String.format(""Total %,d"", totalLen)); + + if (MASKED) prt(String.format(""Hard masked: %,d lower case changed to N"", cntMask)); + + prt(""""); + prt(String.format(""Gaps >= %,d: %,d"", gapMinLen, nGap)); + prt(""Finish writing "" + annoDir + outGapFile + "" ""); + } + catch (Exception e) {e.printStackTrace(); die(""rwFasta"");} + } + /******************************************************** + * >NC_010460.4 Sus scrofa isolate TJ Tabasco breed Duroc chromosome 18, Sscrofa11.1, whole genome shotgun sequence + * >NC_010461.5 Sus scrofa isolate TJ Tabasco breed Duroc chromosome X, Sscrofa11.1, whole genome shotgun sequence + * >NW_018084777.1 Sus scrofa isolate TJ Tabasco breed Duroc chromosome Y unlocalized genomic scaffold, + */ + private void rwFasta(String fastaFile) { + try { + prt(""\nProcessing "" + fastaFile); + BufferedReader fhIn = openGZIP(fastaFile); if (!bSuccess) return; + + String line=""""; + int len=0, lineN=0; + + String idcol1="""", prtName="""", seqType=""""; + boolean bPrt=false, isChr=false, isScaf=false, isMT=false; + boolean bMt=false, bPt=false; + int baseLoc=0, gapStart=0, gapCnt=1; + + while ((line = fhIn.readLine()) != null) { + lineN++; + if (line.startsWith(""!"") || line.startsWith(""#"") || line.trim().equals("""")) continue; + + if (line.startsWith("">"")) { // id line + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMT, len, idcol1, prtName); + len=0; + } + String line1 = line.substring(1).trim(); + String [] tok = line1.split(""\\s+""); + if (tok.length==0) { + die(""Header line is blank: line #"" + lineN); + return; + } + idcol1 = tok[0]; + + isChr=isScaf=isMT=false; + + if (idcol1.startsWith(""NC_"")) isChr=true; + else if (idcol1.startsWith(""NW_"") || idcol1.startsWith(""NT_"") ) isScaf=true; + + if (isChr) { + if (line.contains(""mitochondrion"") || line.contains(""mitochondrial"") + || line.contains(""plastid"") || line.contains(""chloroplast"")) isMT=true; // Mt/Pt, etc are NC_, but not 'chromosome' + } + if (isChr) cntChr++; + else if (isScaf) cntScaf++; + else if (isMT) cntMtPt++; + else cntUnk++; + + if (prefixOnly!=null) { + if (!idcol1.startsWith(prefixOnly)) { + cntNoOutSeq++; + continue; + } + } + + gapStart=1; gapCnt=0; baseLoc=0; + bPrt=false; + if (isChr && !isMT) { + nChr++; + seqType=chrType; + prtName = createChrPrtName(line); + id2chr.put(idcol1, prtName); + chr2id.put(prtName, idcol1); + cntChrGene.put(idcol1, 0); + + bPrt=true; + } + else if (isMT && INCLUDEMtPt) { + nChr++; + if (line.contains(""mitochondrion"") || line.contains(""mitochondrial"")) { + prtName= chrPrefix + ""Mt""; + if (!bMt) {bMt=true; nMt++;} + else { + cntNoOutSeq++; + if (VERBOSE) prt(""Ignore Mt: "" + line); + continue; + } + } + else { + prtName = chrPrefix + ""Pt""; + if (!bPt) {bPt=true; nMt++;} + else { + cntNoOutSeq++; + if (VERBOSE) prt(""Ignore Mt: "" + line); + continue; + } + } + id2chr.put(idcol1, prtName); + chr2id.put(prtName, idcol1); + cntChrGene.put(idcol1, 0); + + seqType=chrType; + bPrt=true; + } + else if (isScaf && INCLUDESCAF) { + nScaf++; + prtName = scafPrefix + padNum(nScaf+""""); + id2scaf.put(idcol1, prtName); + cntScafGene.put(idcol1, 0); + + seqType=scafType; + bPrt=true; + } + else { + if (isScaf) {prtName=scafPrefix;} + else if (isMT) {prtName=""Mt/Pt"";} + else {prtName=unkPrefix;} + + if (prefixOnly!=null) {// use chr, don't know what it is + nUnk++; + prtName = unkPrefix + padNum(nUnk+""""); + id2chr.put(idcol1, prtName); + cntChrGene.put(idcol1, 0); + seqType=unkType; + bPrt=true; + } + } + if (bPrt) { + fhOut.println("">"" + prtName + "" "" + idcol1 + "" "" + seqType); + cntOutSeq++; + } + else cntNoOutSeq++; + } // finish header line + ////////////////////////////////////////////////////////////////////// + else { // sequence line + String aline = line.trim(); + if (bPrt) { + char [] bases = aline.toCharArray(); + + //eval for gaps, mask and count bases + for (int i =0 ; i0) { // gaps + if (gapCnt>gapMinLen) { + nGap++; + String x = createGap(prtName, gapStart, gapCnt); + ghOut.println(x); + } + gapStart=0; gapCnt=1; + } + if (MASKED) { + if (b=='a' || b=='c' || b=='t' || b=='g' || b=='n') { + bases[i]='N'; + cntMask++; + } + } + } + if (MASKED) aline = new String(bases); + } + + len += aline.length(); + if (bPrt) fhOut.println(aline); + } // finish seq line + } + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMT, len, idcol1, prtName); + } + System.err.print("" \r""); + fhIn.close(); + } + catch (Exception e) {die(e, ""rwFasta: "" + fastaFile);} + } + // >NC_015438.3 Solanum lycopersicum cultivar Heinz 1706 chromosome 12, SL3.0, whole genome""; + // >NC_003279.8 Caenorhabditis elegans chromosome III + // >NC_003070.9 Arabidopsis thaliana chromosome X sequence + // >NC_027748.1 Brassica oleracea TO1000 chromosome C1, BOL, whole genome shotgun sequence + private String createChrPrtName(String line) { + try { + String name=null; + String [] words = line.split(""\\s+""); + for (int i=0; i1000000) System.out.print(msg2 + ""\r""); + } + else { + unkLen += len; + if (bPrt || VERBOSE) { + if (cntUnk<=traceNum) prt(msg); + else if (cntUnk==traceNum+1) prt(""Suppressing further unknown logs""); + else System.out.print(msg2 + ""\r""); + } + else if (len>1000000) System.out.print(msg2 + ""\r""); + } + } + /*************************************************************************** + * XXX GFF file example: + * NC_016131.2 Gnomon gene 18481 21742 . + . ID=gene3;Dbxref=GeneID:100827252;Name=LOC100827252;gbkey=Gene;gene=LOC100827252;gene_biotype=protein_coding + NC_016131.2 Gnomon mRNA 18481 21742 . + . ID=rna2;Parent=gene3;Dbxref=GeneID:100827252,Genbank:XM_003563157.3;Name=XM_003563157.3;gbkey=mRNA;gene=LOC100827252;model_evidence=Supporting evidence includes similarity to: 3 Proteins%2C and 78%25 coverage of the annotated genomic feature by RNAseq alignments;product=angio-associated migratory cell protein-like;transcript_id=XM_003563157.3 + NC_016131.2 Gnomon exon 18481 18628 . + . ID=id15;Parent=rna2;Dbxref=GeneID:100827252,Genbank:XM_003563157.3;gbkey=mRNA;gene=LOC100827252;product=angio-associated migratory cell protein-like;transcript_id=XM_003563157.3 + */ + + private void rwAnno() { + try { + if (inGffFile==null) return; + prt(""""); + prt(""Processing "" + inGffFile); + + int cntReadGene=0, cntReadMRNA=0, cntReadExon=0; + BufferedReader fhIn = openGZIP(inGffFile); if (!bSuccess) return; + PrintWriter fhOutGff = new PrintWriter(new FileOutputStream(annoDir + outGffFile, false)); + fhOutGff.println(header); + + String line=""""; + int skipLine=0; + + while ((line = fhIn.readLine()) != null) { + line = line.trim(); + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().length()==0) continue; + + String [] tok = line.split(""\\t""); + if (tok.length!=9) { + skipLine++; + if (skipLine<10) prt(""Bad line: "" + line); + else die(""too many errors""); + continue; + } + + // Count everything here for summary + String type = tok[2].trim(); // gene, mRNA, exon... + if (!allTypeCnt.containsKey(type)) allTypeCnt.put(type,1); + else allTypeCnt.put(type, allTypeCnt.get(type)+1); + + if (type.equals(geneType)) { + rwAnnoOut(fhOutGff); // Write last record + rwAnnoGene(tok, line); // Start new + cntReadGene++; cntThisGeneMRNA++; + if (cntReadGene%PRT==0) System.err.print("" Process "" + cntReadGene + "" genes...\r""); + } + else if (type.equals(mrnaType)) { + rwAnnoMRNA(tok, line); + cntReadMRNA++; + } + else if (type.equals(cdsType)) { + rwAnnoCDS(tok, line); + } + else if (type.equals(exonType)) { + rwAnnoExon(tok, line); + cntReadExon++; + } + } + fhIn.close(); fhOutGff.close(); + prt(String.format("" Use Gene %,d from %,d "", cntUseGene, cntReadGene)); + prt(String.format("" Use mRNA %,d from %,d "", cntUseMRNA, cntReadMRNA)); + prt(String.format("" Use Exon %,d from %,d "", cntUseExon, cntReadExon)); + prt(""Finish writing "" + annoDir + outGffFile + "" ""); + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + + private void rwAnnoGene(String [] tok, String line) { + try { + // counts for gene + String [] typeAttrs = tok[8].trim().split("";""); + String biotype = getVal(biotypeAttrKey, typeAttrs); + if (!allGeneBiotypeCnt.containsKey(biotype)) allGeneBiotypeCnt.put(biotype,1); + else allGeneBiotypeCnt.put(biotype, allGeneBiotypeCnt.get(biotype)+1); + + String src = tok[1].trim(); // RefSeq, Gnomon.. + if (src.contains(""%2C"")) src = src.replace(""%2C"", "",""); + + if (!allGeneSrcCnt.containsKey(src)) allGeneSrcCnt.put(src,1); + else allGeneSrcCnt.put(src, allGeneSrcCnt.get(src)+1); + + if (!biotype.equals(biotypeAttr)) return; // protein-coding + + String idcol1 = tok[0]; // chromosome, scaffold, linkage group... + if (id2chr.containsKey(idcol1)) { + cntChrGeneAll++; + gchr = id2chr.get(idcol1); + cntChrGene.put(idcol1, cntChrGene.get(idcol1)+1); + } + else if (id2scaf.containsKey(idcol1)) { + cntScafGeneAll++; + gchr = id2scaf.get(idcol1); + cntScafGene.put(idcol1, cntScafGene.get(idcol1)+1); + } + else { + cntGeneNotOnSeq++; + return; + } + //////////// + geneID = getVal(idAttrKey, typeAttrs); + geneLine = line; + cntUseGene++; + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + // mRNA is not loaded into SyMAP, but needed for exon parentID + private void rwAnnoMRNA(String [] tok, String line) { + try { + if (!mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + if (!geneID.equals(pid)) return; + + //////////////////////// + mrnaID = getVal(idAttrKey, attrs); + + String mid = mrnaID.replace(RMRNA,""""); + gmrnaAt = MRNAID + mid; + gproductAt = DESC + getVal(productAttrKey, attrs); + + String idStr = idAttrKey + ""="" + mrnaID.replace(RMRNA,""""); + String parStr = parentAttrKey + ""="" + geneID.replace(RMGENE,""""); + String newAttrs = idStr + "";"" + parStr + "";"" + gproductAt; + mrnaLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + + tok[4] + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + + cntUseMRNA++; + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + private void rwAnnoCDS(String [] tok, String line) { + try { + if (!ATTRPROT || mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (mrnaID.equals(pid)) { + gproteinAt = "";"" + PROTEINID + getVal(cdsProteinAttrKey, attrs); + } + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + /** Write genes and exons to file**/ + private void rwAnnoExon(String [] tok, String line) { + try { + if (mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (!mrnaID.equals(pid)) return; + + ////////////// + String idStr = idAttrKey + ""="" + getVal(idAttrKey, attrs); // create shortened attribute list + String parStr = parentAttrKey + ""="" + mrnaID.replace(RMRNA,""""); + String geneStr = exonGeneAttrKey + ""="" + getVal(exonGeneAttrKey, attrs); + String newAttrs = idStr + "";"" + parStr + "";"" + geneStr; + String nLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + exonVec.add(nLine); + cntUseExon++; + } + catch (Exception e) {die(e, ""rwAnnoExon"");} + } + private void rwAnnoOut( PrintWriter fhOutGff) { + try { + if (geneID.trim().equals("""")) return; + if (mrnaID.trim().equals("""")) return; + + String [] tok = geneLine.split(""\\t""); + if (tok.length!=9) die(""Gene: "" + tok.length + "" "" + geneLine); + + if (geneID.startsWith(RMGENE)) geneID = geneID.replace(RMGENE,""""); + String idAt = idAttrKey + ""="" + geneID + "";""; + + String [] attrs = tok[8].split("";""); + String val = getVal(nameAttrKey, attrs); + String nameAt = (!geneID.contains(val)) ? (nameAttrKey + ""="" + val + "";"") : """"; // CHANGE here to alter what attributes are saved + + String desc = getVal(descAttrKey, attrs).trim(); + if (!desc.equals("""")) gproductAt = DESC + desc; + + gmrnaAt += "" ("" + cntThisGeneMRNA + "");""; + + String allAttrs = idAt + nameAt + gmrnaAt + gproductAt + gproteinAt; + + String line = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + allAttrs; + + if (line.contains(""%"")) { + for (String hex : hexMap.keySet()) { + if (line.contains(hex)) line = line.replace(hex, hexMap.get(hex)); + } + } + fhOutGff.println(""###\n"" + line); + + fhOutGff.println(mrnaLine); + + for (String eline : exonVec) fhOutGff.println(eline); + + cntThisGeneMRNA=0; + geneID=geneLine=gchr=gproteinAt=gmrnaAt=gproductAt=mrnaID=mrnaLine=""""; + exonVec.clear(); + } + catch (Exception e) {die(e, ""rwAnnoOut"");} + } + + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return x[1]; + } + return """"; + } + + /***********************************************************************/ + private void printSummary() { + prt("" ""); + if (VERBOSE) { + prt("">>Sequence ""); + if (cntChr>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntChr, nChr, ""Chromosomes"", chrLen)); + } + if (cntMtPt>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntMtPt, nMt, ""Mt/Pt"", mtptLen)); + } + if (cntScaf>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d (%,d < %,dbp)"", + cntScaf,nScaf, ""Scaffolds"", scafLen, cntScafSmall, traceScafMaxLen)); + } + if (cntUnk>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntUnk, nUnk, ""Unknown"", unkLen)); + } + + if (inGffFile==null) return; + + ////////////////// anno //////////////// + prt("" ""); + + prt("">>All Types (col 3) ("" + plus + "" are processed keywords)""); + for (String key : allTypeCnt.keySet()) { + boolean bKey = ATTRPROT && key.equals(cdsType); + String x = (key.equals(geneType) || key.equals(mrnaType) || key.equals(exonType)) || bKey ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allTypeCnt.get(key), x)); + } + + prt("">>All Gene Source (col 2)""); + for (String key :allGeneSrcCnt.keySet()) { + prt(String.format("" %-22s %,8d"", key, allGeneSrcCnt.get(key))); + } + prt("">>All gene_biotype= (col 8) ""); + for (String key : allGeneBiotypeCnt.keySet()) { + String x = (key.equals(biotypeAttr)) ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allGeneBiotypeCnt.get(key), x)); + } + } + prt(String.format("">>Chromosome gene count %,d "", cntChrGeneAll)); + for (String prt : chr2id.keySet()) { + String id = chr2id.get(prt); + prt(String.format("" %-10s %-20s %,8d"", prt, id, cntChrGene.get(id))); + } + if (INCLUDESCAF) { + int cntOne=0; + prt(String.format("">>Scaffold gene count %,d (list scaffolds with #genes>%d) "", cntScafGeneAll, traceNumGenes)); + for (String id : cntScafGene.keySet()) { + if (cntScafGene.get(id)>traceNumGenes) + prt(String.format("" %-10s %-20s %,8d"", id2scaf.get(id), id, cntScafGene.get(id))); + else cntOne++; + } + prt(String.format("" Scaffolds with <=%d gene (not listed) %,8d"", traceNumGenes, cntOne)); + prt(String.format("" Genes not included %,8d"", cntGeneNotOnSeq)); + } + else prt(String.format("" %s %,8d"", ""Genes not on Chromosome"", cntGeneNotOnSeq)); + } + + /************************************************************************** + * Find .fna and .gff in top project directory or in projDir/ncbi_dataset/data/ + */ + private boolean checkInitFiles() { + try { + if (projDir==null || projDir.trim().equals("""")) { + die(""No project directory""); + return false; + } + File[] files; + String dsDirName=null; + + File dir = new File(projDir); + if (!dir.isDirectory()) + return die(projDir + "" is not a directory.""); + + // for check projDir/ncbi_dataset/data/ + files = dir.listFiles(); + boolean isDS=false; + for (File f : files) { + if (f.isDirectory()) { + if (f.getName().contentEquals(ncbi_dataset)) { + isDS = true; + break; + } + } + } + if (isDS) { + if (!projDir.endsWith(""/"")) projDir += ""/""; + dsDirName = projDir + ncbi_dataset + ncbi_data; + + dir = new File(dsDirName); + if (!dir.isDirectory()) + return die(""ncbi_dataset directory is incorrect "" + dsDirName); + + files = dir.listFiles(); + for (File f : files) { + if (f.isDirectory()) { + subDir = f.getName(); + break; + } + } + if (subDir==null) return die(dsDirName + "" missing sub-directory""); + + dsDirName += ""/"" + subDir; + } + else { + dsDirName = projDir; + } + + // find .fna and .gff files in dsDirName + File dsDir = new File(dsDirName); + if (!dsDir.isDirectory()) + return die(dsDir + "" is not a directory.""); + + files = dsDir.listFiles(); + for (File f : files) { + if (!f.isFile() || f.isHidden()) continue; + + String fname = f.getName(); + + if (fname.endsWith(faSuffix + "".gz"") || fname.endsWith(faSuffix)) { + if (inFaFile!=null) { + prt(""Multiple fasta files - using "" + inFaFile); + break; + } + inFaFile = dsDirName + ""/"" + fname; + } + else if (fname.endsWith(gffSuffix + "".gz"") || fname.endsWith(gffSuffix)) { + if (inGffFile!=null) { + prt(""Multiple fasta files - using "" + inFaFile); + break; + } + inGffFile= dsDirName + ""/"" +fname; + } + } + + if (inFaFile == null) return die(""Project directory "" + projDir + "": no file ending with "" + faSuffix + "" or ""+ faSuffix + "".gz (i.e. Ensembl files)""); + if (inGffFile == null) prt(""Project directory "" + projDir + "": no file ending with "" + gffSuffix + "" or "" + gffSuffix + "".gz""); + + // Create sequence and annotation directories + if (!projDir.endsWith(""/"")) projDir += ""/""; + seqDir = projDir + seqDir; + checkDir(true, seqDir); if (!bSuccess) return false; + + annoDir = projDir + annoDir; + checkDir(false, annoDir); if (!bSuccess) return false; + + return true; + } + catch (Exception e) { return die(e, ""Checking "" + projDir); } + } + /*****************************************************************/ + private void createLog(String [] args) { + if (args.length==0) return; + logFileName = args[0] + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {die(""Cannot open "" + logFileName); logFile=null;} + } + private boolean checkDir(boolean isSeq, String dir) { + File nDir = new File(dir); + if (nDir.exists()) { + String x = (isSeq) ? "" .fna and .fa "" : "" .gff and .gff3""; + prt(dir + "" exists - remove existing "" + x + "" files""); + deleteFilesInDir(isSeq, nDir); + return true; + } + else { + if (!nDir.mkdir()) + return die(""*** Failed to create directory '"" + nDir.getAbsolutePath() + ""'.""); + } + return true; + } + private void deleteFilesInDir(boolean isSeq, File dir) { + if (!dir.isDirectory()) return; + + String[] files = dir.list(); + + if (files==null) return; + + for (String fn : files) { + if (isSeq) { + if (fn.endsWith("".fna"") || fn.endsWith("".fa"")) { + new File(dir, fn).delete(); + } + } + else { + if (fn.endsWith("".gff"") || fn.endsWith("".gff3"")) { + new File(dir, fn).delete(); + } + } + } + } + private BufferedReader openGZIP(String file) { + try { + if (!file.endsWith("".gz"")) { + File f = new File (file); + if (f.exists()) return new BufferedReader ( new FileReader (f)); + else die(""Cannot open file "" + file); + } + else if (file.endsWith("".gz"")) { + FileInputStream fin = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fin); + InputStreamReader xover = new InputStreamReader(gzis); + return new BufferedReader(xover); + } + else die(""Do not recognize file suffix: "" + file); + } + catch (Exception e) {die(e, ""Cannot open file "" + file);} + return null; + } + /*******************************************************/ + private void checkArgs(String [] args) { + if (args.length==0 || args[0].equals(""-h"") || args[0].equals(""-help"") || args[0].equals(""help"")) { // for stand alone + prt(""\nConvertNCBI [options] ""); + prt("" the project directory must contain the FASTA file and the GFF is optional: "" + + ""\n FASTA file ending with .fna or .fna.gz"" + + ""\n GFF file ending with .gff or .gff.gz"" + + ""\n Alternatively, the directory can contain the ncbi_dataset directory."" + + ""\nOptions:"" + + ""\n-m assuming a soft-masked genome file, convert it to hard-masked."" + + ""\n-s include any sequence with NT_ or NW_ prefix'."" + + ""\n-t include Mt and Pt chromosomes."" + + ""\n-p include the protein name (1st CDS) in the attribute field."" + + ""\n-v write extra information."" + + ""\n\nSee https://csoderlund.github.io/SyMAP/input for details.""); + System.exit(0); + } + + if (args.length>1) { + for (int i=1; i< args.length; i++) + if (args[i].equals(""-s"")) { + INCLUDESCAF=true; + chrPrefix = chrPrefix2; + } + else if (args[i].equals(""-t"")) INCLUDEMtPt=true; + else if (args[i].equals(""-v"")) VERBOSE=true; + else if (args[i].equals(""-m"")) MASKED=true; + else if (args[i].equals(""-p"")) ATTRPROT=true; + } + prt(""Parameters:""); + prt("" Project directory: "" + projDir); + + if (gapMinLen!=defGapLen) prt("" Gap minimum size: "" + gapMinLen); // set in main + if (prefixOnly!=null) prt("" Prefix Only: "" + prefixOnly); // set in main + + if (INCLUDESCAF) { + prt("" Include scaffold sequences ('NT_' or 'NW_' prefix)""); + prt("" Uses prefixes Chr '"" + chrPrefix2 + ""' and Scaffold '"" + scafPrefix + ""'""); + } + if (INCLUDEMtPt) prt("" Include Mt and Pt chromosomes""); + if (MASKED) prt("" Hard mask sequence""); + if (ATTRPROT) prt("" Include protein-id in attributes""); + if (VERBOSE) {traceNum=20; prt("" Verbose"");} + } + private boolean die(Exception e, String msg) { + System.err.println(""Fatal error -- "" + msg); + e.printStackTrace(); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private boolean die(String msg) { + System.err.println(""Fatal error -- "" + msg); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/ToFrame.java",".java","13929","419","package toSymap; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.io.File; +import java.util.Vector; + +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JLabel; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import backend.Constants; +import util.ErrorReport; +import util.Jcomp; +import util.Jhtml; +import util.Popup; + +/****************************************************** + * Interface to run convertNCBI, convertEnsembl, and getLengths + */ +public class ToFrame extends JDialog implements WindowListener { + private static final long serialVersionUID = 1L; + private final String rootDir = Constants.seqDataDir; // data/seq/ + private final String convertDir = Constants.seqSeqDataDir; //sequence + + protected final int defGapLen = 30000; + protected final int defSeqLen = 10000; + + public ToFrame() { + addWindowListener(this); + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + setTitle(""Input files for SyMAP""); + parent = this; + + createMainPanel(); + add(mainPanel); + + pack(); + setResizable(false); + setLocationRelativeTo(null); + setVisible(true); + } + private void createMainPanel() { + mainPanel = Jcomp.createPagePanel(); + + createFileSelect(); mainPanel.add(new JSeparator()); + + createConvert(); mainPanel.add(new JSeparator()); + + createButtonPanel(); + + setDisable(); + } + private void createFileSelect() { + JPanel panel = Jcomp.createPagePanel(); + + JPanel trow = Jcomp.createRowPanel(); + JLabel lbl = Jcomp.createLabel(""Project directory""); + trow.add(lbl); + + txtDir = Jcomp.createTextField(rootDir, 16); + trow.add(txtDir); + + JButton btnGetFile = Jcomp.createButton(""..."", ""Select the project directory""); + btnGetFile.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + String fname = fileChooser(); + if (fname!=null && fname!="""") { + txtDir.setText(fname); + setDisable(); + radDisable(); + } + else setDisable(); + } + }); + trow.add(btnGetFile); + + panel.add(trow); panel.add(Box.createHorizontalStrut(10)); // linux crowds it w/o this + panel.add(Box.createVerticalStrut(5)); + + JPanel crow = Jcomp.createRowPanel(); + btnSummary = Jcomp.createBoldButton(""Summarize"", + ""Print/log information about FASTA and GFF files""); + btnSummary.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { // XXX + String dir = txtDir.getText().trim(); + if (dir.equals(rootDir) || dir.isEmpty()) { + Popup.showInfoMessage(""Project"", ""Please select a project directory""); + setDisable(); + return; + } + boolean b = chkSumConvert.isSelected() && chkSumConvert.isEnabled(); + new Summary(dir).runCheck(chkSumVerbose.isSelected(), b); + } + }); + crow.add(btnSummary); crow.add(Box.createHorizontalStrut(10)); + + chkSumVerbose = Jcomp.createCheckBox(""Verbose"", ""Write extra information to the terminal/log"", false); + crow.add(chkSumVerbose); crow.add(Box.createHorizontalStrut(10)); + + chkSumConvert = Jcomp.createCheckBox(""Converted"", ""After Convert; use the /sequence and /annotation files"", false); + crow.add(chkSumConvert); crow.add(Box.createHorizontalStrut(10)); + + panel.add(crow); + + mainPanel.add(panel); + } + private void createConvert() { + JPanel panel = Jcomp.createPagePanel(); + + createConvertOptions(panel); panel.add(Box.createVerticalStrut(20)); + + JPanel row = Jcomp.createRowPanel(); + btnExec = Jcomp.createBoldButton(""Convert"", ""Covert FASTA and GFF to SyMAP input""); + btnExec.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + convert(); + } + }); + chkVerbose = Jcomp.createCheckBox(""Verbose"", ""Write extra information to the terminal/log"", false); + + row.add(btnExec); row.add(Box.createHorizontalStrut(5)); + lblExec = new JLabel(""NCBI files""); + row.add(lblExec); + row.add(Box.createHorizontalStrut(30)); + row.add(chkVerbose); + + panel.add(row); + mainPanel.add(panel); + } + private void createConvertOptions(JPanel cpanel) { + radNCBI = Jcomp.createRadio(""NCBI"", ""When Convert is selected, the NCBI conversion will be run.""); + radNCBI.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + radDisable(); + } + }); + radEns = Jcomp.createRadio(""Ensembl"", ""When Convert is selected, the Ensembl conversion will be run.""); + radEns.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + radDisable(); + } + }); + ButtonGroup grp = new ButtonGroup(); + grp.add(radNCBI); + grp.add(radEns); + radNCBI.setSelected(true); + + int lj_width = 92; + + // ncbi + chkNmask = Jcomp.createCheckBox(""Hard mask"", ""Hard mask the sequence when creating the new sequence file."", false); + + JPanel rowN = Jcomp.createRowPanel(); + rowN.add(radNCBI); + if (lj_width > radNCBI.getPreferredSize().width) + rowN.add(Box.createHorizontalStrut(lj_width-radNCBI.getPreferredSize().width)); + rowN.add(chkNmask); + + // ensembl + chkEonlyNum = Jcomp.createCheckBox(""Only #, X, Y, I"", ""Only output sequences identified with a number, X, Y, or Roman numerals"", false); + + JPanel rowE = Jcomp.createRowPanel(); + rowE.add(radEns); + if (lj_width > radEns.getPreferredSize().width) + rowE.add(Box.createHorizontalStrut(lj_width-radEns.getPreferredSize().width)); + rowE.add(chkEonlyNum); + + // 2 shared + JPanel row3 = Jcomp.createRowPanel(); + chkScaf = Jcomp.createCheckBox(""Scaffolds"", ""Include scaffolds in the output"", false); + chkMtPt = Jcomp.createCheckBox(""Mt/Pt"", ""Include Mt/Pt in the output"", false); + + chkOnlyPrefix = Jcomp.createCheckBox(""Only prefix"", ""Only output sequences with this prefix"", false); + chkOnlyPrefix.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + boolean b = chkOnlyPrefix.isSelected(); + txtPrefix.setEnabled(b); + } + }); + txtPrefix = Jcomp.createTextField("""", 6); + txtPrefix.setEnabled(false); + row3.add(chkScaf); row3.add(Box.createHorizontalStrut(2)); + row3.add(chkMtPt); row3.add(Box.createHorizontalStrut(25)); + row3.add(chkOnlyPrefix);row3.add(Box.createHorizontalStrut(1)); + row3.add(txtPrefix); + + // 4 + JPanel row4 = Jcomp.createRowPanel(); row4.add(Box.createHorizontalStrut(7)); + lblGap = Jcomp.createLabel(""Gap size >="", ""Consecutive n's of this length will be identified in the gap.gff file.""); + txtGap = Jcomp.createTextField(defGapLen+"""", 6); + chkNp = Jcomp.createCheckBox(""Protein-id"", ""New gene attribute of: proteinID = 1st CDS protein-id of 1st mRNA"", false); + + row4.add(lblGap); row4.add(Box.createHorizontalStrut(2)); + row4.add(txtGap); row4.add(Box.createHorizontalStrut(15)); + row4.add(chkNp); + + cpanel.add(rowN); cpanel.add(Box.createVerticalStrut(5)); + cpanel.add(rowE); cpanel.add(Box.createVerticalStrut(10)); + cpanel.add(row3); cpanel.add(Box.createVerticalStrut(5)); + cpanel.add(row4); cpanel.add(Box.createVerticalStrut(5)); + } + + private void createButtonPanel() { + JPanel panel = Jcomp.createPagePanel(); + + JPanel row = Jcomp.createRowPanel(); + + btnLen = Jcomp.createBoldButton(""Lengths"", ""Output to terminal the sequence lengths and summary""); + btnLen.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { // XXX + String dir = txtDir.getText().trim(); + if (dir.equals(rootDir) || dir.isEmpty()) { + Popup.showInfoMessage(""Project"", ""Please select a project directory""); + return; + } + new Lengths(dir); + } + }); + row.add(btnLen); row.add(Box.createHorizontalStrut(10)); + + btnSplit = Jcomp.createBoldButton(""Split"", ""Split converted files by chromosome""); + btnSplit.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { // XXX + String dir = txtDir.getText().trim(); + if (dir.equals(rootDir) || dir.isEmpty()) { + Popup.showInfoMessage(""Project"", ""Please select a project directory""); + return; + } + new Split(dir); + } + }); + row.add(btnSplit); row.add(Box.createHorizontalStrut(80)); + + btnExit = Jcomp.createButton(""Exit"", ""Exit xToSyMAP"");; + btnExit.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setVisible(false); + System.exit(0); + } + }); + row.add(btnExit); row.add(Box.createHorizontalStrut(30)); + + JButton help1 = Jcomp.createBorderIconButton(""/images/info.png"", ""Quick Help""); // not used yet + help1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + quickHelp(); + } + }); + + JButton btnHelp = Jhtml.createHelpIconSysSm(Jhtml.CONVERT_GUIDE_URL, """"); + row.add(btnHelp); row.add(Box.createHorizontalStrut(10)); + + panel.add(row); + panel.add(Box.createVerticalStrut(10)); + + mainPanel.add(panel); + } + /*******************************************************/ + private void convert() { + String dir = txtDir.getText().trim(); + if (dir.equals(rootDir) || dir.isEmpty()) { + Popup.showInfoMessage(""Project"", ""Please select a project directory""); + return; + } + Vector args = new Vector (); + args.add(dir); + + String g = txtGap.getText().trim(); + int gapLen=defGapLen; + try { + if (g.contains("","")) g = g.replace("","", """"); + gapLen = Integer.parseInt(g); + if (gapLen<100) { + Popup.showInfoMessage(""Gap size"", ""Gap size must at least be 100, i.e. "" + g +"" is too small. Using 100.""); + g = ""100""; + gapLen=100; + return; + } + } + catch (Exception e) { + Popup.showInfoMessage(""Gap size"", ""Gap size must be an integer.""); + return; + } + + if (chkOnlyPrefix.isSelected() && txtPrefix.getText().trim().isEmpty()) { + Popup.showInfoMessage(""Only prefix"", ""When 'Only prefix' is checked, a prefix must be entered.""); + return; + } + String prefix = (chkOnlyPrefix.isSelected()) ? txtPrefix.getText().trim() : null; + + args.add(g); + if (chkVerbose.isSelected()) args.add(""-v""); + if (chkScaf.isSelected()) args.add(""-s""); + if (chkMtPt.isSelected()) args.add(""-t""); + if (chkNp.isSelected()) args.add(""-p""); + + if (radNCBI.isSelected()) { + if (chkNmask.isSelected()) args.add(""-m""); + String [] s = args.toArray(new String [args.size()]); + + new ConvertNCBI(s, gapLen, prefix); + } + else { + if (chkEonlyNum.isSelected() && prefix!=null) { + Popup.showInfoMessage(""Only options"", ""Select either 'Only #, X, Y, I' or 'Only prefix', not both.""); + return; + } + String [] s = args.toArray(new String [args.size()]); + + new ConvertEnsembl(s, gapLen, prefix, chkEonlyNum.isSelected()); + } + setDisable(); + } + + /********************************************************/ + + private String fileChooser() { + try { + final JFileChooser fc = new JFileChooser(); + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fc.setCurrentDirectory(new File(rootDir)); + if(fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { + String filePath = fc.getSelectedFile().getCanonicalPath(); + String cur = System.getProperty(""user.dir""); + + if(filePath.contains(cur)) filePath = filePath.replace(cur, "".""); + + return filePath; + } + } + catch (Exception e) {ErrorReport.print(e, ""Problems getting file"");} + return null; + } + + public void windowClosed(WindowEvent arg0) {System.exit(0);} + public void windowActivated(WindowEvent arg0) {} + public void windowClosing(WindowEvent arg0) {} + public void windowDeactivated(WindowEvent arg0) {} + public void windowDeiconified(WindowEvent arg0) {} + public void windowIconified(WindowEvent arg0) {} + public void windowOpened(WindowEvent arg0) {} + + /***************************************************/ + private void quickHelp() { + String msg=""""; + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + + private void radDisable() { + boolean bNCBI = radNCBI.isSelected(); + + if (bNCBI) lblExec.setText(""NCBI files""); + else lblExec.setText(""Ensembl files""); + + chkNmask.setEnabled(bNCBI); + chkEonlyNum.setEnabled(!bNCBI); + repaint(); + } + private void setDisable() { + String fname = txtDir.getText().trim(); + boolean b = !(fname.equals(rootDir)) ; + btnSummary.setEnabled(b); chkSumVerbose.setEnabled(b); chkSumConvert.setEnabled(b); + + radNCBI.setEnabled(b); chkNp.setEnabled(b); chkNmask.setEnabled(b); + radEns.setEnabled(b); chkEonlyNum.setEnabled(b); + + chkScaf.setEnabled(b); chkMtPt.setEnabled(b); + chkVerbose.setEnabled(b); chkOnlyPrefix.setEnabled(b); + lblGap.setEnabled(b); txtGap.setEnabled(b); + + lblExec.setEnabled(b); btnExec.setEnabled(b); btnLen.setEnabled(b); btnSplit.setEnabled(b); + + if (b) { // these need /sequence directory + b = new File(fname + convertDir).exists(); + chkSumConvert.setEnabled(b); if (!b) chkSumConvert.setSelected(false); + btnLen.setEnabled(b); + btnSplit.setEnabled(b); + } + repaint(); + } + /*************************************************/ + private JPanel mainPanel = null; + private JTextField txtDir = null; + private JButton btnSummary = null; + private JCheckBox chkSumVerbose = null, chkSumConvert = null; + + private JRadioButton radNCBI = null; + private JCheckBox chkNmask = null, chkNp = null; + + private JRadioButton radEns = null; + private JCheckBox chkEonlyNum = null; + + // shared + private JCheckBox chkScaf = null, chkMtPt = null; + private JCheckBox chkOnlyPrefix = null; + private JLabel lblGap = null; + private JTextField txtGap = null, txtPrefix = null; + private JCheckBox chkVerbose = null; + + private JLabel lblExec = null ; + private JButton btnExec = null; + + private JButton btnLen = null, btnSplit = null, btnExit = null; + + private ToFrame parent; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/ConvertEnsembl.java",".java","32848","944","package toSymap; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Vector; +import java.util.zip.GZIPInputStream; + +/************************************************************* + * ConvertEnsembl: Ensembl genome files formatted for SyMAP + * See https://csoderlund.github.io/SyMAP/input/ensembl.html + * + * Called from toSymap, but can be used stand-alone. + * + * This assumes input of, e.g: + * 1. ftp://ftp.ensemblgenomes.org/pub/plants/release-45/fasta//dna/.dna_sm.toplevel.fa.gz + * Note: either hard-masked (rm) where repeats are replaced with Ns, or soft-masked (sm) where repeats are in lower-case text. + * 2. ftp://ftp.ensemblgenomes.org/pub/plants/release-45/gff3//.chr.gff3.gz + * + * Note: I am no expert on Ensembl GFF format, so I cannot guarantee this is 100% correct mapping for all input. + * Your sequences/annotations may have other variations. + * Hence, you may want to edit this to customize it for your needs -- its simply written so easy to modify. + * See https://csoderlund.github.io/SyMAP/input/ensembl.html#edit + */ + +public class ConvertEnsembl { + static private boolean isToSymap=true; // set to false in main if standalone + static private int defGapLen=30000; + + private final String header = ""### Written by SyMAP ConvertEnsembl""; // Split expects this to be 1st line + private String logFileName = ""/xConvertENS.log""; + private final String star = ""*"", plus=""+""; + private final String source = ""[Source""; // remove this from description + + private final int PRT = 10000; + private final int scafMaxLen=10000; // counted if less than this + private int traceNum=5; // if verbose, change to 20 + private final int traceNumGenes=3; // Only print sequence if at least this many genes + + //input - project directory + private final String faSuffix = "".fa""; + private final String gffSuffix = "".gff3""; + + //output - the projDir gets appended to the front + private String seqDir = ""sequence""; // Default sequence directory for symap + private String annoDir = ""annotation""; // Default sequence directory for symap + + private final String outFaFile = ""/genomic.fna""; // Split expects this name + private final String outGffFile = ""/anno.gff""; // Split expects this name + private final String outGapFile = ""/gap.gff""; + + // args (can be set from command line) + private boolean VERBOSE = false; + private boolean INCLUDESCAF = false; + private boolean INCLUDEMtPt = false; + private boolean ATTRPROT = false; + + // args (if running standalone, change in main) + private int gapMinLen=defGapLen; // Print to gap.gff if #N's is greater than this + private String prefixOnly=null; // e.g. NC + private boolean bNumOnly=false; // Only number, X, Y or roman numeral + + private String chrPrefix=""Chr"", chrPrefix2=""C"", chrType=""chromosome""; // these values are checked in Split + private String scafPrefix=""s"", scafType=""scaffold""; + private String unkPrefix=""Unk"", unkType=""unknown""; + + // types + private final String geneType = ""gene""; + private final String mrnaType = ""mRNA""; + private final String exonType = ""exon""; + private final String cdsType = ""CDS""; + + // attribute keywords + private final String idAttrKey = ""ID""; // Gene and mRNA + private final String nameAttrKey = ""Name""; // All + private final String descAttrKey = ""description""; // Gene + private final String biotypeAttrKey = ""biotype""; // Gene + private final String biotypeAttr = ""protein_coding""; // Gene + private final String parentAttrKey = ""Parent""; // mRNA and Exon + private final String cdsProteinAttrKey = ""protein_id""; + + private final String PROTEINID = ""proteinID=""; // new keywords for gene attributes + private final String MRNAID = ""rnaID=""; // ditto + private final String DESC = ""desc=""; // ditto + private final String RMGENE = ""gene:""; + private final String RMTRAN = ""transcript:""; + + // input + private String projDir = null; // command line input + // Ensembl allows individual chromosomes to be downloaded, hence, the vector + private Vector inFaFileVec = new Vector (); // must be in projDir, end with fastaSuffix + private Vector inGffFileVec = new Vector (); // must be in projDir, end with annoSuffix + + // All chromosome and scaffold names are mapped to ChrN and ScafN + private TreeMap cntChrGene = new TreeMap (); + private TreeMap cntScafGene = new TreeMap (); + private TreeMap id2scaf = new TreeMap (); + private TreeMap id2chr = new TreeMap (); + private TreeMap chr2id = new TreeMap (); + + private TreeMap allTypeCnt = new TreeMap (); + private TreeMap allGeneBiotypeCnt = new TreeMap (); + private TreeMap allGeneSrcCnt = new TreeMap (); + + + private int cntChrGeneAll=0, cntScafGeneAll=0, cntOutSeq=0, cntNoOutSeq=0, cntScafSmall=0; + private int nChr=0, nScaf=0, nMt=0, nUnk=0, nGap=0; // for numbering output seqid and totals + private int cntChr=0, cntScaf=0, cntMtPt=0, cntUnk=0; // for counting regardless of write to file + private long chrLen=0, scafLen=0, mtptLen=0, unkLen=0, totalLen=0; + + private HashMap hexMap = new HashMap (); + + private TreeMap cntBase = new TreeMap (); + private PrintWriter fhOut, ghOut; + private PrintWriter logFile=null; + + private boolean bSuccess=true; + + /************************************************************************/ + public static void main(String[] args) { + isToSymap=false; + new ConvertEnsembl(args, defGapLen, null, false); + } + protected ConvertEnsembl(String[] args, int gapLen, String prefix, boolean bNum) { + if (args.length==0) { // command line + checkArgs(args); + return; + } + gapMinLen = gapLen; + prefixOnly = prefix; + bNumOnly = bNum; + + projDir = args[0]; + prt(""\n------ ConvertEnsembl "" + projDir + "" ------""); + checkInitFiles(); if (!bSuccess) return; + + //hexMap.put(""%09"", "" ""); // tab break on this + hexMap.put(""%3D"", ""-""); // = but cannot have these in attr, so use dash + hexMap.put(""%0A"", "" ""); // newline + hexMap.put(""%25"", ""%""); // % + hexMap.put(""%2C"", "",""); // , + hexMap.put(""%3B"", "",""); // ; but cannot have these in attr, so use comma + hexMap.put(""%26"", ""&""); // & + + createLog(args); if (!bSuccess) return; + checkArgs(args); if (!bSuccess) return; + + rwFasta(); + + rwAnno(); if (!bSuccess) return; + + printSummary(); + + prt(""""); + printSuggestions(); + prt(""------ Finish ConvertEnsembl "" + projDir + "" -------""); + if (logFile!=null) logFile.close(); + } + private void printSuggestions() { + boolean isChr = true; + if (chr2id.size()>0) { + for (String c : chr2id.keySet()) { + if (!c.startsWith(chrPrefix)) { + isChr=false; + break; + } + } + if (isChr && !INCLUDESCAF) prt(""Suggestion: Set SyMAP project parameter 'Group prefix' to 'Chr'.""); + } + if (cntOutSeq==0) prt(""Are these Ensembl files? Should scaffolds be included? Should 'Prefix only' be set?""); + else if (cntOutSeq>30) prt( ""Suggestion: There are "" + String.format(""%,d"",cntOutSeq) + "" sequences. "" + + ""Set SyMAP project parameter 'Minimum length' to reduce number loaded.""); + } + /** + * * Fasta file example: + * >1 dna_sm:chromosome chromosome:IRGSP-1.0:1:1:43270923:1 REF + * >Mt dna_sm:chromosome chromosome:IRGSP-1.0:Mt:1:490520:1 REF + * >Syng_TIGR_043 dna_sm:scaffold scaffold:IRGSP-1.0:Syng_TIGR_043:1:4236:1 REF + */ + private void rwFasta() { + try { + cntBase = new TreeMap (); + char [] base = {'A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'}; + for (char b : base) cntBase.put(b, 0); + + fhOut = new PrintWriter(new FileOutputStream(seqDir+outFaFile, false)); + fhOut.println(header); + + ghOut = new PrintWriter(new FileOutputStream(annoDir + outGapFile, false)); + ghOut.println(header); + + for (String file : inFaFileVec) { + rwFasta(file); + } + fhOut.close(); ghOut.close(); + System.err.print("" \r""); + String xx = (VERBOSE) ? ""("" + star + "")"" : """"; + prt(String.format(""Sequences not output: %,d %s"", cntNoOutSeq, xx)); + prt(""Finish writing "" + seqDir + outFaFile + "" ""); + + prt(""""); + prt( String.format(""A %,11d a %,11d"", cntBase.get('A'), cntBase.get('a')) ); + prt( String.format(""T %,11d t %,11d"", cntBase.get('T'), cntBase.get('t')) ); + prt( String.format(""C %,11d c %,11d"", cntBase.get('C'), cntBase.get('c')) ); + prt( String.format(""G %,11d g %,11d"", cntBase.get('G'), cntBase.get('g')) ); + prt( String.format(""N %,11d n %,11d"", cntBase.get('N'), cntBase.get('n') )); + String other=""""; + for (char b : cntBase.keySet()) { + boolean found = false; + for (char x : base) if (x==b) {found=true; break;} + if (!found) other += String.format(""%c %,d "", b, cntBase.get(b)); + } + if (other!="""") prt(other); + + cntBase.clear(); + prt(String.format(""Total %,d"", totalLen)); + + prt("" ""); + prt(String.format(""Gaps >= %,d: %,d (using N and n)"", gapMinLen, nGap)); + prt(""Finish writing "" + annoDir + outGapFile + "" ""); + } + catch (Exception e) {die(e, ""rwFasta"");} + } + private void rwFasta(String fileName) { + try { + prt(""Processing "" + fileName); + + String prtName="""", idCol1="""", line; + boolean bPrt=false, isChr=false, isScaf=false, isMtPt=false; + boolean bMt=false, bPt=false; + int baseLoc=0, gapStart=0, gapCnt=1, len=0, lineN=0; + + BufferedReader fhIn = openGZIP(fileName); if (!bSuccess) return; + + while ((line = fhIn.readLine()) != null) { + lineN++; + if (line.startsWith(""!"") || line.startsWith(""#"") || line.trim().equals("""")) continue; + + if (line.startsWith("">"")) { + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMtPt, len, idCol1, prtName); + len=0; + } + bPrt=false; + String line1 = line.substring(1).trim(); + String [] tok = line1.split(""\\s+""); + if (tok.length==0) { + die(""Header line is blank: line #"" + lineN); + return; + } + + idCol1 = tok[0].trim(); + + isMtPt = idCol1.toLowerCase().startsWith(""mt"") // MT or mtDNA... + || idCol1.toLowerCase().startsWith(""pt"") + || line.contains(""mitochondrion"") + || line.contains(""plastid"") + || line.contains(""mitochondrial"") + || line.contains(""chloroplast""); + + isChr = isChrNum(idCol1) || line.contains(""chromosome""); + + isScaf = line.contains(""scaffold""); + + if (isChr && !isMtPt) cntChr++; + else if (isMtPt) cntMtPt++; + else if (isScaf) cntScaf++; + else cntUnk++; + + if (prefixOnly!=null) { + if (!idCol1.startsWith(prefixOnly)) { + cntNoOutSeq++; + continue; + } + } + else if (bNumOnly) { + if (!isChrNum(idCol1)) { + cntNoOutSeq++; + continue; + } + } + + if (isChr && !isMtPt) { + nChr++; + prtName = isChrNum(idCol1) ? chrPrefix + padNum(tok[0]) : idCol1; // tok[0], e.g. C1 for cabbage + cntChrGene.put(idCol1, 0); + id2chr.put(idCol1, prtName); + chr2id.put(prtName, idCol1); + + fhOut.println("">"" + prtName + "" "" + idCol1 + "" "" + chrType); + bPrt=true; + } + else if (isMtPt && INCLUDEMtPt) { // just like for numeric chromosome + prtName = chrPrefix + tok[0]; + + if (idCol1.equalsIgnoreCase(""Mt"")) { + if (bMt) { + if (VERBOSE) prt(""Ignore Mt: "" + line); + cntNoOutSeq++; + continue; + } + else {bMt=true; nMt++;} + } + if (idCol1.equalsIgnoreCase(""Pt"")) { + if (bPt) { + if (VERBOSE) prt(""Ignore Pt: "" + line); + cntNoOutSeq++; + continue; + } + else {bPt=true; nMt++;} + } + cntChrGene.put(idCol1, 0); + id2chr.put(idCol1, prtName); + chr2id.put(prtName, idCol1); + + fhOut.println("">"" + prtName + "" "" + idCol1 + "" "" + chrType); + bPrt=true; + } + else if (isScaf && INCLUDESCAF) { + nScaf++; + prtName = scafPrefix + padNum(nScaf+""""); // scaf use name + + id2scaf.put(idCol1, prtName); + cntScafGene.put(idCol1, 0); + gapStart=1; gapCnt=0; baseLoc=0; + + fhOut.println("">"" + prtName+ "" "" + idCol1 + "" "" + scafType); + bPrt=true; + } + else { + if (isScaf) {prtName=""Scaf"";} + else if (isMtPt) {prtName=""Mt/Pt"";} + else {prtName=""Unk"";} + + if (prefixOnly!=null) {// use chr, don't know what it is + nUnk++; + prtName = unkPrefix + padNum(nUnk+""""); // but no prefix + id2chr.put(idCol1, prtName); + cntChrGene.put(idCol1, 0); + + bPrt=true; + fhOut.println("">"" + prtName+ "" "" + idCol1 + "" "" + unkType); + } + } + if (bPrt) cntOutSeq++; else cntNoOutSeq++; + } + ////////////////////////////////////////////////////////////////// + else { + String aline = line.trim(); + if (bPrt) { + char [] bases = aline.toCharArray(); + + for (int i =0 ; i0) { // gaps + if (gapCnt>gapMinLen) { + nGap++; + String x = createGap(prtName, gapStart, gapCnt); + if (bPrt) ghOut.println(x); + } + gapStart=0; gapCnt=1; + } + } + } + len += aline.length(); + if (bPrt) fhOut.println(aline); + } + } + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMtPt, len, idCol1, prtName); + } + fhIn.close(); + } + catch (Exception e) {die(e, ""rwFasta"");} + } + private boolean isChrNum(String col1) { + if (col1.contentEquals(""X"") || col1.contentEquals(""Y"")) return true; + try { + Integer.parseInt(col1); + return true; + } + catch (Exception e) { + if (col1.length()>3) return false; + // roman + char [] x = col1.toCharArray(); + for (char y : x) { + if (y!='I' && y!='V' && y!='X') return false; + } + return true; + } + } + //chr3 consensus gap 4845507 4895508 . + . Name ""chr03_0"" + private String createGap(String chr, int start, int len) { + String id = ""Gap_"" + nGap + ""_"" + len; + return chr + ""\tsymap\tgap\t"" + start + ""\t"" + (start+len) + ""\t.\t+\t.\tID=\"""" + id + ""\""""; + } + // The zero is added so that the sorting will be integer based + private String padNum(String x) { + try { + Integer.parseInt(x); + if (x.length()==1) return ""0"" + x; + else return x; + } + catch (Exception e) { + return x; + } // could be X or Y + } + + private void printTrace(boolean bPrt, boolean isChr, boolean isScaf, boolean isMtPt, int len, String id, String prtname) { + String x = (bPrt) ? """" : star; + String msg = String.format(""%-7s %-15s %,11d %s"", prtname, id, len,x); + String msg2 = String.format("" %s %,d %s .... "", prtname, len,x); + if (isChr && !isMtPt) { + chrLen+=len; + if (bPrt || VERBOSE) { + if (cntChr<=traceNum) prt(msg); + else if (cntChr==traceNum+1) prt(""Suppressing further chromosome logs""); + else System.out.print(msg2 + ""\r""); + } + else System.out.print(msg2 + ""\r""); + } + else if (isMtPt) { + mtptLen+=len; + if (bPrt || VERBOSE) { + if (cntMtPt<=traceNum) prt(msg); + else if (cntMtPt==traceNum+1) prt(""Suppressing further Mt/Pt logs""); + else System.out.print(msg2 + ""\r""); + } + } + else if (isScaf) { + scafLen+=len; + if (len1000000) System.out.print(msg2 + ""\r""); + } + else { + unkLen += len; + if (bPrt || VERBOSE) { + if (cntUnk<=traceNum) prt(msg); + else if (cntUnk==traceNum+1) prt(""Suppressing further unknown logs""); + else System.out.print(msg2 + ""\r""); + } + else if (len>1000000) System.out.print(msg2 + ""\r""); + } + } + + /******************************************************************************** + * XXX GFF file, e.g. +1 araport11 gene 3631 5899 . + . ID=gene:AT1G01010;Name=NAC001;biotype=protein_coding;description=NAC domain containing protein 1 [Source:NCBI gene (formerly Entrezgene)%3BAcc:839580];gene_id=AT1G01010;logic_name=araport11 +1 araport11 mRNA 3631 5899 . + . ID=transcript:AT1G01010.1;Parent=gene:AT1G01010;Name=NAC001-201;biotype=protein_coding;transcript_id=AT1G01010.1 +1 araport11 five_prime_UTR 3631 3759 . + . Parent=transcript:AT1G01010.1 +1 araport11 exon 3631 3913 . + . Parent=transcript:AT1G01010.1;Name=AT1G01010.1.exon1;constitutive=1;ensembl_end_phase=1;ensembl_phase=-1;exon_id=AT1G01010.1.exon1;rank=1 + */ + private int cntGene=0, cntExon=0, cntMRNA=0, cntGeneNotOnSeq=0, cntNoDesc=0; + private int skipLine=0; + private PrintWriter fhOutGff=null; + private int cntReadGene=0, cntReadMRNA=0, cntReadExon=0; + + // per gene + private String geneID="""",geneLine="""", gchr="""", gproteinAt="""", gmrnaAt=""""; + private String mrnaLine="""", mrnaID=""""; + private int cntThisGeneMRNA=0; + private Vector exonVec = new Vector (); + + private void rwAnno() { + if (inGffFileVec==null || inGffFileVec.size()==0) return; + try { + fhOutGff = new PrintWriter(new FileOutputStream(annoDir + outGffFile, false)); + fhOutGff.println(header); + + for (String file : inGffFileVec) { + rwAnno(file); + } + fhOutGff.close(); + + prt(String.format("" Use Gene %,d from %,d "", cntGene, cntReadGene)); + prt(String.format("" Use mRNA %,d from %,d "", cntMRNA, cntReadMRNA)); + prt(String.format("" Use Exon %,d from %,d "", cntExon, cntReadExon)); + prt(""Finish writing "" + annoDir + outGffFile + "" ""); + } + catch (Exception e) {die(e, ""rwAnno"");} + } + private void rwAnno(String file) { + try { + String line="""", type=""""; + + prt(""""); + prt(""Processing "" + file); + BufferedReader fhIn = openGZIP(file); if (!bSuccess) return; + + while ((line = fhIn.readLine()) != null) { + line = line.trim(); + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().length()==0) continue; + + String [] tok = line.split(""\\t""); + if (tok.length!=9) { + skipLine++; + if (skipLine<10) prt(""Bad line: "" + line); + else die(""too many errors""); + continue; + } + + // Count everything here for summary + type = tok[2].trim(); // gene, mRNA, exon... + if (!allTypeCnt.containsKey(type)) allTypeCnt.put(type,1); + else allTypeCnt.put(type, allTypeCnt.get(type)+1); + + if (type.equals(geneType)) { + rwAnnoOut(fhOutGff); + rwAnnoGene(tok, line); + cntReadGene++; + } + else if (type.equals(mrnaType)) { + rwAnnoMRNA(tok, line); + cntReadMRNA++; cntThisGeneMRNA++; + } + else if (type.equals(cdsType)) { + rwAnnoCDS(tok, line); + } + else if (type.equals(exonType)) { + rwAnnoExon(tok, line); + cntReadExon++; + } + } + fhIn.close(); + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + + private void rwAnnoGene(String [] tok, String line) { + try { + cntGene++; + if (cntGene%PRT==0) System.err.print("" Process "" + cntGene + "" genes...\r""); + + // counts for gene + String [] typeAttrs = tok[8].trim().split("";""); + String biotype = getVal(biotypeAttrKey, typeAttrs); + if (!allGeneBiotypeCnt.containsKey(biotype)) allGeneBiotypeCnt.put(biotype,1); + else allGeneBiotypeCnt.put(biotype, allGeneBiotypeCnt.get(biotype)+1); + + String src = tok[1].trim(); // RefSeq, Gnomon.. + + if (!allGeneSrcCnt.containsKey(src)) allGeneSrcCnt.put(src,1); + else allGeneSrcCnt.put(src, allGeneSrcCnt.get(src)+1); + + if (!biotype.equals(biotypeAttr)) return; // protein-coding + + String idcol1 = tok[0]; // chromosome, scaffold, linkage group... + if (id2chr.containsKey(idcol1)) { + cntChrGeneAll++; + gchr = id2chr.get(idcol1); + cntChrGene.put(idcol1, cntChrGene.get(idcol1)+1); + } + else if (id2scaf.containsKey(idcol1)) { + cntScafGeneAll++; + gchr = id2scaf.get(idcol1); + cntScafGene.put(idcol1, cntScafGene.get(idcol1)+1); + } + else { + cntGeneNotOnSeq++; + return; + } + geneID = getVal(idAttrKey, typeAttrs); + String gid = geneID.replace(RMGENE,""""); + String attr = idAttrKey + ""="" + gid + "";"" + getKeyVal(nameAttrKey, typeAttrs); + + String desc = getVal(descAttrKey, typeAttrs).trim(); + if (desc==null || desc.equals("""")) { + cntNoDesc++; + } + else { + if (desc.contains(source)) desc = desc.substring(0, desc.lastIndexOf(source)).trim(); + + if (desc.contains(""%"")) { + for (String hex : hexMap.keySet()) { + if (desc.contains(hex)) desc = desc.replace(hex, hexMap.get(hex)); + } + } + attr += "";"" + DESC + desc; + } + + geneLine = ""###\n"" + gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + attr; + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + // mRNA is not loaded into SyMAP, but needed for exon parentID + private void rwAnnoMRNA(String [] tok, String line) { + try { + if (!mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (!geneID.equals(pid)) return; + + //////// + mrnaID = getVal(idAttrKey, attrs); + gmrnaAt = "";"" + MRNAID + mrnaID.replace(RMTRAN,""""); + + String mid = idAttrKey + ""="" + mrnaID.replace(RMTRAN,""""); + String gid = parentAttrKey + ""="" + geneID.replace(RMGENE,""""); + String newAttrs = mid + "";"" + gid; + mrnaLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + + tok[4] + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + + cntMRNA++; + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + private void rwAnnoCDS(String [] tok, String line) { + try { + if (!ATTRPROT || mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (mrnaID.equals(pid)) { + gproteinAt = PROTEINID + getVal(cdsProteinAttrKey, attrs); + } + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + /** Write genes and exons to file**/ + private void rwAnnoExon(String [] tok, String line) { + try { + if (mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + if (!mrnaID.equals(pid)) return; + + ////////////////// + String newAttrs = parentAttrKey + ""="" + mrnaID.replace(RMTRAN,""""); + + String nLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + exonVec.add(nLine); + cntExon++; + } + catch (Exception e) {die(e, ""rwAnnoExon"");} + } + private void rwAnnoOut( PrintWriter fhOutGff) { + try { + if (geneID.equals("""")) return; + if (mrnaID.equals("""")) return; + + gmrnaAt = gmrnaAt.replace(RMTRAN,""""); + gmrnaAt += "" ("" + cntThisGeneMRNA + "");""; + String line = geneLine + gmrnaAt + gproteinAt; + fhOutGff.println(line); + + fhOutGff.println(mrnaLine); + + for (String eline : exonVec) fhOutGff.println(eline); + + cntThisGeneMRNA=0; + geneID=geneLine=gchr=gproteinAt=gmrnaAt=mrnaID=mrnaLine=""""; + exonVec.clear(); + } + catch (Exception e) {die(e, ""rwAnnoOut"");} + } + + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return x[1]; + } + return """"; + } + private String getKeyVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return s; + } + return key + ""=no value""; + } + + /***************************************************************** + * Summary + */ + private void printSummary() { + prt("" ""); + if (VERBOSE) { + prt("">>Sequences ""); + if (cntChr>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntChr, nChr, ""Chromosomes"", chrLen)); + } + if (cntMtPt>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntMtPt, nMt, ""Mt/Pt"", mtptLen)); + } + if (cntScaf>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d (%,d < %,dbp)"", cntScaf,nScaf, ""Scaffolds"", scafLen, cntScafSmall, scafMaxLen)); + } + if (cntUnk>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntUnk, nUnk, ""Unknown"", unkLen)); + } + if (inGffFileVec==null) return; + + prt("" ""); + prt("">>All Types (col 3) ("" + plus + "" are processed keywords)""); + for (String key : allTypeCnt.keySet()) { + boolean bKey = ATTRPROT && key.equals(cdsType); + String x = (key.equals(geneType) || key.equals(mrnaType) || key.equals(exonType)) || bKey ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allTypeCnt.get(key), x)); + } + + prt("">>All Gene Source (col 2)""); + for (String key :allGeneSrcCnt.keySet()) { + prt(String.format("" %-22s %,8d"", key, allGeneSrcCnt.get(key))); + } + + prt("">>All gene biotype= (col 8) ""); + for (String key : allGeneBiotypeCnt.keySet()) { + String x = (key.equals(biotypeAttr)) ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allGeneBiotypeCnt.get(key), x)); + } + + if (cntNoDesc>0) { + prt("">>Description""); + prt(String.format("" %-22s %,8d"", ""None"", cntNoDesc)); + } + } + prt(String.format("">>Chromosome gene count %,d"", cntChrGeneAll)); + + for (String prt : chr2id.keySet()) { + String id = chr2id.get(prt); // sorted on prtName + int cnt = cntChrGene.get(id); + prt(String.format("" %-10s %-20s %,8d"", prt, id, cnt)); + } + + if (INCLUDESCAF) { + prt(String.format("">>Scaffold gene count %,d (list scaffolds with #genes>%d)"", cntScafGeneAll, traceNumGenes)); + int cntOne=0; + for (String key : cntScafGene.keySet()) { // sorted on idCol1, which is not scaffold order + int cnt = cntScafGene.get(key); + if (cnt>traceNumGenes) prt(String.format("" %-7s %-15s %,8d"", id2scaf.get(key), key, cnt)); + else cntOne++; + } + prt(String.format("" Scaffolds with <=%d gene (not listed) %,8d"", traceNumGenes, cntOne)); + prt(String.format("" Genes not included %,8d"", cntGeneNotOnSeq)); + } + else prt(String.format("" Genes not on Chromosome %,8d"", cntGeneNotOnSeq)); + } + /************************************************************ + * File stuff + */ + private boolean checkInitFiles() { + // find fasta and gff files + try { + if (projDir==null || projDir.trim().equals("""")) + return die(""No project directory""); + + File dir = new File(projDir); + if (!dir.isDirectory()) + return die(""The argument must be a directory. "" + projDir + "" is not a directory.""); + + File[] files = dir.listFiles(); + for (File f : files) { + if (f.isFile() && !f.isHidden()) { + String fname = f.getName(); + + if (fname.endsWith(faSuffix + "".gz"") || fname.endsWith(faSuffix)) inFaFileVec.add(projDir + ""/"" + fname); + else if (fname.endsWith(gffSuffix + "".gz"") || fname.endsWith(gffSuffix)) inGffFileVec.add(projDir + ""/"" +fname); + } + } + } + catch (Exception e) {die(e, ""Checking files"");} + + if (inFaFileVec.size()==0) + return die(""Project directory "" + projDir + "": no file ending with "" + faSuffix + "" or ""+ faSuffix + "".gz (i.e. Ensembl files)""); + if (inGffFileVec.size()==0) + prt(""Project directory "" + projDir + "": no file ending with "" + gffSuffix + "" or "" + gffSuffix + "".gz""); + + // Create sequence and annotation directories + if (!projDir.endsWith(""/"")) projDir += ""/""; + seqDir = projDir + seqDir; + createDir(true, seqDir); if (!bSuccess) return false; + + annoDir = projDir + annoDir; + createDir(false, annoDir); if (!bSuccess) return false; + + return true; + } + private void createLog(String [] args) { + if (args.length==0) return; + logFileName = args[0] + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {die(""Cannot open "" + logFileName); logFile=null;} + } + + private boolean createDir(boolean isSeq, String dir) { + File nDir = new File(dir); + if (nDir.exists()) { + String x = (isSeq) ? "" .fna and .fa "" : "" .gff and .gff3""; + prt(dir + "" exists - remove existing "" + x + "" files""); + deleteFilesInDir(isSeq, nDir); + return true; + } + else { + if (!nDir.mkdir()) { + die(""*** Failed to create directory '"" + nDir.getAbsolutePath() + ""'.""); + return false; + } + } + return true; + } + private void deleteFilesInDir(boolean isSeq, File dir) { + if (!dir.isDirectory()) return; + + String[] files = dir.list(); + + if (files==null) return; + + for (String fn : files) { + if (isSeq) { + if (fn.endsWith("".fna"") || fn.endsWith("".fa"")) { + new File(dir, fn).delete(); + } + } + else { + if (fn.endsWith("".gff"") || fn.endsWith("".gff3"")) { + new File(dir, fn).delete(); + } + } + } + } + private BufferedReader openGZIP(String file) { + try { + if (!file.endsWith("".gz"")) { + File f = new File (file); + if (f.exists()) return new BufferedReader ( new FileReader (f)); + else die(""Cannot open file "" + file); + } + else if (file.endsWith("".gz"")) { + FileInputStream fin = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fin); + InputStreamReader xover = new InputStreamReader(gzis); + return new BufferedReader(xover); + } + else die(""Do not recognize file suffix: "" + file); + } + catch (Exception e) {die(e, ""Cannot open file "" + file);} + return null; + } + + /****************************************************************** + * Args print and process + */ + private void checkArgs(String [] args) { + if (args.length==0 || args[0].equals(""-h"") || args[0].equals(""-help"") || args[0].equals(""help"")) { + System.out.println(""\nConvertEnsembl [-r] [-c] [-v] ""); + System.out.println( + "" the project directory must contain the FASTA file and the GFF is optional: \n"" + + "" FASTA file ending with .fa or .fa.gz e.g. Oryza_sativa.IRGSP-1.0.dna_sm.toplevel.fa.gz\n"" + + "" GFF file ending with .gff3 or .gff3.gz e.g. Oryza_sativa.IRGSP-1.0.45.chr.gff3.gz\n"" + + "" Options:\n"" + + "" -s include any sequence with the header contains 'scaffold'.\n"" + + "" -t include Mt and Pt chromosomes.\n"" + + "" -p include the protein name (1st CDS) in the attribute field.\n"" + + "" -v write header lines of ignored sequences [default false].\n"" + + ""\nSee https://csoderlund.github.io/SyMAP/convert for details.""); + System.exit(0); + } + + prt(""Parameters:""); + prt("" Project Directory: "" + args[0]); + projDir = args[0]; + + if (gapMinLen!=defGapLen) prt("" Gap size: "" + gapMinLen); // argument to Convert + if (prefixOnly!=null) prt("" Prefix Only: "" + prefixOnly); // set in main + if (bNumOnly) prt("" Only number, X, Y, Roman""); // set in main + + if (args.length>1) { + for (int i=1; i< args.length; i++) { + if (args[i].equals(""-v"")) { + VERBOSE=true; + prt("" Verbose ""); + traceNum=20; + } + else if (args[i].equals(""-s"")) { + INCLUDESCAF=true; + chrPrefix = chrPrefix2; + prt("" Include any sequence whose header line contains 'scaffold'""); + prt("" Uses prefixes Chr '"" + chrPrefix + ""' and Scaffold '"" + scafPrefix +""'""); + } + else if (args[i].equals(""-t"")) { + INCLUDEMtPt=true; + prt("" Include Mt and Pt chromosomes""); + } + else if (args[i].equals(""-p"")) { + ATTRPROT=true; + prt("" Include protein-id in attributes""); + } + } + } + } + private boolean die(Exception e, String msg) { + System.err.println(""Fatal error -- "" + msg); + e.printStackTrace(); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private boolean die(String msg) { + System.err.println(""Fatal error -- "" + msg); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/toSymap/xToSymap.java",".java","695","23","package toSymap; + +/************************************************** + * toSymap is part of the symap package, but has its own main. + * The files ConvertNCBI and ConvertEnsembl can be extracted, modified and run stand-alone + * The other files use backend.Constants and backend.Util, so can not be directly extracted + */ +public class xToSymap { + protected static boolean isDebug=false; + public static void main(String[] args) { + if (hasArg(args, ""-d"")) { + isDebug=true; + System.out.println(""Running in debug mode""); + } + new ToFrame(); + } + static boolean hasArg(String [] args, String arg) { + for (int i=0; i + * 3. sequence and annotation directory + * + * Fasta: + * provide list of prefixes + * GFF + * is there ID and Parent and do they abide by the rules + * is description in gene or mRNA + * + * NCBI vs Ensembl: + * NCBI has ""NCBI"" in header lines whereas Ensembl has no indication in header + * NCBI uses ""gene-biotype"" whereas Ensembl used ""biotype"" + * NCBI has mRNA ""products"" whereas I haven't seen that in Ensembl + */ +public class Summary { + private final String seqSubDir = Constants.seqSeqDataDir; + private final String annoSubDir = Constants.seqAnnoDataDir; + private final String [] fastaFile = Constants.fastaFile; + private String logFileName = ""xSummary.log""; + private boolean bVerbose=false, bConverted=false; // args from xToSymap + private int CNTHEAD=1, CNTPREFIX=5, CNTLEN=5; // #header, #unique prefix, #sequence len; changed if Verbose + private int MAXBASE=Integer.MAX_VALUE; // if verbose, count bases for this many + + private final String chrPrefix=""Chr""; + private final String sChrPrefix=""C""; + private final String scafPrefix=""s""; + private final String geneType = ""gene""; + private final String mrnaType = ""mRNA""; + private final String exonType = ""exon""; + private final String cdsType = ""CDS""; + + private final String idAttrKey = ""ID""; // Gene and mRNA + private final String parentAttrKey = ""Parent""; // mRNA and Exon + private final String nBiotypeAttrKey = ""gene_biotype""; // NCBI Gene + private final String eBiotypeAttrKey = ""biotype""; // Ensemble Gene + private final String proteinCoding = ""protein_coding""; // biotype=protein_coding + private final String proteinID = ""protein_id""; // CDS attribute, NCBI and Ensembl + + private final String prodAttrKey = ""product""; // NCBI + private final String [] descAttrKeyArr = {""description"", ""desc"", ""Desc""}; // Ensembl and NCBI + + private PrintWriter logFile=null; + private boolean bSuccess=true; + private String typeFile=""""; + + private Vector seqFiles = new Vector (); + private Vector annoFiles = new Vector (); + + private TreeMap chrMap = new TreeMap (); // Id, length + private TreeMap cntBase = new TreeMap (); + + private String projDir ="""", seqDir=null, annoDir = null; + private int cntErr=0; + + protected Summary(String dirName) { + this.projDir = dirName; + } + /*************************************************************/ + protected void runCheck(boolean bVerbose, boolean bConvert) { + if (!isDir(projDir)) { + prt(""Not a directory: "" + projDir); + return; + } + this.bVerbose = bVerbose; + if (bVerbose) {CNTPREFIX=10;} + this.bConverted = bConvert; + + prt(""""); + prt(""------ Summary for "" + projDir + "" ------""); + createLog(); + if (bVerbose) prt(""Verbose output ""); + if (bConverted) prt(""Converted""); + prtConvertLog(); + + if (bConverted) { + setConvertDir(); + } + else { + setTopDir(); + if (seqDir==null) setNcbiDir(); + if (seqDir==null) setConvertDir(); + } + if (seqDir==null) { + prt(""Cannot find FASTA or GFF files in project directory: "" + projDir); + return; + } + // print files + prt(""""); + if (seqDir.endsWith(""/"")) seqDir = seqDir.substring(0, seqDir.length()-1); + prt(""Sequence directory: "" + seqDir + "" "" + FileDir.fileDate(seqDir)); + for (File f : seqFiles) prt("" "" + f.getName()); + + if (annoDir!=null) { + if (annoDir.endsWith(""/"")) annoDir = annoDir.substring(0, annoDir.length()-1); + prt(""Annotation directory: "" + annoDir); + for (File f : annoFiles) prt("" "" + f.getName()); + } + + // compute + rFasta(); if (!bSuccess) return; + + rAnno(); + + // finish + if (!bConverted) { + prt("" ""); + if (typeFile.isEmpty()) typeFile = ""No hints""; + if (typeFile.startsWith("";"")) typeFile = typeFile.substring(1); + prt(""Input type: "" + typeFile); + } + if (cntErr>0) prt(""Warnings: "" + cntErr); + + prt(""------ Finish summary for "" + projDir + "" ------""); + if (logFile!=null) logFile.close(); + } + /*********************************************************** + * + */ + private void rFasta() { + prt(""""); + prt(""FASTA sequence file(s)""); + String fileName=""""; + try { + char [] base = {'A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'}; + for (char b : base) cntBase.put(b, 0); + + TreeMap prefixMap = new TreeMap (); + int [] lenCutoff = {10000, 100000, 1000000, 10000000, 50000000, 100000000, 200000000, 0}; + int [] lenCnts = {0,0,0,0,0, 0, 0, 0, 0}; + final String NUM_PREFIX = ""Number, X, Y, Roman""; + + String idCol1="""", line; + boolean isChr=false, isScaf=false, isMt=false, isPt=false, isLowerCase=false; + int cntAll=0, cntChr=0, cntChrScaf=0, cntScaf=0, cntMt=0, cntPt=0, cntUnk=0, cntN=0, cntLine=0, len=0; + int cntUniPre=0; + long totalLen = 0; + String baseMsg=""""; + + Vector headLines = new Vector (); + + String lenline=""""; + for (File file : seqFiles) { + fileName = file.getName(); + String f = (seqDir.endsWith(""/"")) ? seqDir + fileName : seqDir + ""/"" + fileName; + BufferedReader fhIn = Utils.openGZIP(f); + if (fhIn==null) return; + len=0; + + while ((line = fhIn.readLine()) != null) { + if (line.startsWith(""!"") || line.startsWith(""#"") || line.trim().isEmpty()) continue; + + if (line.startsWith("">"")) { + if (len>0) { // process last sequence + totalLen += len; + System.out.print("" #"" + cntAll +"" process ID "" + idCol1 + "" "" + totalLen + "" bases... \r""); + + for (int i=0; i < lenCutoff.length; i++) { + if (len= MAXBASE) baseMsg = String.format("" for 1st %,d bases"", totalLen); + } + if (bVerbose && baseMsg.isEmpty()) { + char [] bases = line.toCharArray(); + for (char b : bases) { + if (cntBase.containsKey(b)) cntBase.put(b, cntBase.get(b)+1); // counts + else cntBase.put(b, 1); + } + } + else if (!isLowerCase) { + isLowerCase = line.contains(""a"") || line.contains(""c"") || line.contains(""t"") || line.contains(""g""); + if (!isLowerCase) { + if (line.contains(""N"")) cntN++; + cntLine++; + } + } + } + } + if (len>0) { // finish last one + totalLen += len; + for (int i=0; i < lenCutoff.length; i++) { + if (len0) + typeFile = ""NCBI chr NC_ prefix""; + else if (prefixMap.containsKey(""NW_"") && prefixMap.get(""NW_"")>0) + typeFile = ""NCBI scaf NW_ prefix""; + else if (prefixMap.containsKey(NUM_PREFIX) && prefixMap.get(NUM_PREFIX)>0) + typeFile = ""Ensembl chr '"" + NUM_PREFIX + ""'""; + + Vector pVec = new Vector (); + for (String key : prefixMap.keySet()) { + Count p = new Count(); + p.word = key; + p.count = prefixMap.get(key); + pVec.add(p); + } + Collections.sort(pVec); + + int cnt=0; + for (Count p : pVec) { + if (p.count>1) prt(6, p.count, p.word); + else if (p.count==1) { + cnt++; + if (cnt<5) prt(6, p.count, p.word); + else if (cnt==5) prt(""Suppressing further unique prefixes""); + } + } + if (cnt>=5) prtNZ(6, cnt, ""Unique prefixes""); + + prt(""""); + prt(""Counts of Length Ranges:""); + String outline=""""; + int end=0; + for (int i=0; i < lenCutoff.length; i++) if ( lenCnts[i]!=0) end=i; + for (int i=0; i <= end; i++) { + String xxx = lenCnts[i]==0 ? """" : String.format(""%,d"", lenCnts[i]); + if (lenCutoff[i]==0) + outline += String.format("" %s>=%s"",xxx, Utilities.kMText(lenCutoff[i-1])); + else + outline += String.format("" %s<%s"",xxx, Utilities.kMText(lenCutoff[i])); + } + if (!outline.isEmpty()) prt(outline); + prt(String.format("" %,d Total length"", totalLen)); + + if (bVerbose) { + prt(""""); + int d = (chrMap.size()3) return false; + // roman + char [] x = col1.toCharArray(); + for (char y : x) { + if (y!='I' && y!='V' && y!='X') return false; + } + return true; + } + } + + private String getPrefix(String tag) { + if (tag.contains(""_"")) { + Pattern pat2 = Pattern.compile(""([AN][A-Z])_(\\d*).*""); // NC_ + Matcher m = pat2.matcher(tag); + if (m.matches()) return m.group(1) + ""_""; + } + + Pattern pat1 = Pattern.compile(""([a-zA-Z]+)(\\d+)([.]?).*""); // Scaf123 or Scaf123.3 + Matcher m = pat1.matcher(tag); + if (m.matches()) return m.group(1); + + Pattern pat3 = Pattern.compile(""([a-zA-Z]+)$""); // Alphabetic + m = pat3.matcher(tag); + if (m.matches()) return m.group(1); + + String [] x = tag.split(""_""); // other, could be CTG123_ + if (x.length>0) return x[0]; + + return tag; + } + + /*********************************************************** + * XXX Make sure there is ID and product or description + * Make sure that the Exon is linked to the first mRNA of the gene + */ + private void rAnno() { + prt("" ""); + if (annoFiles.size()==0) { + prt(""No GFF Annotation file(s)""); + return; + } + prt(""GFF Annotation file(s)""); + String fileName=""""; + + try { + int cntReadGenes=0, cntReadMRNAs=0, cntReadExons=0; + int cntGene=0, cntExon=0, cntMRNA=0, cntmProdKey=0, cntgProdKey=0, cntgDescKey=0, cntProteinID=0; + int errID=0, errParent=0, errChr=0, errLine=0; + boolean isNCBI=false, isEns=false; + + TreeMap typeMap = new TreeMap (); // column 3 + TreeMap biotypeMap = new TreeMap (); // column 8 + TreeMap attrMap = new TreeMap (); // column 8 + + if (bVerbose) prt(""Example lines:""); + for (File file : annoFiles) { + fileName = file.getName(); + String f = (seqDir.endsWith(""/"")) ? (annoDir + fileName) : (annoDir + ""/"" + fileName); + BufferedReader fhIn = Utils.openGZIP(f); + if (fhIn==null) return; + + String line, geneID=null, mrnaID=null, cdsID=null; + + while ((line = fhIn.readLine()) != null) { + if (line.startsWith(""#"")) { + if (line.contains(""processor NCBI"")) { + if (!typeFile.isEmpty()) typeFile += ""; ""; + typeFile += ""NCBI GFF header""; + isNCBI = true; + } + continue; + } + if (line.startsWith(""!"") || line.startsWith(""#"") ||line.isEmpty()) continue; + + String [] tok = line.split(""\\t""); + if (tok.length!=9) { + badLine(errLine++, ""Wrong number columns ("" + tok.length + ""): "", line); if (!bSuccess) return; + continue; + } + + String chrCol = tok[0]; // chromosome, scaffold, ... + String type = tok[2]; + incMap(type, typeMap); // count types + + boolean isGene = type.equals(geneType); + boolean isMRNA = type.equals(mrnaType); + boolean isExon = type.equals(exonType); + boolean isCDS = type.equals(cdsType); + if (!isGene && !isMRNA && !isExon && !isCDS) continue; + + String [] attrs = tok[8].split("";""); + if (attrs.length==0) { + badLine(errLine++, ""No attributes"", line); if (!bSuccess) return; + continue; + } + if (!chrMap.containsKey(chrCol)) { + badLine(errChr++, ""No '"" + chrCol + ""' sequence name in FASTA: "", line); if (!bSuccess) return; + continue; + } + + if (isGene) { + cntReadGenes++; + if (cntReadGenes%5000==0) System.err.print("" Read "" + cntReadGenes + "" genes...\r""); + + geneID=mrnaID=cdsID=null; + + String ebiotype = getVal(eBiotypeAttrKey, attrs); // biotype= + String nbiotype = getVal(nBiotypeAttrKey, attrs); // gene-biotype= + if (!ebiotype.isEmpty()) { + isEns=true; + incMap(ebiotype, biotypeMap); + if (!ebiotype.contentEquals(proteinCoding)) continue; // not protein-coding + } + else if (!nbiotype.isEmpty()) { + isNCBI=true; + incMap(nbiotype, biotypeMap); + if (!nbiotype.contentEquals(proteinCoding)) continue; // not protein-coding + } + + geneID = getVal(idAttrKey, attrs); + if (geneID.contentEquals("""")) { + geneID = null; + badLine(errID++, ""No ID keyword: "", line); if (!bSuccess) return; + continue; + } + + cntGene++; + if (cntGene==1 && bVerbose) prt(line); + + for (String a : attrs) { + String [] tok2 = a.split(""=""); + if (tok2.length==2) incMap(tok2[0], attrMap); + } + + for (String a : descAttrKeyArr) { + String v = getVal(a, attrs); + if (!v.isEmpty()) { + cntgDescKey++; + break; + } + } + String product = getVal(prodAttrKey, attrs); + if (!product.isEmpty()) cntgProdKey++; + } + else if (isMRNA) { + cntReadMRNAs++; + + if (geneID==null) continue; + if (mrnaID!=null) continue; + + String parent = getVal(parentAttrKey, attrs); + if (parent.contentEquals("""")) { + badLine(errParent++, ""No parent keyword: "", line); if (!bSuccess) return; + continue; + } + if (!geneID.startsWith(""gene-"")) + parent = parent.replace(""gene-"", """"); + if (!parent.contentEquals(geneID)) { + geneID=mrnaID=null; // pseudogene, etc + continue; + } + + mrnaID = getVal(idAttrKey, attrs); + if (mrnaID.contentEquals("""")) { + mrnaID=null; + badLine(errID++, ""No ID keyword: "", line); if (!bSuccess) return; + continue; + } + cntMRNA++; + if (cntMRNA==1 && bVerbose) prt(line); + + String product = getVal(prodAttrKey, attrs); + if (!product.isEmpty()) cntmProdKey++; + } + else if (isExon) { + cntReadExons++; + if (mrnaID==null) continue; + + String parent = getVal(parentAttrKey, attrs); + if (parent.contentEquals("""")) { + badLine(errParent++, ""No parent keyword: "", line); if (!bSuccess) return; + continue; + } + if (!parent.contentEquals(mrnaID)) continue; + + cntExon++; + if (cntExon==1 && bVerbose) prt(line); + } + else if (isCDS) { + if (mrnaID==null) continue; + if (cdsID!=null) continue; + + String parent = getVal(parentAttrKey, attrs); + if (parent.contentEquals("""") || !parent.contentEquals(mrnaID)) continue; + + cdsID = ""yes""; + String pid = getVal(proteinID, attrs); + if (!pid.isEmpty()) cntProteinID++; + } + if (!bSuccess) return; + } + fhIn.close(); + }// Loop through files + ////////////////////////////////////////////// + if (bVerbose) prt("" ""); + prt(""Summary: ""); + String pc = (biotypeMap.size()>0) ? "" (use protein_coding only)"" : """"; + prt(7, cntGene, String.format(""Genes from %,d %s"", cntReadGenes, pc)); + pc = (cntProteinID>0) ? String.format("" (%,d has protein_id)"", cntProteinID) : """"; + prt(7, cntMRNA, String.format(""mRNAs from %,d %s"", cntReadMRNAs, pc)); + prt(7, cntExon, String.format(""Exons from %,d "", cntReadExons)); + + if (bVerbose) { + prt(""""); + prt(""Types: "" + typeMap.size()); + String oline=""""; + int cnt=0; + for (String key : typeMap.keySet()) { + if (typeMap.get(key)>1) { + oline += String.format(""%,7d %-25s "",typeMap.get(key), key); + cnt++; + if (cnt>2) { + prt(oline); + cnt=0; + oline=""""; + } + } + } + if (!oline.isEmpty()) prt(oline); + if (biotypeMap.size()>0) {// Converted do not have biotype + prt(""""); + prt(""Gene Attributes biotype: "" + biotypeMap.size()); + oline=""""; + cnt=0; + for (String key : biotypeMap.keySet()) { + if (biotypeMap.get(key)>1) { + oline += String.format(""%,7d %-25s "",biotypeMap.get(key), key); + cnt++; + if (cnt>2) { + prt(oline); + cnt=0; + oline=""""; + } + } + } + if (!oline.isEmpty()) prt(oline); + } + } // end Verbose + + prt(""""); + prt(""Gene Attribute: "" + attrMap.size()); // print because if Load into SyMAP, this is the Query columns + String oline=""""; + int cnt=0; + for (String a : attrMap.keySet()) { + oline += String.format("" %,7d %-25s"", attrMap.get(a), a); + cnt++; + if (cnt==2) { + prt(oline); + cnt=0; + oline=""""; + } + } + if (!oline.isEmpty()) prt(oline); + + if (!bConverted) { + if (cntmProdKey>0) { + prt(""mRNA Attribute:""); + prt(7, cntmProdKey, ""product""); + } + + if (!typeFile.isEmpty() && (isNCBI || isEns)) + typeFile += ""\n ""; // separate from FASTA remarks + + if (isNCBI) { + typeFile += ""NCBI 'gene_biotype' keyword""; + + if (cntmProdKey>0) typeFile += ""; NCBI mRNA 'product' keyword""; + if (cntgProdKey>0) typeFile += ""; gene 'product' keyword""; + if (cntgDescKey>0) typeFile += ""; gene 'description' keyword""; + if (cntmProdKey==0 && cntgDescKey==0) prt(""No mRNA product or gene description""); + } + if (isEns) { + typeFile += ""Ensembl 'biotype' keyword""; + + if (cntgDescKey>0) typeFile += ""; gene 'description' keyword""; + else prt(""No gene description""); + } + } + } + catch (Exception e) { die(e, ""Checking GFF file "" + fileName); } + } + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x.length==2 && x[0].equals(key)) return x[1]; + } + return """"; + } + + private void badLine(int cnt, String msg, String line) { + cntErr++; + String s = (line.length()>100) ? line.substring(100) + ""..."" : line; + if (cnt<3) prt(""+++"" + msg + ""\n "" + s); + if (cntErr>20) { + die(""Too many bad lines: "" + cntErr); + bSuccess=false; + } + } + /************************************************* + * Are the files directly in the projDir + */ + private void setTopDir() { + try { + seqDir = projDir; + annoDir = projDir; + getFiles(); + } + catch (Exception e) { die(e, ""Checking project directory for files"" + projDir); } + } + + /************************************************************************** + * Are the files in projDir/ncbi_dataset/data/ + */ + private void setNcbiDir() { + try { + String ncbi_dataset=""ncbi_dataset""; + String ncbi_data= ""/data""; + String subDir=null; + + String dsDirName=null; + File dir = new File(projDir); + + File[] files = dir.listFiles(); + boolean isDS=false; + for (File f : files) { + if (f.isDirectory()) { + if (f.getName().contentEquals(ncbi_dataset)) { + isDS = true; + break; + } + } + } + if (!isDS) return; + + ///////////////////////////////// + dsDirName = FileDir.fileNormalizePath(projDir, ncbi_dataset + ncbi_data); + + dir = new File(dsDirName); + if (!dir.isDirectory()) { + die(""ncbi_dataset directory is incorrect "" + dsDirName); + return; + } + files = dir.listFiles(); + for (File f : files) { + if (f.isDirectory()) { + subDir = f.getName(); + break; + } + } + if (subDir==null) { + die(dsDirName + "" missing sub-directory""); + return; + } + seqDir = FileDir.fileNormalizePath(dsDirName, subDir); + annoDir = seqDir; + + getFiles(); + } + catch (Exception e) { die(e, ""Checking "" + projDir); } + } + private void setConvertDir() { + seqDir = FileDir.fileNormalizePath(projDir, seqSubDir); + annoDir = FileDir.fileNormalizePath(projDir, annoSubDir); + getFiles(); + } + /************************************************************************** + * Are the files in /sequence and /annotation + */ + private void getFiles() { + try { + File sdf = new File(seqDir); + if (sdf.exists() && sdf.isDirectory()) { + for (File f2 : sdf.listFiles()) { + String name = f2.getAbsolutePath(); + for (String suf : fastaFile) { + if (!f2.isFile() || f2.isHidden()) continue; + + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + seqFiles.add(f2); + break; + } + } + } + } + if (seqFiles.size()==0) { + seqDir=null; + return; + } + sdf = new File(annoDir); + if (sdf.exists() && sdf.isDirectory()) { + for (File f2 : sdf.listFiles()) { + if (!f2.isFile() || f2.isHidden()) continue; + + String name = f2.getAbsolutePath(); + for (String suf : Constants.gffFile) { + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + annoFiles.add(f2); + break; + } + } + } + } + if (annoFiles.size()==0) annoDir=null; + } + catch (Exception e) { die(e, ""Getting sequence and annotation files from: "" + projDir); } + } + + ////////////////////////////////////////////////////////// + private void createLog() { + if (!projDir.endsWith(""/"")) projDir += ""/""; + logFileName = projDir + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {die(e, ""Cannot open "" + logFileName); logFile=null;} + } + /******************************************************* + * Print out whether convert has been run + */ + private void prtConvertLog() { + try { + File sdf = new File(projDir); + if (sdf.exists() && sdf.isDirectory()) { + for (File f2 : sdf.listFiles()) { + String name = f2.getName(); + if (name.startsWith(""xConvert"")) { + prt(""Convert log: "" + name + "" "" + FileDir.fileDate(f2.getAbsolutePath())); + } + } + } + } + catch (Exception e) {die(e, ""Cannot search for convert log""); } + } + private boolean isDir(String dirName) { + File dir = new File(dirName); + if (!dir.isDirectory()) return false; + else return true; + } + private boolean die(Exception e, String msg) { + ErrorReport.print(e, msg); + bSuccess = false; + return false; + } + private boolean die(String msg) { + System.err.println(""Fatal error -- "" + msg); + bSuccess = false; + return false; + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } + private void prt(int sz, int num, String msg) { + String f = "" %,"" + sz + ""d %s""; + String x = String.format(f, num, msg); + System.out.println(x); + if (logFile!=null) logFile.println(x); + } + private void prtNZ(int sz, int num, String msg) { + if (num==0) return; + String f = "" %,"" + sz + ""d %s""; + String x = String.format(f, num, msg); + System.out.println(x); + if (logFile!=null) logFile.println(x); + } + + // Count and sort map + private boolean incMap(String key, TreeMap map) { + if (map.containsKey(key)) { + map.put(key, map.get(key)+1); + return false; + } + else { + map.put(key, 1); + return true; + } + } + private class Count implements Comparable { + String word=""""; + int count=0; + + public int compareTo(Count a){ + return a.count - count; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorVariable.java",".java","3536","115","package colordialog; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +public class ColorVariable implements ActionListener { + protected String className; // e.g. Mapper + protected String variableName; // e.g. mapper (symap.Mapper.mapper) + protected String displayName; + protected JLabel label; + protected JButton button; + private ColorIcon icon; + private Color defaultColor, prevColor; + private boolean alphaEnabled=true; + private int order; + private JColorChooser colorChoose; + private JDialog dialog; + + protected ColorVariable(String className, String variableName, String display_name, + String description, Dimension dim, int nOrder) { + + defaultColor = ColorDialog.getDefault(variableName); + prevColor = defaultColor; + + this.className = className; + this.variableName = variableName; + this.displayName = display_name; + label = new JLabel(display_name); + this.order = nOrder; + + icon = new ColorIcon(defaultColor, null, dim.width, dim.height); + button = new JButton(icon); + button.setMargin(new Insets(0,0,0,0)); + button.addActionListener(this); + button.setToolTipText(""Click here to edit the color. Hover over label for definition.""); + label.setToolTipText(description); + } + + public ColorVariable(String className, String variableName, Color color) { + this.className = className; + this.variableName = variableName; + this.defaultColor = color; + this.prevColor = color; + } + + public boolean equals(Object obj) { + if (obj instanceof ColorVariable) { + return ( className.equals(((ColorVariable)obj).className) && + variableName.equals(((ColorVariable)obj).variableName) ); + } + return false; + } + public int getOrder() { return order; } + + // do not change; used to store changed color in cookie + public String toString() { + Color c = icon.getColor(); + return className+"".""+variableName+""=""+c.getRed()+"",""+c.getGreen()+"",""+c.getBlue()+"",""+c.getAlpha(); + } + + public boolean isDefault() { // writing cookie's + return (defaultColor != null && defaultColor.equals(icon.getColor())); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == button) { + colorChoose = new JColorChooser(); + colorChoose.setColor(icon.getColor()); + colorChoose.setChooserPanels(new AbstractColorChooserPanel[] { new SwatchChooserPanel(alphaEnabled), + new RGBAChooserPanel(alphaEnabled) } ); + dialog = JColorChooser.createDialog(button,label.getText(),true,colorChoose,this,null); + dialog.setVisible(true); + } + else { // ok button on color chooser + setIconColor(colorChoose.getColor()); + } + } + public void cancelColorChange() { + setIconColor(prevColor); + } + + public void setDefaultColor() { + setIconColor(defaultColor); + } + + public void commitColorChange() { + if (prevColor == null || !prevColor.equals(icon.getColor())) { + prevColor = icon.getColor(); + ColorDialog.setColor(className,variableName,prevColor); + } + } + + public void commitColorChange(ColorVariable cv) { // cv is temp obj from reading cookies + Color newColor = cv.prevColor; + setIconColor(newColor); + if (colorChoose != null) colorChoose.setColor(newColor); + prevColor = newColor; + ColorDialog.setColor(className, variableName, newColor); + } + + private void setIconColor(Color color) { + icon.setColor(color); + button.repaint(); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorIcon.java",".java","1418","53","package colordialog; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; + +import javax.swing.Icon; + +/** + * Class ColorIcon consists of a rectangular color with a possible icon displayed over that color. + * @see Icon + */ +public class ColorIcon implements Icon { + private Color color; + private Icon overIcon; + private int width, height; + + public ColorIcon(Color color, Icon over, int minWidth, int minHeight) { + this.color = color; + overIcon = over; + width = minWidth; + height = minHeight; + if (overIcon != null) { + if (overIcon.getIconWidth() > width) width = overIcon.getIconWidth(); + if (overIcon.getIconHeight() > height) height = overIcon.getIconHeight(); + } + } + + public Color getColor() { + return color; + } + public void setColor(Color color) { + this.color = color; + } + public int getIconWidth() { + return width; + } + public int getIconHeight() { + return height; + } + public void paintIcon(Component c, Graphics g, int x, int y) { + Color tcolor = g.getColor(); + g.setColor(color); + g.fillRect(x,y,getIconWidth(),getIconHeight()); + g.setColor(tcolor); + if (overIcon != null) { + int ox = (int)Math.round( x + ( (getIconWidth() - overIcon.getIconWidth() ) / 2.0 ) ); + int oy = (int)Math.round( y + ( (getIconHeight() - overIcon.getIconHeight()) / 2.0 ) ); + overIcon.paintIcon(c,g,ox,oy); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorDialog.java",".java","11222","363","package colordialog; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.Field; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Vector; +import java.util.Collections; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +import props.PersistentProps; +import props.PropertiesReader; +import symap.drawingpanel.SyMAP2d; +import util.ErrorReport; + +/** + * Class ColorDialog is used for editing the colors in a dialog box. + * For example, to add the color for pseudoLineColorPP: + * properties/color.properties + * symap.mapper.Mapper@pseudoLineColorPP + * In symap.mapper.Mapper.java + * it reads /properties/mapper.properties + * add pseudoLineColorPP as a public static variable and read it value + * /properties/mapper.properties + * add it to this file + * Add to appropriate code to use value, in this case, it was in PseudoPseudoHits.java + * + * Tabs are ordered by giving the variable name tab#, where # starts at 1, with the value of the tab name (i.e. tab1=Title on Tab). + * + * Tabs can be added by: + * Add tab in colors.properties and in pFiles below + */ +public class ColorDialog extends JDialog implements ActionListener { + private static final long serialVersionUID = 1L; + private static final String TAB = ""tab""; + private static final String VAR_SEP = "":""; + + private PersistentProps changedProps = null; + private String propName=""SyMapColors""; + + private JTabbedPane tabbedPane; + private JButton okButton, cancelButton, defaultButton; + + private final String propsFile = ""/properties/colors.properties""; + private String [] pFiles = {""annotation"", ""closeup"",""mapper"", ""sequence"", ""dotplot"", ""circle""}; + + static private HashMap colorDefs = new HashMap (); + + /* cookie - user/.symap_saved_props - changes to colors are stored here */ + public ColorDialog(PersistentProps cookie) { + super(); + + setModal(true); + setTitle(""SyMAP Color Editor""); + + if (cookie != null) changedProps = cookie.copy(propName); + + tabbedPane = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT); + + initDefaultProps(); + initPropColors(); + initCookieColors(); + + okButton = new JButton(""Save""); + cancelButton = new JButton(""Cancel""); + defaultButton = new JButton(""Default""); + JButton helpButton = util.Jhtml.createHelpIconUserSm(util.Jhtml.colorIcon); + + okButton.addActionListener(this); + cancelButton.addActionListener(this); + defaultButton.addActionListener(this); + + JPanel buttonPanel = new JPanel(); + buttonPanel.add(okButton); + buttonPanel.add(cancelButton); + buttonPanel.add(defaultButton); + buttonPanel.add(helpButton); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(tabbedPane,BorderLayout.CENTER); + getContentPane().add(buttonPanel,BorderLayout.SOUTH); + + pack(); + setBackground(Color.white); + setAlwaysOnTop(true); + Dimension dim = getToolkit().getScreenSize(); + setLocation(dim.width / 2,dim.height / 5); + } + + public void setDotplot() { + tabbedPane.setSelectedIndex(3); + } + public void setCircle() { + tabbedPane.setSelectedIndex(4); + } + + // read colors.properties + private void initPropColors() { + try { + Dimension iconDim = new Dimension(35,20); + + HashMap tabMap = new HashMap(); // initial structure of tabs + Vector cvarsVec = new Vector(); // displayname/colors + + String name, pvalue, dn, desc; + int ind, cInd, c2Ind; + int nOrder=0; + + // Read /properties file, symap lines - does not retain input order + PropertiesReader defaultProps = new PropertiesReader(SyMAP2d.class.getResource(propsFile)); + + Enumeration propertyNames = defaultProps.propertyNames(); + while (propertyNames.hasMoreElements()) { + name = (String)propertyNames.nextElement(); + if (name.startsWith(""tab"")) continue; // e.g. tab1=General + + pvalue = defaultProps.getString(name); + + ind = name.indexOf('@'); + if (ind < 0) { // e.g. symap.sequence.Sequence=Track + tabMap.put(name,pvalue); + } + else { // e.g. symap.sequence.Sequence@unitColor=Ruler,The color of the ruler text,1 + cInd = pvalue.indexOf(','); + c2Ind = pvalue.lastIndexOf(','); + + dn = pvalue; + desc = null; // description + + if (cInd > 0) { + dn = pvalue.substring(0,cInd).trim(); + if (c2Ind != cInd) { + desc = pvalue.substring(cInd+1, c2Ind).trim(); + nOrder = Integer.parseInt(pvalue.substring(c2Ind+1)); + } + else { + desc = pvalue.substring(cInd+1).trim(); + nOrder=0; + } + } + + String path = name.substring(0,ind); + String var = name.substring(ind+1); + cvarsVec.add(new ColorVariable(path,var,dn,desc,iconDim,nOrder)); + } + } + +// Tabs + // read tab lines, e.g. tab2=Sequence Track + HashMap tabOrderMap = new HashMap(); + for (ind = 1; ; ind++) { + name = (String) defaultProps.getString(TAB+ind); + if (name == null) break; + name = name.trim(); + + tabOrderMap.put(name, ind); + } + // Build tabs in order + Vector tabVec = new Vector(); + + for (ColorVariable colorVar : cvarsVec) { + name = (String)tabMap.get(colorVar.className); + ind = (tabOrderMap.get(name)==null) ? Integer.MAX_VALUE : tabOrderMap.get(name); + + ColorTab colorTab = new ColorTab(name, ind); + + ind = tabVec.indexOf(colorTab); + if (ind < 0) tabVec.add(colorTab); + else colorTab = (ColorTab)tabVec.get(ind); + + colorTab.addVariable(colorVar); + } + + Collections.sort(tabVec); // sort by order + + for (ColorTab colorTab : tabVec) { + tabbedPane.add(colorTab); + colorTab.setup(); + } + } + catch (Exception e) {ErrorReport.print(e, ""init prop colors"");} + } + + private void initDefaultProps() { + try { + for (String f : pFiles) { + String file = ""/properties/"" + f + "".properties""; + PropertiesReader defProps = new PropertiesReader(SyMAP2d.class.getResource(file)); + + Enumeration propertyNames = defProps.propertyNames(); + while (propertyNames.hasMoreElements()) { + String name = (String)propertyNames.nextElement(); + String pvalue = defProps.getString(name); + if (pvalue.contains("","")) { + Color cvalue = defProps.getColor(name); + colorDefs.put(name, cvalue); + } + } + } + } + catch (Exception e) {ErrorReport.print(e, ""init prop colors"");} + } + /************************************************************* + * SyMapColors=symap.mapper.Mapper.pseudoLineColorNN\=153,0,153,255 + */ + private void initCookieColors() { + String cookie = (changedProps != null) ? changedProps.getProp() : null; + if (cookie == null || cookie.length() == 0) return; + + String[] variables = cookie.split(VAR_SEP); + String cn, vn, c, cvars[]; + int pind, eind, r, g, b, a; + for (int i = 0; i < variables.length; i++) { + try { + pind = variables[i].lastIndexOf('.'); // name shown beside color box + eind = variables[i].indexOf('='); + if (pind < 0 || eind < pind) { + System.out.println(""Illegal Variable Found [""+variables[i]+""]!!!!""); + } + else { + cn = variables[i].substring(0,pind); // path + vn = variables[i].substring(pind+1,eind); + c = variables[i].substring(eind+1); + cvars = c.split("",""); + if (cvars.length < 3 || cvars.length > 4) { + System.out.println(""Invalid Color Variable: [""+c+""]""); + } + else { + r = Integer.parseInt(cvars[0]); + g = Integer.parseInt(cvars[1]); + b = Integer.parseInt(cvars[2]); + if (cvars.length == 4) a = Integer.parseInt(cvars[3]); + else a = 255; + + changeCookieColor(new ColorVariable(cn,vn,new Color(r,g,b,a))); + } + } + } + catch (Exception e) { + ErrorReport.print(e, ""Exception Parsing Color Variable [""+variables[i]+""]!!!""); + } + } + } + private void changeCookieColor(ColorVariable cv) { // called from right above reading properties + Component[] comps = tabbedPane.getComponents(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof ColorTab) { + if (((ColorTab)comps[i]).changeColor(cv)) break; + } + } + } + + /****************************************************************/ + public void actionPerformed(ActionEvent e) { + if (e.getSource() == okButton) { + okAction(); + setCookie(); + setVisible(false); + } + else if (e.getSource() == cancelButton) { + cancelAction(); + setVisible(false); + } + else if (e.getSource() == defaultButton) { + defaultAction(); + } + } + + protected void cancelAction() { + Component[] comps = tabbedPane.getComponents(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof ColorTab) + ((ColorTab)comps[i]).cancel(); + } + } + protected void okAction() { + Component[] comps = tabbedPane.getComponents(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof ColorTab) + ((ColorTab)comps[i]).commit(); + } + } + + protected void defaultAction() { + try { + Component c = tabbedPane.getSelectedComponent(); + ((ColorTab) c).setDefault(); + } + catch (Exception e) { + ErrorReport.print(e, ""This feature does not work on this machine. Setting all defaults. (Please email symap@agcol.arizona.edu)""); + Component[] comps = tabbedPane.getComponents(); + for (int i = 0; i < comps.length; i++) + if (comps[i] instanceof ColorTab) + ((ColorTab)comps[i]).setDefault(); + } + } + + /* write change to user.home/.symap_prop; called after any changed colors; called on Ok */ + private void setCookie() { + if (changedProps == null) return; + + Component[] comps = tabbedPane.getComponents(); + Vector v = new Vector(); + for (int i = 0; i < comps.length; i++) { + if (comps[i] instanceof ColorTab) { + v.addAll(((ColorTab)comps[i]).getChangedVariables()); + } + } + Iterator iter = v.iterator(); + StringBuffer cookie = new StringBuffer(); + ColorVariable cv; + for (int i = v.size(); i > 0; i--) { + cv = iter.next(); + cookie.append(cv.toString()); + if (i > 1) cookie.append(VAR_SEP); + } + if (v.size() > 0) changedProps.setProp(cookie.toString()); + else changedProps.deleteProp(); + } + /******************************************************** + * Writes to static color variables in the specified file; called by ColorVariable on change + */ + protected static boolean setColor(String className, String variableName, Color color) { + try { + Class c = Class.forName(className); + Field f = c.getField(variableName); + f.set(null,color); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""set color""); return false;} + } + + protected static Color getColor(String className, String variableName) { + Color color = null; + try { + Class c = Class.forName(className); + Field f = c.getField(variableName); + color = (Color)f.get(null); + } + catch (Exception e) {ErrorReport.print(e, ""get color""); } + return color; + } + + protected static Color getDefault(String var) { + if (!colorDefs.containsKey(var)) { + System.out.println(""Not found "" + var); + return Color.black; + } + return colorDefs.get(var); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorListener.java",".java","195","9","package colordialog; + +/** + * Interface ColorListener can be used by the color dialog to notify objects when a change occurs. + */ +public interface ColorListener { + public void resetColors(); +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorTab.java",".java","2664","112","package colordialog; + +import javax.swing.JPanel; +import java.awt.BorderLayout; +import javax.swing.BoxLayout; +import java.awt.GridLayout; +import java.util.Vector; + +class ColorTab extends JPanel implements Comparable { + private static final long serialVersionUID = 1L; + private Vector cvVec; + private int nRows=3; + private int order; + + protected ColorTab(String tabName, int order) { + super(new BorderLayout()); + + setName(tabName); + cvVec = new Vector(); + this.order = order; + } + + public int compareTo(ColorTab t) { + return order - t.order; + } + + public void addVariable(ColorVariable cv) { + cvVec.add(cv); + } + + public void setup() { + removeAll(); + + int nCells = cvVec.size(); + int nCols = nCells / nRows; + if (nCells % nRows != 0) nCols++; + + setLayout(new GridLayout(1, nRows)); + + // this assumes the order# are correctly entered in colors.properties 1-size + ColorVariable [] orderComps = new ColorVariable [nCells]; + for (int i=0; i getChangedVariables() { + Vector v = new Vector(); + for (ColorVariable cv : cvVec) + if (!cv.isDefault()) v.add(cv); + return v; + } + + public boolean equals(Object obj) { + if (obj instanceof ColorTab) { + return getName().equals(((ColorTab)obj).getName()); + } + else if (obj instanceof String) { + return getName().equals(obj); + } + return false; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/ColorDialogHandler.java",".java","2321","93","package colordialog; + +import java.util.Vector; +import java.util.Iterator; +import java.lang.ref.WeakReference; + +import props.PersistentProps; + +/** + * The shows and setting of colors of a color dialog box. + */ +public class ColorDialogHandler { + + private Vector> listeners; + + private PersistentProps cookie; // read from file + private ColorDialog dialog = null; + + /** + * Created in circview.ControlPanelCirc, dotplot.DotPlotFrame, drawingPanel.SyMAP2d + * cookie - in user's directory file .symap_saved_props + */ + public ColorDialogHandler(PersistentProps cookie) { + listeners = new Vector>(); + this.cookie = cookie; + setColors(); + } + // frame.ControlPanel calls when color icon clicked + public void showX() { + if (dialog == null) dialog = new ColorDialog(cookie); + dialog.setVisible(true); + notifyListeners(); + } + + public void setDotPlot() { + dialog.setDotplot(); + } + public void setCircle() { + dialog.setCircle(); + } + private void setColors() { + if (dialog != null) { + dialog.setVisible(false); + dialog.defaultAction(); + dialog.okAction(); + } + dialog = new ColorDialog(cookie); + notifyListeners(); + } + + /* adds listener to the list of objects listening to this dialog. The + * listener's resetColors() method is called when the colors change. + */ + public void addListener(ColorListener listener) { + ColorListener l; + Iterator> iter = listeners.iterator(); + while (iter.hasNext()) { + l = iter.next().get(); + if (l == null) iter.remove(); + else if (l.equals(listener)) return ; + } + listeners.add(new WeakReference(listener)); + } + + public void removeListener(ColorListener listener) { + ColorListener l; + Iterator> iter = listeners.iterator(); + while (iter.hasNext()) { + l = iter.next().get(); + if (l == null) iter.remove(); + else if (l.equals(listener)) { + iter.remove(); + break; + } + } + } + + public void removeAllListeners() { + listeners.clear(); + } + + private synchronized void notifyListeners() { + Iterator> iter = listeners.iterator(); + ColorListener l; + while (iter.hasNext()) { + l = iter.next().get(); + if (l == null) iter.remove(); + else l.resetColors(); + } + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/RGBAChooserPanel.java",".java","5829","162","package colordialog; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; + +import javax.swing.Icon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import javax.swing.colorchooser.AbstractColorChooserPanel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + * Class RGBAChooserPanel is based of of the DefaultRGBChooserPanel with + * an added slider and spinner for the alpha value (optional). + */ +public class RGBAChooserPanel extends AbstractColorChooserPanel implements ChangeListener { + private static final long serialVersionUID = 1L; + private static final int MIN_VALUE = 0; + private static final int MAX_VALUE = 255; + + private JSlider redSlider, greenSlider, blueSlider, alphaSlider; + private JSpinner redSpinner, greenSpinner, blueSpinner, alphaSpinner; + + private boolean isLocked; + private boolean doAlpha; + + public RGBAChooserPanel() { + this(true); + } + public RGBAChooserPanel(boolean alphaEnabled) { + super(); + doAlpha = alphaEnabled; + isLocked = false; + } + public String getDisplayName() { + return ""RGBA""; + } + public Icon getSmallDisplayIcon() { + return null; + } + public Icon getLargeDisplayIcon() { + return null; + } + + protected void buildChooser() { + setLayout(new BorderLayout()); + Color color = getColorFromModel(); + + GridBagLayout gridbag = new GridBagLayout(); + JPanel panel = new JPanel(gridbag); + GridBagConstraints constraints = new GridBagConstraints(); + + constraints.fill = GridBagConstraints.NONE; + constraints.gridheight = 1; + constraints.ipadx = 10; + constraints.ipady = 10; + + add(panel, BorderLayout.CENTER); + + redSlider = createSlider(color.getRed()); + redSpinner = createSpinner(color.getRed()); + setRow(new JLabel(""Red""),redSlider,redSpinner,panel,gridbag,constraints); + + greenSlider = createSlider(color.getGreen()); + greenSpinner = createSpinner(color.getGreen()); + setRow(new JLabel(""Green""),greenSlider,greenSpinner,panel,gridbag,constraints); + + blueSlider = createSlider(color.getBlue()); + blueSpinner = createSpinner(color.getBlue()); + setRow(new JLabel(""Blue""),blueSlider,blueSpinner,panel,gridbag,constraints); + + alphaSlider = createSlider(color.getAlpha()); + alphaSpinner = createSpinner(color.getAlpha()); + if (doAlpha) setRow(new JLabel(""Alpha""),alphaSlider,alphaSpinner,panel,gridbag,constraints); + } + + /* updates the sliders and spinners based on the current color.*/ + public void updateChooser() { + if (!isLocked) { + isLocked = true; + + Color color = getColorFromModel(); + int red = color.getRed(); + int blue = color.getBlue(); + int green = color.getGreen(); + int alpha = color.getAlpha(); + + if (redSlider.getValue() != red) redSlider.setValue(red); + if (greenSlider.getValue() != green)greenSlider.setValue(green); + if (blueSlider.getValue() != blue) blueSlider.setValue(blue); + if (alphaSlider.getValue() != alpha)alphaSlider.setValue(alpha); + + if (((Integer)redSpinner.getValue()).intValue() != red) + redSpinner.setValue(red); + if (((Integer)greenSpinner.getValue()).intValue() != green) + greenSpinner.setValue(green); + if (((Integer)blueSpinner.getValue()).intValue() != blue) + blueSpinner.setValue(blue); + if (((Integer)alphaSpinner.getValue()).intValue() != alpha) + alphaSpinner.setValue(alpha); + + isLocked = false; + } + } + + /* handles the changing of sliders and spinner */ + public void stateChanged(ChangeEvent e) { + if (!isLocked) { + if (e.getSource() instanceof JSlider) { + Color color = new Color(redSlider.getValue(),greenSlider.getValue(),blueSlider.getValue(),alphaSlider.getValue()); + getColorSelectionModel().setSelectedColor(color); + } + else if (e.getSource() instanceof JSpinner) { + int red = ((Integer)redSpinner.getValue()).intValue(); + int green = ((Integer)greenSpinner.getValue()).intValue(); + int blue = ((Integer)blueSpinner.getValue()).intValue(); + int alpha = ((Integer)alphaSpinner.getValue()).intValue(); + getColorSelectionModel().setSelectedColor(new Color(red,green,blue,alpha)); + } + } + } + private void setRow(JLabel label, JSlider slider, JSpinner spinner, JPanel panel, + GridBagLayout layout, GridBagConstraints constraints) { + addToGrid(panel,layout,constraints,new JLabel(),1); + constraints.anchor = GridBagConstraints.EAST; + addToGrid(panel,layout,constraints,label,1); + constraints.anchor = GridBagConstraints.CENTER; + addToGrid(panel,layout,constraints,slider,3); + constraints.anchor = GridBagConstraints.WEST; + addToGrid(panel,layout,constraints,spinner,1); + addToGrid(panel,layout,constraints,new JLabel(),GridBagConstraints.REMAINDER); + } + private void addToGrid(Container cp, GridBagLayout layout, GridBagConstraints constraints, Component comp, int width) { + constraints.gridwidth = width; + layout.setConstraints(comp, constraints); + cp.add(comp); + } + private JSlider createSlider(int value) { + JSlider slider = new JSlider(JSlider.HORIZONTAL,MIN_VALUE,MAX_VALUE,value); + slider.setMajorTickSpacing(85); + slider.setMinorTickSpacing(17); + slider.setPaintTicks(true); + slider.setPaintLabels(true); + slider.addChangeListener(this); + return slider; + } + private JSpinner createSpinner(int value) { + JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, MIN_VALUE, MAX_VALUE, 1)); + spinner.addChangeListener(this); + return spinner; + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/colordialog/SwatchChooserPanel.java",".java","13256","564","package colordialog; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.Icon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import javax.swing.UIManager; +import javax.swing.border.Border; +import javax.swing.border.CompoundBorder; +import javax.swing.border.EmptyBorder; +import javax.swing.border.LineBorder; +import javax.swing.colorchooser.AbstractColorChooserPanel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + * Class SwatchChooserPanel is based off of the DefaultSwatchChooserPanel with + * an added slider and spinner for Alpha values (optional). + */ +public class SwatchChooserPanel extends AbstractColorChooserPanel implements ChangeListener, MouseListener { + private static final long serialVersionUID = 1L; + private MainSwatchPanel swatchPanel; + private RecentSwatchPanel recentSwatchPanel; + private JSlider alphaSlider; + private JSpinner alphaSpinner; + private boolean isLocked; // for stopping an endless loop of changing the slider and updating the colors + private boolean doAlpha; // not allowing alpha changes + + public SwatchChooserPanel() { + this(true); + } + public SwatchChooserPanel(boolean alphaEnabled) { + super(); + doAlpha = alphaEnabled; + isLocked = false; + } + + public String getDisplayName() { + return ""Swatches""; + } + public Icon getSmallDisplayIcon() { + return null; + } + public Icon getLargeDisplayIcon() { + return null; + } + protected void buildChooser() { + int alpha = getColorFromModel().getAlpha(); + + alphaSlider = new JSlider(JSlider.HORIZONTAL,0,255,alpha); + alphaSlider.setMajorTickSpacing(85); + alphaSlider.setMinorTickSpacing(17); + alphaSlider.setPaintTicks(true); + alphaSlider.setPaintLabels(true); + alphaSlider.addChangeListener(this); + + alphaSpinner = new JSpinner(new SpinnerNumberModel(alpha,0,255,1)); + alphaSpinner.addChangeListener(this); + + JPanel alphaRow = new JPanel(); + alphaRow.add(new JLabel(""Alpha"")); + alphaRow.add(alphaSlider); + alphaRow.add(alphaSpinner); + + swatchPanel = new MainSwatchPanel(alpha); + recentSwatchPanel = new RecentSwatchPanel(); + + swatchPanel.addMouseListener(this); + recentSwatchPanel.addMouseListener(this); + + JPanel superHolder = new JPanel(new BorderLayout()); + JPanel mainHolder = new JPanel(new BorderLayout()); + Border border = new CompoundBorder(new LineBorder(Color.black),new LineBorder(Color.white)); + + mainHolder.setBorder(border); + mainHolder.add(swatchPanel,BorderLayout.CENTER); + superHolder.add(mainHolder,BorderLayout.CENTER); + + JPanel recentHolder = new JPanel(new BorderLayout()); + recentHolder.setBorder(border); + recentHolder.add(recentSwatchPanel, BorderLayout.CENTER); + JPanel recentLabelHolder = new JPanel(new BorderLayout()); + recentLabelHolder.add(recentHolder, BorderLayout.CENTER); + recentLabelHolder.add(new JLabel(""Recent:""), BorderLayout.NORTH); + JPanel recentHolderHolder = new JPanel(new BorderLayout()); + if (this.getComponentOrientation().isLeftToRight()) { + recentHolderHolder.setBorder(new EmptyBorder(2,10,2,2)); + } + else { + recentHolderHolder.setBorder(new EmptyBorder(2,2,2,10)); + } + recentHolderHolder.add(recentLabelHolder,BorderLayout.CENTER); + superHolder.add(recentHolderHolder,BorderLayout.AFTER_LINE_ENDS); + + if (doAlpha) superHolder.add(alphaRow,BorderLayout.SOUTH); + + add(superHolder); + } + + /* handles the changing of the alpha slider and alpha spinner. */ + public void stateChanged(ChangeEvent e) { + if (!isLocked && e.getSource() == alphaSlider || e.getSource() == alphaSpinner) { + Color c = getColorFromModel(); + int alpha; + if (e.getSource() == alphaSlider) { + alpha = alphaSlider.getValue(); + } + else { // e.getSource() == alphaSpinner + alpha = ((Integer)alphaSpinner.getValue()).intValue(); + } + swatchPanel.changeAlpha(alpha); + swatchPanel.repaint(); + getColorSelectionModel().setSelectedColor(new Color(c.getRed(),c.getGreen(),c.getBlue(),alpha)); + } + } + public void updateChooser() { + if (!isLocked) { + isLocked = true; + + int alpha = getColorFromModel().getAlpha(); + alphaSlider.setValue(alpha); + alphaSpinner.setValue(alpha); + + isLocked = false; + } + } + + /* handles the mouse clicking on spots in the main color grid and the recent color grid. */ + public void mousePressed(MouseEvent e) { + if (e.getSource() == recentSwatchPanel) { + Color color = recentSwatchPanel.getColorForLocation(e.getX(), e.getY()); + getColorSelectionModel().setSelectedColor(color); + } + else if (e.getSource() == swatchPanel) { + Color color = swatchPanel.getColorForLocation(e.getX(), e.getY()); + getColorSelectionModel().setSelectedColor(color); + recentSwatchPanel.setMostRecentColor(color); + } + } + + public void mouseClicked(MouseEvent e) { } + public void mouseEntered(MouseEvent e) { } + public void mouseExited(MouseEvent e) { } + public void mouseReleased(MouseEvent e) { } +} + + +abstract class SwatchPanel extends JPanel { + private static final long serialVersionUID = 1L; + protected Color[] colors; + protected Dimension swatchSize, numSwatches, gap; + + public SwatchPanel() { + initValues(); + initColors(); + setToolTipText(""""); // register for events + setOpaque(true); + setBackground(Color.white); + setRequestFocusEnabled(false); + } + + protected abstract void initValues(); + protected abstract void initColors(); + + public void paintComponent(Graphics g) { + g.setColor(getBackground()); + g.fillRect(0,0,getWidth(), getHeight()); + for (int row = 0; row < numSwatches.height; row++) { + for (int column = 0; column < numSwatches.width; column++) { + g.setColor( getColorForCell(column, row) ); + int x; + if ((!this.getComponentOrientation().isLeftToRight()) && + (this instanceof RecentSwatchPanel)) { + x = (numSwatches.width - column - 1) * (swatchSize.width + gap.width); + } + else { + x = column * (swatchSize.width + gap.width); + } + int y = row * (swatchSize.height + gap.height); + g.fillRect(x, y, swatchSize.width, swatchSize.height); + g.setColor(Color.black); + g.drawLine(x+swatchSize.width-1, y, x+swatchSize.width-1, y+swatchSize.height-1); + g.drawLine(x, y+swatchSize.height-1, x+swatchSize.width-1, y+swatchSize.height-1); + } + } + } + + public Dimension getPreferredSize() { + int x = numSwatches.width * (swatchSize.width + gap.width) - 1; + int y = numSwatches.height * (swatchSize.height + gap.height) - 1; + return new Dimension(x,y); + } + + public String getToolTipText(MouseEvent e) { + Color color = getColorForLocation(e.getX(), e.getY()); + return color.getRed()+"", ""+ color.getGreen() + "", "" + color.getBlue(); + } + + public Color getColorForLocation(int x, int y) { + int column; + if ((!this.getComponentOrientation().isLeftToRight()) && + (this instanceof RecentSwatchPanel)) { + column = numSwatches.width - x / (swatchSize.width + gap.width) - 1; + } else { + column = x / (swatchSize.width + gap.width); + } + int row = y / (swatchSize.height + gap.height); + return getColorForCell(column, row); + } + + private Color getColorForCell( int column, int row) { + return colors[ (row * numSwatches.width) + column ]; + } +} + +class RecentSwatchPanel extends SwatchPanel { + private static final long serialVersionUID = 1L; + + protected void initValues() { + swatchSize = UIManager.getDimension(""ColorChooser.swatchesRecentSwatchSize""); + numSwatches = new Dimension(5,7); + gap = new Dimension(1,1); + } + + protected void initColors() { + Color defaultRecentColor = UIManager.getColor(""ColorChooser.swatchesDefaultRecentColor""); + int numColors = numSwatches.width * numSwatches.height; + + colors = new Color[numColors]; + for (int i = 0; i < numColors ; i++) { + colors[i] = defaultRecentColor; + } + } + + public void setMostRecentColor(Color c) { + System.arraycopy(colors, 0, colors, 1, colors.length-1); + colors[0] = c; + repaint(); + } +} + +class MainSwatchPanel extends SwatchPanel { + private static final long serialVersionUID = 1L; + + public MainSwatchPanel(int alpha) { + super(); + changeAlpha(alpha); + } + + public void changeAlpha(int alpha) { + Color old; + for (int i = 0; i < colors.length; i++) { + old = colors[i]; + if (old != null) + colors[i] = new Color(old.getRed(),old.getGreen(),old.getBlue(),alpha); + } + } + + protected void initValues() { + swatchSize = UIManager.getDimension(""ColorChooser.swatchesSwatchSize""); + numSwatches = new Dimension(31,9); + gap = new Dimension(1,1); + } + + protected void initColors() { + int numColors = rawValues.length / 3; + + colors = new Color[numColors]; + for (int i = 0; i < numColors ; i++) { + colors[i] = new Color(rawValues[(i*3)], rawValues[(i*3)+1], rawValues[(i*3)+2]); + } + } + + private static int[] rawValues = { + 255, 255, 255, // first row. + 204, 255, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 204, 204, 255, + 255, 204, 255, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 204, 204, + 255, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 255, 204, + 204, 204, 204, // second row. + 153, 255, 255, + 153, 204, 255, + 153, 153, 255, + 153, 153, 255, + 153, 153, 255, + 153, 153, 255, + 153, 153, 255, + 153, 153, 255, + 153, 153, 255, + 204, 153, 255, + 255, 153, 255, + 255, 153, 204, + 255, 153, 153, + 255, 153, 153, + 255, 153, 153, + 255, 153, 153, + 255, 153, 153, + 255, 153, 153, + 255, 153, 153, + 255, 204, 153, + 255, 255, 153, + 204, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 153, + 153, 255, 204, + 204, 204, 204, // third row + 102, 255, 255, + 102, 204, 255, + 102, 153, 255, + 102, 102, 255, + 102, 102, 255, + 102, 102, 255, + 102, 102, 255, + 102, 102, 255, + 153, 102, 255, + 204, 102, 255, + 255, 102, 255, + 255, 102, 204, + 255, 102, 153, + 255, 102, 102, + 255, 102, 102, + 255, 102, 102, + 255, 102, 102, + 255, 102, 102, + 255, 153, 102, + 255, 204, 102, + 255, 255, 102, + 204, 255, 102, + 153, 255, 102, + 102, 255, 102, + 102, 255, 102, + 102, 255, 102, + 102, 255, 102, + 102, 255, 102, + 102, 255, 153, + 102, 255, 204, + 153, 153, 153, // fourth row + 51, 255, 255, + 51, 204, 255, + 51, 153, 255, + 51, 102, 255, + 51, 51, 255, + 51, 51, 255, + 51, 51, 255, + 102, 51, 255, + 153, 51, 255, + 204, 51, 255, + 255, 51, 255, + 255, 51, 204, + 255, 51, 153, + 255, 51, 102, + 255, 51, 51, + 255, 51, 51, + 255, 51, 51, + 255, 102, 51, + 255, 153, 51, + 255, 204, 51, + 255, 255, 51, + 204, 255, 51, + 153, 244, 51, + 102, 255, 51, + 51, 255, 51, + 51, 255, 51, + 51, 255, 51, + 51, 255, 102, + 51, 255, 153, + 51, 255, 204, + 153, 153, 153, // Fifth row + 0, 255, 255, + 0, 204, 255, + 0, 153, 255, + 0, 102, 255, + 0, 51, 255, + 0, 0, 255, + 51, 0, 255, + 102, 0, 255, + 153, 0, 255, + 204, 0, 255, + 255, 0, 255, + 255, 0, 204, + 255, 0, 153, + 255, 0, 102, + 255, 0, 51, + 255, 0 , 0, + 255, 51, 0, + 255, 102, 0, + 255, 153, 0, + 255, 204, 0, + 255, 255, 0, + 204, 255, 0, + 153, 255, 0, + 102, 255, 0, + 51, 255, 0, + 0, 255, 0, + 0, 255, 51, + 0, 255, 102, + 0, 255, 153, + 0, 255, 204, + 102, 102, 102, // sixth row + 0, 204, 204, + 0, 204, 204, + 0, 153, 204, + 0, 102, 204, + 0, 51, 204, + 0, 0, 204, + 51, 0, 204, + 102, 0, 204, + 153, 0, 204, + 204, 0, 204, + 204, 0, 204, + 204, 0, 204, + 204, 0, 153, + 204, 0, 102, + 204, 0, 51, + 204, 0, 0, + 204, 51, 0, + 204, 102, 0, + 204, 153, 0, + 204, 204, 0, + 204, 204, 0, + 204, 204, 0, + 153, 204, 0, + 102, 204, 0, + 51, 204, 0, + 0, 204, 0, + 0, 204, 51, + 0, 204, 102, + 0, 204, 153, + 0, 204, 204, + 102, 102, 102, // seventh row + 0, 153, 153, + 0, 153, 153, + 0, 153, 153, + 0, 102, 153, + 0, 51, 153, + 0, 0, 153, + 51, 0, 153, + 102, 0, 153, + 153, 0, 153, + 153, 0, 153, + 153, 0, 153, + 153, 0, 153, + 153, 0, 153, + 153, 0, 102, + 153, 0, 51, + 153, 0, 0, + 153, 51, 0, + 153, 102, 0, + 153, 153, 0, + 153, 153, 0, + 153, 153, 0, + 153, 153, 0, + 153, 153, 0, + 102, 153, 0, + 51, 153, 0, + 0, 153, 0, + 0, 153, 51, + 0, 153, 102, + 0, 153, 153, + 0, 153, 153, + 51, 51, 51, // eigth row + 0, 102, 102, + 0, 102, 102, + 0, 102, 102, + 0, 102, 102, + 0, 51, 102, + 0, 0, 102, + 51, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 102, + 102, 0, 51, + 102, 0, 0, + 102, 51, 0, + 102, 102, 0, + 102, 102, 0, + 102, 102, 0, + 102, 102, 0, + 102, 102, 0, + 102, 102, 0, + 102, 102, 0, + 51, 102, 0, + 0, 102, 0, + 0, 102, 51, + 0, 102, 102, + 0, 102, 102, + 0, 102, 102, + 0, 0, 0, // ninth row + 0, 51, 51, + 0, 51, 51, + 0, 51, 51, + 0, 51, 51, + 0, 51, 51, + 0, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 51, + 51, 0, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 51, 51, 0, + 0, 51, 0, + 0, 51, 51, + 0, 51, 51, + 0, 51, 51, + 0, 51, 51, + 51, 51, 51 }; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AnnotLoadMain.java",".java","17050","510","package backend; + +import java.io.BufferedReader; +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.TreeMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.util.Comparator; +import java.util.HashSet; +import java.sql.PreparedStatement; + +import database.DBconn2; +import symap.Globals; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ProgressDialog; +import util.Utilities; +import util.ErrorReport; + +/*********************************************** + * Load gff files for sequence projects: recognize gene, mRNA, exon, gap, centromere + * Allows reading of NCBI and Ensembl files directly. + */ + +public class AnnotLoadMain { + private final String idKey = ""ID""; // Gene and mRNA + private final String parentKey = ""Parent""; // mRNA and Exon + + private ProgressDialog plog; + private DBconn2 tdbc2; + private Mproject mProj; // contains chromosomes and the grpIdx from reading FASTA + + private TreeMap typeCounts = new TreeMap();; + + // init + private Vector annotFiles = new Vector(); + + private final String exonAttr = ""Parent""; // save exon attribute; + private TreeMap userAttr = new TreeMap (); + private TreeMap ignoreAttr = new TreeMap (); + private int userSetMinKeywordCnt=0; + private boolean bUserSetKeywords = false; + private final int savAtLeastKeywords=10; // These are columns in SyMAP Query + + private boolean bSuccess=true; + private int cntAllGene=0 , cntNoKey=0; + + protected AnnotLoadMain(DBconn2 dbc2, ProgressDialog log, Mproject proj) throws Exception { + this.tdbc2 = new DBconn2(""AnnoLoad-""+ DBconn2.getNumConn(), dbc2);; + this.plog = log; + this.mProj = proj; + proj.loadDataFromDB(); + } + + protected boolean run(String projDBName) throws Exception { + long startTime = Utils.getTime(); + + plog.msg(""Loading annotation for "" + projDBName); + + initFromParams(projDBName); if (!bSuccess) {tdbc2.close(); return false; }; + + if (annotFiles.size()==0) { + Utils.prtMsgFile(plog, ""Finish annotation""); + tdbc2.executeUpdate(""delete from annot_key where proj_idx="" + mProj.getIdx()); + tdbc2.close(); + return true; + } + +/*** LOAD FILE ***/ + int nFiles = 0; + + long time = Utils.getTimeMem(); + + for (File af : annotFiles) { + nFiles++; + loadFile(af); if (!bSuccess) {tdbc2.close(); return false; } + } + Utils.prtTimeMemUsage(plog, (nFiles + "" file(s) loaded""), time); + +/** Compute gene order **/ + plog.msg(""Computations for "" + projDBName); + time = Utils.getTimeMem(); + + AnnotLoadPost alp = new AnnotLoadPost(mProj, tdbc2, plog); + + bSuccess = alp.run(cntAllGene>0); if (!bSuccess) {tdbc2.close(); return false; } + Utils.prtTimeMemUsage(plog, ""Finish computations"", time); + +/** Wrap up **/ + summary(); if (!bSuccess) {tdbc2.close(); return false; } + Utils.prtMsgTimeDone(plog, ""Finish annotation for "" + projDBName + "" "", startTime); + + tdbc2.close(); + return true; + } + /************************************************************************8 + * Load file and write to DB + */ + private void loadFile(File f) throws Exception { + int grpIdx=0; + try { + plog.msg(""Loading "" + f.getName()); + BufferedReader fh = Utils.openGZIP(f.getAbsolutePath()); + + String line; + int lineNum = 0, cntBatch=0, totalLoaded = 0, numParseErrors = 0; + HashSet noGrpSet = new HashSet (); + + int cntSkipMRNA=0, cntSkipGeneAttr=0, cntGene=0, cntExon=0; + + int lastGeneIdx = -1; // keep track of the last gene idx to be inserted + int lastIdx = tdbc2.getIdx(""select max(idx) from pseudo_annot""); + String geneID=null, mrnaID=null; + + PreparedStatement ps = tdbc2.prepareStatement(""insert into pseudo_annot "" + + ""(grp_idx,type,name,start,end,strand,gene_idx, genenum,tag) "" + + ""values (?,?,?,?,?,?,?,0,'')""); + while ((line = fh.readLine()) != null) { + if (Cancelled.isCancelled()) { + plog.msg(""User cancelled""); + bSuccess=false; + break; + } + + lineNum++; + if (line.startsWith(""#"")) continue; // skip comment + if (Utilities.isEmpty(line.trim())) continue; + + String[] fs = line.split(""\t""); + if (fs.length < 9) { + ErrorCount.inc(); + numParseErrors++; + if (numParseErrors <= 3) { + plog.msgToFile(""*** Parse: expecting at least 9 tab-delimited fields in gff file at line "" + lineNum); + if (numParseErrors >= 3) plog.msgToFile(""*** Suppressing further parse errors""); + } + continue; // skip this annotation + } + String chr = fs[0]; + //String source = fs[1]; // ignored + String type = sqlSanitize(fs[2]); + int start = Integer.parseInt(fs[3]); + int end = Integer.parseInt(fs[4]); + String strand = fs[6]; + String attr = sqlSanitize(fs[8]); + + if (strand == null || (!strand.equals(""-"") && !strand.equals(""+""))) strand = ""+""; + + /** Type: After count, discard unsupported types **/ + if (type == null || type.length() == 0) type = ""unknown""; + else if (type.length() > 20) type = type.substring(0, 20); + + if (!typeCounts.containsKey(type)) typeCounts.put(type, 1); + else typeCounts.put(type, 1 + typeCounts.get(type)); + + /** only use exons from first mRNA **/ + boolean isGene = (type.contentEquals(Globals.geneType)) ? true : false; + boolean isExon = (type.contentEquals(Globals.exonType)) ? true : false; + boolean isMRNA = (type.contentEquals(""mRNA"")) ? true : false; // this is nowhere else + boolean isGap = (type.contentEquals(Globals.gapType)) ? true : false; + boolean isCent = (type.contentEquals(Globals.centType)) ? true : false; + if (!(isGene || isExon || isMRNA || isGap || isCent)) continue; + + String[] keyVals = attr.split("";""); + + if (isGene) { + mrnaID = null; + geneID = getVal(idKey, keyVals); + } + else if (isMRNA) { + if (geneID!=null && mrnaID==null) { + mrnaID = getmRNAid(geneID, keyVals, lineNum, line); + if (!bSuccess) return; + } + else if (geneID!=null) cntSkipMRNA++; + continue; + } + else if (isExon) { + if (mrnaID==null) continue; + + if (!isGoodExon(mrnaID, keyVals, lineNum, line)) { + if (!bSuccess) return; + continue; + } + } + // else isGap or isCent + + /** Process for write **/ + // Chromosome idx + grpIdx = mProj.getGrpIdxRmPrefix(chr); + if (grpIdx < 0) {// this is not an error; can happen if scaffolds have been filtered out + if (!noGrpSet.contains(chr)) { + if (noGrpSet.size() < 3) plog.msgToFile(""+++ Gene on sequence '"" + chr + ""'; sequence is not loaded - ignore""); + else if (noGrpSet.size() == 3) plog.msgToFile(""+++ Suppressing further warnings of no loaded sequence""); + if (noGrpSet.size()==0) System.out.println(""Valid names: "" + mProj.getValidGroup()); + noGrpSet.add(chr); + } + continue; // skip this annotation + } + // Swap coordinates so that start is always less than end. + if (start > end) { + int tmp = start; + start = end; + end = tmp; + } + // Annotation Keywords + String parsedAttr=""""; // MySQL text: Can hold up to 65k + + if (isGene) { // create string of only user-supplied keywords; + cntGene++; + lastGeneIdx = (lastIdx+1); // for exon + + for (String kv : keyVals) { + String[] words = kv.trim().split(""=""); // if no '=', then no keyword + if (words.length!=2) { + if (!kv.trim().isEmpty()) { // happens with convert no desc; two ;; + cntSkipGeneAttr++; + if (cntSkipGeneAttr<2) symap.Globals.tprt(line); + } + continue; + } + String key = words[0].trim(); + if (key.equals("""")) continue; + + if (bUserSetKeywords) { + if (userAttr.containsKey(key)) { + userAttr.put(key, 1 + userAttr.get(key)); + parsedAttr += kv.trim() + "";""; + } + else { + if (!ignoreAttr.containsKey(key)) ignoreAttr.put(key, 0); + ignoreAttr.put(key, 1 + ignoreAttr.get(key)); + } + } + else { // no keywords excluded + if (!userAttr.containsKey(key)) userAttr.put(key, 0); + userAttr.put(key, 1 + userAttr.get(key)); + } + } + if (bUserSetKeywords) { + if (parsedAttr.endsWith("";"")) + parsedAttr = parsedAttr.substring(0, parsedAttr.length()-1); // remove ; at end + } + else parsedAttr = attr; // no keywords excluded + + if (parsedAttr.equals("""")) parsedAttr=""[no description]""; + } + else if (isExon) { // using parent or first; + cntExon++; + + for (String kv : keyVals) { + String[] words = kv.trim().split(""=""); + String key = words[0].trim(); + if (words.length!=2) continue; + if (key.equals("""")) continue; + + if (key.endsWith(""="")) + key = key.substring(0,key.length() - 1); + if (key.contentEquals(exonAttr)) { + parsedAttr = kv.trim() + "";""; + break; + } + } + if (parsedAttr.contentEquals("""") && keyVals.length>0) + parsedAttr = keyVals[0] + "";""; + } + // else isGap or isCent + + /** Load annotation into database **/ + int gidx = (isGene) ? 0 : lastGeneIdx; + ps.setInt(1,grpIdx); + ps.setString(2,type); + ps.setString(3,parsedAttr); + ps.setInt(4,start); + ps.setInt(5,end); + ps.setString(6,strand); + ps.setInt(7, gidx); + + ps.addBatch(); + totalLoaded++; cntBatch++; lastIdx++; + + if (cntBatch==1000) { + cntBatch=0; + ps.executeBatch(); + Globals.rprt(totalLoaded + "" annotations""); + } + } + if (cntBatch> 0) ps.executeBatch(); + ps.close(); + fh.close(); + + cntAllGene+=cntGene; + Utils.prtNumMsg(plog, totalLoaded, ""annotations loaded from "" + f.getName()); + if (cntGene>0 || cntExon>0) { // no longer supporting exons in separate file + Utils.prtNumMsg(plog, cntGene, String.format(""genes %,d exons"", cntExon)); + if (cntGene==0) plog.msg(""Warning: genes and exons must be in the same file for accurate results""); + } + if (cntSkipGeneAttr>0) Utils.prtNumMsg(plog,cntSkipGeneAttr, ""skipped gene attribute with no '='""); + if (cntSkipMRNA>0) Utils.prtNumMsg(plog,cntSkipMRNA, ""skipped mRNA and exons""); + if (numParseErrors>0) Utils.prtNumMsg(plog,numParseErrors, ""parse errors - lines discarded""); + if (noGrpSet.size() >0) Utils.prtNumMsg(plog,noGrpSet.size(), ""sequence names in annotation file not loaded into database""); + } + catch (Exception e) { + System.err.println(""""); + System.err.println(""*** Database index problem: try 'Load' again (it generally works on 2nd try)""); + System.err.println(""""); + ErrorReport.print(e, ""Load file (grpIdx="" + grpIdx + "") try 'Load' again (it generally works on 2nd try).""); + bSuccess=false;} + } + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return x[1]; + } + return null; + } + private String getmRNAid(String geneID, String [] keyVal, int lineNum, String line) { + String mrnaID = getVal(idKey, keyVal); + if (mrnaID==null) { + plog.msgToFile(""+++ missing mRNA ID on line "" + lineNum); + plog.msgToFile(""line: "" + line); + cntNoKey++; + if (cntNoKey>5) { + bSuccess=false; + plog.msgToFile(""Fatal error: missing keywords ""); + return null; + } + String parent = getVal(parentKey, keyVal); + if (parent==null) { + plog.msgToFile(""+++ missing mRNA parent on line "" + lineNum + "" Last Parent '"" + geneID); + plog.msgToFile(""line: "" + line); + cntNoKey++; + if (cntNoKey>5) { + bSuccess=false; + plog.msgToFile(""Fatal error: missing keywords ""); + return null; + } + } + if (!parent.equals(geneID)) { + plog.msgToFile(""+++ missing mRNA parent on line "" + lineNum + "" Last Parent '"" + geneID); + plog.msgToFile(""line: "" + line); + cntNoKey++; + if (cntNoKey>5) { + bSuccess=false; + plog.msgToFile(""Fatal error: missing keywords ""); + return null; + } + } + } + return mrnaID; + } + private boolean isGoodExon(String mrnaID, String [] keyVal, int lineNum, String line) { + String parent = getVal(parentKey, keyVal); + if (parent==null) { + plog.msgToFile(""+++ missing mRNA parent on line "" + lineNum + "" Last Parent '"" + mrnaID); + plog.msgToFile(""line: "" + line); + cntNoKey++; + if (cntNoKey>5) { + bSuccess=false; + plog.msgToFile(""Fatal error: missing keywords ""); + return false; + } + } + return parent.equals(mrnaID); + } + + // Eliminate all quotes in strings before DB insertion, though do not need with PreparedStatement. + static Pattern mpQUOT = Pattern.compile(""[\'\""]"");; + public String sqlSanitize(String in) { + Matcher m = mpQUOT.matcher(in); + return m.replaceAll(""""); + } + /************* Initialize local data *****************/ + private void initFromParams(String projName) { + try { + String projDir = Constants.seqDataDir + projName; + + // Files init + String annoFiles = mProj.getAnnoFile(); + String saveAnnoDir=""""; + long modDirDate=0; + + if (annoFiles.equals("""")) {// Check for annotation directory + String annotDir = projDir + Constants.seqAnnoDataDir; + plog.msg("" Anno_files "" + annotDir + "" (Default location)""); + File ad = new File(annotDir); + if (!ad.isDirectory()) { + plog.msg("" No annotation files provided""); + return; // this is not considered an error + } + + File[] fs = ad.listFiles(); + Arrays.sort(fs); // If separate files, order is random; this isn't necessary, but nice + + for (File f2 : fs) { + if (!f2.isFile() || f2.isHidden()) continue; // macOS add ._ files in tar + + annotFiles.add(f2); + } + if (annotFiles.size()==0) { + plog.msg("" No annotation files provided""); + return; // this is not considered an error + } + saveAnnoDir=annotDir; + } + else { + String[] fileList = annoFiles.split("",""); + String xxx = (fileList.length>1) ? (fileList.length + "" files "") : annoFiles; + plog.msg("" User specified annotation files - "" + xxx); + + for (String filstr : fileList) { + if (filstr == null) continue; + if (filstr.trim().equals("""")) continue; + + File f = new File(filstr); + if (!f.exists()) { + plog.msg(""***Cannot find annotation file "" + filstr); + } + else if (f.isDirectory()) { + saveAnnoDir=filstr; + for (File f2 : f.listFiles()) { + if (!f2.isFile() || f2.isHidden()) continue; // macOS add ._ files in tar + + annotFiles.add(f2); + } + } + else { + saveAnnoDir=Utils.pathOnly(filstr); + annotFiles.add(f); + } + } + } + if (saveAnnoDir!="""") {// print on View + modDirDate = new File(saveAnnoDir).lastModified(); + mProj.saveProjParam(""proj_anno_date"", Utils.getDateStr(modDirDate)); + mProj.saveProjParam(""proj_anno_dir"", saveAnnoDir); + } + + // Parse user-specified types + userSetMinKeywordCnt = mProj.getdbMinKey(); + String attrKW = mProj.getKeywords(); + if (!attrKW.contentEquals("""")) plog.msg("" "" + mProj.getLab(mProj.sANkeyCnt) + "" "" + attrKW); + + // if ID is not included, it all still works... + bUserSetKeywords = (attrKW.equals("""")) ? false : true; + if (bUserSetKeywords) { + if (attrKW.contains("","")) { + String[] kws = attrKW.trim().split("",""); + for (String key : kws) userAttr.put(key.trim(), 0); + } + else userAttr.put(attrKW.trim(), 0); + } + } + catch (Exception e) {ErrorReport.print(e, ""load anno init""); bSuccess=false;} + } + /********************** wrap up ***********************/ + private void summary() { + try { + // Print type counts + plog.msg(""GFF Types:""); + for (String type : typeCounts.keySet()) { + plog.msg(String.format("" %-15s %,d"", type, typeCounts.get(type))); + } + + Vector sortedKeys = new Vector(); + sortedKeys.addAll(userAttr.keySet()); + Collections.sort(sortedKeys, new Comparator() { + public int compare(String o1, String o2) { + return userAttr.get(o2).compareTo(userAttr.get(o1)); + } + }); + + int cntSav=0; + if (bUserSetKeywords) plog.msg(""User specified attribute keywords: ""); + else plog.msg(""Best attribute keywords:""); + + tdbc2.executeUpdate(""delete from annot_key where proj_idx="" + mProj.getIdx()); + for (String key : sortedKeys) { + cntSav++; + if (cntSav>savAtLeastKeywords) { + plog.msg(sortedKeys.size() + "" Attribute keywords; skip remaining....""); + break; + } + int count = userAttr.get(key); + + plog.msg(String.format("" %-15s %,d"", key,count)); + tdbc2.executeUpdate(""insert into annot_key (proj_idx,keyname,count) values ("" + + mProj.getIdx() + "",'"" + key + ""',"" + count + "")""); + } + if (ignoreAttr.size()>0) { + plog.msg(""Ignored attribute keywords: ""); + for (String key : ignoreAttr.keySet()) { + int count = ignoreAttr.get(key); + if (count>userSetMinKeywordCnt) + plog.msg(String.format("" %-15s %,d"", key, count)); + } + } + // Release data from heap + typeCounts = null; + System.gc(); // Java treats this as a suggestion + } + catch (Exception e) {ErrorReport.print(e, ""Compute gene order""); bSuccess=false;} + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/Constants.java",".java","5325","123","package backend; + +import backend.anchor1.Proj; +import symap.manager.Mpair; + +public class Constants { + +/********************************************** + * Command line arguments + */ +// Set in SymapCE.SyMAPmanager +public static boolean WRONG_STRAND_PRT = false; // -wsp print wrong strand hits for algo2 +public static boolean MUM_NO_RM = false; // -mum on A&S ONLY do not remove any mummer files; +public static boolean VERBOSE = false; // -v on +public static boolean CoSET_ONLY = false; // -scs on A&S ONLY execute AnchorPosts; not on -h, leave for possible updates +public static boolean NUMHITS_ONLY = false; // -nh on A&S only execute in AnchorMain for v5.7.9c + +// Anchor1 constants; Anchor2 constants are in Anchor2.Arg +public static final int TARGET=0, QUERY=1, EITHER=2; +public static final String GeneGene=""GeneGene""; +public static final String GeneNonGene = ""GeneNonGene""; +public static final String NonGene = ""NonGene""; + +public static final double FperBin=0.8; // HitBin.filter piles FperBin*matchLen +/*************************************************************/ + +// types +public static final String seqType = ""seq""; // directory name +public static final String dbSeqType = ""pseudo""; // name in database +public static final String geneType = ""gene""; // is this used? + +public static final int CHUNK_SIZE = 1000000; + +// Write to logs: ProgSpec for program alignment output +// ProjectManagerFrameCommon.buildLog for SyMAP alignment output +public static final String logDir = ""logs/""; // in symap directory +public static final String loadLog = ""load.log""; // suffix for load log (symap_load.log) +public static final String syntenyLog = ""symap.log""; // suffix for align log (p1_to_p2.log) + +// default directories of data ('/' in front indicates after project name +// these are repeated as constants in xToSymap - don't change +public static final String dataDir = ""data/""; // top level +public static final String seqDataDir = ""data/seq/""; +public static final String seqSeqDataDir = ""/sequence/""; +public static final String seqAnnoDataDir = ""/annotation/""; + +// MacOS Sequoia will no longer easily open files if they do not end with .txt; checked in Utils.getParamFile +public static final String paramsFile = ""/params.txt""; // in both seq/proj and seq_results/proj1_to_proj2 +public static final String usedFile = ""/params_align_used.txt""; // seq_results + +//These file types, denoted by the .fas extension, are used by most large curated databases. +//Specific extensions exist for nucleic acids (.fna), nucleotide coding regions (.ffn), amino acids (.faa), +//and non-coding RNAs (.frn). +public static final String [] fastaFile = {"".fa"", "".fna"", "".fas"", "".fasta"", "".seq""}; +public static final String fastaList = "".fas, .fa, .fna, .fasta, .seq (options .gz)""; +public static final String [] gffFile = {"".gff"", "".gff3""}; +public static final String gffList = "".gff, .gff3""; + +// directories for results +public static final String seqRunDir = ""data/seq_results/""; + +public static final String alignDir = ""/align/""; +public static final String mumSuffix = "".mum""; +public static final String doneSuffix = "".done""; +public static final String selfPrefix = ""self.""; +public static final String finalDir = ""/final/""; // has been discontinued; still exists in order to Remove + +public static final String projTo = ""_to_""; +public static final String faFile = "".fa""; + +public static final String orderSuffix = ""_ordered.csv""; +public static final String orderDelim = ""..""; + +// directory of temporary files written for mummer +//under runDir/_to_/tmp// file names. +//files in are aligned with files in . +public static final String tmpRunDir = ""/tmp/""; + +/*************************************************************************/ + public static boolean rtError(String msg) { + System.out.println(msg); + return false; + } + // default data directory + public static String getNameDataDir(Proj p1) { + String name = p1.getName(); + return seqDataDir + name; + } + public static String getNameResultsDir() { + return seqRunDir; + } + + // Results NOTES: XXX + // 1. Cannot use ""Project p"" as argument as two Project.java + // 2 see ProjectManagerFrameCommon.orderProjects + public static String getNameResultsDir(String n1, String n2) { + return seqRunDir + n1 + projTo + n2; + } + + public static String getNameAlignDir(String n1, String n2) { + return getNameResultsDir(n1, n2) + alignDir; + } + + public static String getNameAlignFile(String n1, String n2) { + String tmp1 = n1.substring(0, n1.indexOf(Constants.faFile)); + String tmp2 = n2.substring(0, n2.indexOf(Constants.faFile)); + if (tmp1.equals(tmp2)) return selfPrefix + tmp1; + return tmp1 + ""."" + tmp2; + } + // tmp preprocessed results; created in AlignName.java + public static String getNameTmpDir(String n1, String n2) { + return getNameResultsDir(n1, n2) + tmpRunDir; + } + public static String getNameTmpPreDir(String n1, String n2, String n) { + return getNameResultsDir(n1, n2) + tmpRunDir + n; + } + public static String getOrderDir(Mpair mp) { + if (mp.isOrder1(Mpair.FILE)) return mp.mProj1.getDBName() + Constants.orderDelim + mp.mProj2.getDBName(); + if (mp.isOrder2(Mpair.FILE)) return mp.mProj2.getDBName() + Constants.orderDelim + mp.mProj1.getDBName(); + return null; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AlignMain.java",".java","20354","594","package backend; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.io.BufferedReader; +import java.util.Vector; + +import java.util.TreeMap; +import java.util.Queue; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.sql.ResultSet; + +import database.DBconn2; +import symap.Ext; +import symap.Globals; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; +import util.FileDir; + +/******************************************************* + * Set up to run MUMmer for alignments for one pair of genomes + */ +public class AlignMain { + protected boolean mCancelled = false; + + private static final int CHUNK_SIZE = Constants.CHUNK_SIZE; // 1000000 + private static final int maxFileSize = 60000000; // 'Concat' parameter works for demo using this size + + private ProgressDialog plog; + private String proj1Dir, proj2Dir; // also dbName, directory name + private Mproject mProj1, mProj2; + + private String alignLogDirName; + private Vector alignList; + private Queue toDoQueue; + private Vector threads; + private int nMaxCPUs; + + private Mpair mp = null; + private DBconn2 dbc2 = null; + + private boolean bDoCat = true; + private boolean notStarted = true; + private boolean interrupted = false; + private boolean error = false; + + private String resultDir; + private String alignParams; // Set in pair_props from DoAlignSynPair; + private int nAlignDone=0; + + protected AlignMain(DBconn2 dbc2, ProgressDialog log, Mpair mp, int nMaxThreads, String alignLogDirName){ + this.plog = log; // diaLog and syLog + this.nMaxCPUs = nMaxThreads; + this.mp = mp; + this.dbc2 = dbc2; + this.mProj1 = mp.mProj1; + this.mProj2 = mp.mProj2; + this.alignLogDirName = alignLogDirName; + + proj1Dir = mProj1.getDBName(); + proj2Dir = mProj2.getDBName(); + bDoCat = mp.isConcat(Mpair.FILE); + + threads = new Vector(); + alignList = new Vector(); + toDoQueue = new LinkedList(); + } + protected String getParams() {// DoAlignSynPair save to DB pairs.params + return alignParams; + } + + /******************************************************* + * Run all alignments for p1-p2 + */ + protected boolean run() { + try { + long startTime = Utils.getTime(); + + System.gc(); // free unused heap for mummer to use (Java treats this as a suggestion) + + resultDir = Constants.getNameResultsDir(proj1Dir, proj2Dir); + + if (alignExists()) return true; // must have all.done and at least one .mum file; r/w params_used + + buildAlignments(); // build toDoQueue + + if (error) return false; // error occurred in buildAlignments + if (mCancelled) return false; + + if (toDoQueue.size() > 0) { + String program = toDoQueue.peek().program.toUpperCase(); + String msg = ""\nRunning "" + program + "": "" + toDoQueue.size() + "" alignments to perform""; + if (nAlignDone>0) msg += "" ("" + nAlignDone + "" previously completed)""; + if (toDoQueue.size()>nMaxCPUs) msg += "" using ""+ nMaxCPUs + "" CPUs""; + plog.msg(msg); + } + + int alignNum = 0; + while (true) { + synchronized(threads) { + if (toDoQueue.size()==0 && threads.size() == 0) + break; + + while (toDoQueue.size()>0 && threads.size() < nMaxCPUs) {// Start another alignment thread + final AlignRun p = toDoQueue.remove(); + alignNum++; + p.alignNum = alignNum; + Thread newThread = new Thread() { + public void run() { + try { + p.doAlignment(); + } + catch (Exception e) { + ErrorReport.print(e, ""Alignment thread""); + p.setStatus(AlignRun.STATUS_ERROR); + } + synchronized(threads) { threads.remove( this ); } + } + }; + + threads.add( newThread ); + newThread.start(); + notStarted=false; + } + } + Utilities.sleep(1000); // free processor + } + + if (getNumErrors() == 0) { + if (!mCancelled) { + Utils.writeDoneFile(resultDir + Constants.alignDir); + plog.msg(""Alignments: success "" + getNumCompleted()); + + String tmpDir = Constants.getNameTmpDir(proj1Dir, proj2Dir);// only delete tmp files if successful + if (Globals.TRACE) { + Globals.prt(""Do not delete "" + tmpDir); + } + else { + File dir = new File(tmpDir); + FileDir.clearAllDir(dir); + dir.delete(); + } + } + } + else { + plog.msg(""Alignments: success "" + getNumCompleted() + "" failed "" + getNumErrors()); + } + Utils.prtMsgTimeDone(plog, ""Alignments"", startTime); // Align done: time + } + catch (Exception e) {ErrorReport.print(e, ""Run alignment""); } + + return (getNumErrors() == 0); + } + + /******************************************************************* + * True - all.done && at least one .mum file; do not do any alignments + * False - !all.done; do any alignments not done (see buildAlignments ps.isDone) + ****************************************************************/ + private boolean alignExists() { + try { + String alignDir = Constants.getNameResultsDir(proj1Dir, proj2Dir) + Constants.alignDir; + File f = new File(alignDir); + if (!f.exists()) return false; /*-- alignments to be done ... --*/ + + boolean bdone = Utils.checkDoneFile(alignDir); // all.done + nAlignDone = Utils.checkDoneMaybe(alignDir); // # existing .mum files + + if (bdone && nAlignDone>0) {// could by SyMAP or user complete + plog.msg(""Warning: "" + nAlignDone + "" alignment files exist - using existing files""); + plog.msg("" If not correct, remove "" + resultDir + "" and re-align""); + paramsRead(Utils.getDateStr(f.lastModified())); + return true; + } + /*-------- Alignments to be done ------*/ + + if (nAlignDone==0) return false; // do all + + /* If !bDone && nAlign>0, probably did not finish; + * This is strictly to let the user know what is being done + * See buildAlignments ps.isDone() */ + HashSet fdone = new HashSet (); + HashSet align = new HashSet (); + + for (File x : f.listFiles()) { + if (!x.isFile()) continue; + if (x.isHidden()) continue; + + String path = x.getName(); + String name = path.substring(path.lastIndexOf(""/"")+1, path.length()); + if (name.endsWith(Constants.doneSuffix)) fdone.add(name); + else if (name.endsWith(Constants.mumSuffix)) align.add(name); + } + plog.msg(""+++ Checking ""+ alignDir); + plog.msg(String.format("" No all.done file; %,d .mum files; %,d .mum.done files "", align.size(), fdone.size())); + plog.msg("" Finding possible missing .mum files to align""); + return false; + } + catch (Exception e) {ErrorReport.print(e, ""Trying to see if alignment exists"");} + return false; + } + /********************************************************* + * Create alignParams for save to pairs.param for summary + * If align, write to params_used, else read it. This is not in the /align directory, but its main directory + */ + private void mummerParamsWrite() { + try { + alignParams = ""MUMmer files "" + Utilities.getDateTime() + "" CPUs: "" + nMaxCPUs + ""\n""; + alignParams += mp.getChgAlign(Mpair.FILE, true); // true, do not add command line + if (Ext.isMummer4Path()) alignParams += Ext.getMummerPath() + "" ""; + + File pfile = Utils.getParamsFile(resultDir,Constants.usedFile); + if (pfile==null) pfile = new File(resultDir,Constants.usedFile); // create + + PrintWriter out = new PrintWriter(pfile); + out.println(""# Parameters used for MUMmer alignments in /align.""); + out.println(alignParams); + out.close(); + } + catch (Exception e) {ErrorReport.print(e, ""Save "" + Constants.usedFile); } + } + private void paramsRead(String dateTime) { + try { + alignParams = ""Use previous "" + nAlignDone + "" MUMmer files "" + dateTime; + File pfile = Utils.getParamsFile(resultDir,Constants.usedFile); + if (pfile==null) return; // okay, not written yet + + alignParams = ""Use previous "" + nAlignDone + "" ""; // completed with what is in file + String line; + BufferedReader reader = new BufferedReader(new FileReader(pfile)); + while ((line = reader.readLine()) != null) { + if (!line.startsWith(""#"")) + alignParams += line + ""\n""; + } + reader.close(); + } + catch (Exception e) {ErrorReport.print(e, ""Save params_used""); } + } + /**************************************************** + * Create preprocessed files and run alignment + */ + private void buildAlignments() { + try { + plog.msg(""\nAligning "" + proj1Dir + "" and "" + proj2Dir + "" with "" + nMaxCPUs + "" CPUs""); + + /* create directories */ + // result directory (e.g. data/seq_results/demo1_to_demo2) + FileDir.checkCreateDir(resultDir, true /* bPrt */); + mummerParamsWrite(); // write here after creating the directory + + // temporary directories to put data for alignment + String tmpDir = Constants.getNameTmpDir(proj1Dir, proj2Dir); + FileDir.checkCreateDir(tmpDir, false); + + boolean isSelf = (proj1Dir.equals(proj2Dir)); + String tmpDir1 = Constants.getNameTmpPreDir(proj1Dir, proj2Dir, proj1Dir); + String tmpDir2 = (isSelf) ? tmpDir1 : Constants.getNameTmpPreDir(proj1Dir, proj2Dir, proj2Dir); + File fh_tDir1 = FileDir.checkCreateDir(tmpDir1, false); + File fh_tDir2 = FileDir.checkCreateDir(tmpDir2, false); + + // Preprocessing for proj1 + if (!writePreprocSeq(fh_tDir1, mProj1, bDoCat, isSelf, ""Query"")) { // concat=true if Concat not checked + mCancelled = true; + Cancelled.cancel(); + System.out.println(""Cancelling""); + return; + } + + // Preprocessing for proj2 + if (!writePreprocSeq(fh_tDir2, mProj2, false, isSelf, ""Target"")) { // concat=false + mCancelled = true; + Cancelled.cancel(); + System.out.println(""Cancelling""); + return; + } + + /** Assign values for Alignment; path is obtained in AlignRun **/ + String program = Ext.exPromer; + if (isSelf) program = Ext.exNucmer; + + // user over-rides + if (program.equals(Ext.exPromer) && mp.isNucmer(Mpair.FILE)) program = Ext.exNucmer; + else if (program.equals(Ext.exNucmer) && mp.isPromer(Mpair.FILE)) program = Ext.exPromer; + + String args = (program.contentEquals(Ext.exPromer)) ? mp.getPromerArgs(Mpair.FILE) : mp.getNucmerArgs(Mpair.FILE); + String self = (isSelf) ? ("" "" + mp.getSelfArgs(Mpair.FILE)) : """"; + + /** create list of comparisons to run **/ + // under runDir/_to_/tmp// with file names + // files in are aligned with files in . + // For self, p1=p2 + String alignDir = resultDir + Constants.alignDir; + FileDir.checkCreateDir(alignDir, false); + File[] fs1 = fh_tDir1.listFiles(); // order, not necessary, but nice + Arrays.sort(fs1); + File[] fs2 = fh_tDir2.listFiles(); + Arrays.sort(fs2); + + for (File f1 : fs1) { + if (!f1.isFile() || f1.isHidden()) continue; + + for (File f2 : fs2) { + if (!f2.isFile() || f2.isHidden()) continue; + + // XXX + String aArgs = args; + if (isSelf) { // chr files have been written as is + if (f1.getName().equals(f2.getName())) aArgs += self; + else if (f1.getName().compareTo(f2.getName()) < 0) continue; // AnchorMain will correct order when wrong + } + + AlignRun ps = new AlignRun(program, aArgs, f1, f2, alignDir, alignLogDirName); + if (ps.isDone()) continue; + + alignList.add(ps); + } + } + if (alignList.size()>0) { + Collections.sort(alignList); + for (AlignRun ps : alignList) { + toDoQueue.add(ps); + ps.setStatus(AlignRun.STATUS_QUEUED); + if (Globals.TRACE) Globals.prt(ps.getDescription()); + } + } + if (nAlignDone>0) { + if (alignList.size()==0) Utils.writeDoneFile(alignDir); + plog.msg(""Alignments to be completed: "" + alignList.size()); + } + else if (alignList.size() == 0 && !Cancelled.isCancelled()) { + plog.msg(""Warning: no alignments between projects""); + error = true; + } + } + catch (Exception e) {ErrorReport.print(e, ""Build alignments""); error=true;} + } + + /************************************** + * Write sequences to file; first is concatenated, second is not. Apply gene masking if requested. + */ + private boolean writePreprocSeq(File dir, Mproject mProj, boolean concat, boolean isSelf, String who) { + try { + int projIdx = mProj.getIdx(); + String projName = mProj.getDBName(); + + if (concat && isSelf) return true; // all get written as originals + + if (Cancelled.isCancelled()) return false; + + DBconn2 tdbc2 = new DBconn2(""WriteAlignFiles-"" + DBconn2.getNumConn(), dbc2); + int nSeqs = tdbc2.executeCount(""select count(*) as nseqs from pseudos "" + + "" join xgroups on xgroups.idx=pseudos.grp_idx "" + + "" where xgroups.proj_idx="" + projIdx); + if (nSeqs == 0) { + plog.msg(""No sequences are loaded for "" + projName + ""!! (idx "" + projIdx + "")""); + return false; + } + + boolean geneMask = (mp.mProj1.getIdx() == mProj.getIdx()) ? + mp.isMask1(Mpair.FILE) : mp.isMask2(Mpair.FILE); + String gmprop = (geneMask) ? ""Masking non-genic sequence; "" : """"; + if (geneMask) plog.msg(projName + "": "" + gmprop); + + if (FileDir.dirNumFiles(dir) > 0) + FileDir.clearAllDir(dir); // leaves directory, just removes files + + // Figure out what chromosomes to group into one file. + Vector> groups = new Vector>(); + + String msg = projName + "": ""; + if (!isSelf) { + if (concat) msg += ""Concatenating all sequences into one file for "" + who; + else msg += ""Writing sequences into one or more files for "" + who; + } + else msg += ""Writing separate chromosome files for self-synteny""; + + // pseudos (files): grp_idx, fileName (e.g. chr3.seq), length + // xgroups (chrs): idx, proj_idx, chr#, fullname where grp_idx is xgroups.idx + ResultSet rs = tdbc2.executeQuery(""select grp_idx, length from pseudos "" + + "" join xgroups on xgroups.idx=pseudos.grp_idx "" + + "" where xgroups.proj_idx="" + projIdx + "" order by xgroups.sort_order""); + groups.add(new Vector()); + long curSize = 0, totSize = 0; + int nOrigGrp = 0, nGrp = 0; + while (!interrupted && rs.next()) { + nOrigGrp++; + int grp_idx = rs.getInt(1); + long chrLen = rs.getLong(2); + totSize += chrLen; + + if (!isSelf) { // Unless concat=true, group up to total seq length maxFileSize. + if (!concat && nOrigGrp > 1 && curSize+chrLen > maxFileSize) { // 60,000,000 + nGrp++; + groups.add(new Vector()); + curSize = 0; + } + groups.get(nGrp).add(grp_idx); + curSize += chrLen; + } + else { // each group only has one chr in it (written like the original file) + groups.get(nGrp).add(grp_idx); + nGrp++; + groups.add(new Vector()); + curSize += chrLen; + } + } + plog.msg(msg + "" ("" + Utilities.kMText(totSize) + "")""); // write total length here first + + TreeMap>> geneMap = new TreeMap>>(); + int cSize = 100000; + + // MASK + if (geneMask) { + // Build a map of the gene annotations that we can use to mask each sequence chunk as we get it. + // The map is sorted into 100kb bins for faster searching. + rs = tdbc2.executeQuery(""select xgroups.idx, pseudo_annot.start, pseudo_annot.end "" + + "" from pseudo_annot join xgroups on xgroups.idx=pseudo_annot.grp_idx "" + + "" where pseudo_annot.type='gene' and xgroups.proj_idx="" + projIdx); + while (!interrupted && rs.next()) + { + int grpIdx = rs.getInt(1); + int start = rs.getInt(2); + int end = rs.getInt(3); + if (!geneMap.containsKey(grpIdx)) { + geneMap.put(grpIdx, new TreeMap>()); + } + int cStart = (int)Math.floor(start/cSize); + int cEnd = (int)Math.ceil(end/cSize); + for (int c = cStart; c <= cEnd; c++) { + int s = c*cSize; + int e = (c+1)*cSize - 1; + int r1 = Math.max(s, start); + int r2 = Math.min(e, end); + if (!geneMap.get(grpIdx).containsKey(c)) geneMap.get(grpIdx).put(c, new Vector()); + geneMap.get(grpIdx).get(c).add(new Range(r1,r2)); + } + if (interrupted) break; + } + } // end mask + + if (interrupted) { + tdbc2.close(); + return false; + } + + /** Write files **/ + // Go through each grouping, write the preprocess file, with masking if called for. + // Note that sequences are stored in chunks of size CHUNK_SIZE (1,000,000). + + for (int i = 0; i < groups.size(); i++) { + if (groups.get(i).size() == 0) break; // last one can come up empty + + String fileName = (concat) ? (""_cc"") : (""_f"" + (i+1)); + + fileName = projName + fileName + Constants.faFile; + msg = "" "" + fileName + "": ""; + long fileSize = 0; // must be long so does not become negative number + int count=0; + + File f = FileDir.checkCreateFile(dir,fileName, ""AM WritePreprocSeq""); + FileWriter fw = new FileWriter(f); + + for (int gIdx : groups.get(i)) { + if (interrupted) break; + + rs = tdbc2.executeQuery(""select fullname from xgroups where idx="" + gIdx); + rs.next(); + String grpFullName = rs.getString(1); + fw.write("">"" + grpFullName + ""\n""); + + if (count==0) msg += grpFullName; + else if (count<4) msg += "", "" + grpFullName; + else if (count==4) msg += ""... ""; + count++; + + rs = tdbc2.executeQuery(""select seq from pseudo_seq2 join xgroups on xgroups.idx=pseudo_seq2.grp_idx "" + + "" where grp_idx="" + gIdx + "" order by chunk asc""); + int cNum = 0; + while (!interrupted && rs.next()){ + if (interrupted) break; + + int start = cNum*CHUNK_SIZE + 1; // use 1-indexed string positions for comparing to annot + int end = (1+cNum)*CHUNK_SIZE; + String seq = rs.getString(1); + if (geneMask) { + if (geneMap.containsKey(gIdx)) { + StringBuffer seqMask = new StringBuffer(seq.replaceAll(""."", ""N"")); + int cs = (int)Math.floor(start/cSize); + int ce = (int)Math.ceil(end/cSize); + TreeMap> map = geneMap.get(gIdx); + + for (int c = cs; c <= ce; c++) {// check the bins covered by this chunk + if (map.containsKey(c)) { + for (Range r : map.get(c)) { + int olapS = (int)Math.max(start, r.s); + int olapE = (int)Math.min(end, r.e); + if (olapE > olapS) { + olapS -= start; // get the 0-indexed relative coords within this chunk + olapE -= start; + seqMask.replace(olapS, olapE, seq.substring(olapS, olapE)); + } + } + } + else { } //System.out.println(""No entries in bin "" + c + "" for "" + gIdx ); + } + seq = seqMask.toString(); + } + } + for (int j = 0; j < seq.length(); j += 50) { + int endw = Math.min(j+50,seq.length()); + String x = seq.substring(j, endw); + fileSize += x.length(); + fw.write(x); + fw.write(""\n""); + } + cNum++; + } + } + plog.msg(msg + String.format("": length %,d"", fileSize)); + fw.close(); + } + tdbc2.close(); + return true; + } + catch (Exception e) {ErrorReport.die(e, ""AlignMain.writePreproc"");} + return false; + } + + /*****************************************************************/ + protected String getStatusSummary() { + String s = """"; + + for (AlignRun p : alignList) + if ( p.isRunning() || p.isError() ) + s += p.toStatus() + ""\n""; + + return s; + } + protected int getNumRunning() { + synchronized(threads) { + return threads.size(); + } + } + protected int getNumRemaining() { + synchronized(threads) { + return toDoQueue.size(); + } + } + protected int getNumCompleted() { + return alignList.size() - getNumRunning() - getNumRemaining() - getNumErrors(); + } + protected int getNumErrors() { + int count = 0; + + for (AlignRun p : alignList) + if (p.isError()) + count++; + + return count; + } + protected boolean notStarted() { + return notStarted; + } + protected void interrupt() { + interrupted = true; + mCancelled = true; + synchronized(threads) { + for (AlignRun p : alignList) + if (p.isRunning()) + p.interrupt(); + + toDoQueue.clear(); + + for (Thread t : threads) + t.interrupt(); + threads.removeAllElements(); + } + } + private class Range {// for mask gene + int s; + int e; + Range(int start, int end) { + s = start; e = end; + } + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AnchorPost.java",".java","15723","450","package backend; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.TreeMap; +import java.util.Vector; + +import database.DBconn2; +import symap.Globals; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; + +/************************************************** + * Computes the collinear sets (pseudo_hits.runsize, runnum); the term 'run' is used here for collinear (run/set) + * NOTES: + * - The hits are ordered along the alphabetically lesser project name, say project A. Hence the + * hits are analyzed along the project A length. + * - The annot_idx are sequential for sequential genes, but have gaps for exons. The temporary tnum is sequential. + * - The hits for collinear may not be sequential when a gene has two hits. + * - Only hits to two genes are downloaded from DB, hence, if a gene has a g1 and g2 hit, the g1 hit is ignored. + * CAS577 the cosets were numbered weird, this is fixed + */ +public class AnchorPost { + // parameters + private int mPairIdx; // project pair + private Mproject mProj1, mProj2; // two projects + private ProgressDialog mLog; + private DBconn2 dbc2; + private boolean isSelf=false; + + // initial; loaded from db + private Vector fHitVec = new Vector (); // forward set + private Vector rHitVec = new Vector (); // reverse set + private Vector csHitVec = new Vector (); // all grp-grp + private TreeMap geneMap1 = new TreeMap (); // tmpNum (tnum), gene + private TreeMap geneMap2 = new TreeMap (); // tmpNum (tnum), gene + private HashMap gidxTnum = new HashMap (); // geneIdx, tmpNum to maintain order + + private int totalRuns=0; + private int coSetNum; // collinear set number + + private String chrs; // ErrorReport + + /** Called from AnchorMain **/ + protected AnchorPost(int pairIdx, Mproject proj1, Mproject proj2, DBconn2 dbc2, ProgressDialog log) { + this.mPairIdx = pairIdx; + this.mProj1 = proj1; + this.mProj2 = proj2; + this.dbc2 = dbc2; + this.mLog = log; + isSelf = proj1.getIdx()==proj2.getIdx(); + } + + protected void collinearSets() { + try { + dbc2.executeUpdate(""update pseudo_hits set runsize=0, runnum=0 where pair_idx="" + mPairIdx); + + int num2go = mProj1.getGrpSize() * mProj2.getGrpSize(); + Utils.prtMsgFile(mLog, "" Finding Collinear sets""); + long time = Utils.getTime(); + + TreeMap map1 = mProj1.getGrpIdxMap(); + TreeMap map2 = mProj2.getGrpIdxMap(); + + for (int grpIdx1 : map1.keySet()) { + for (int grpIdx2 : map2.keySet()) { + if (isSelf && grpIdx10 and pair_idx="" + mPairIdx); + Utils.prtNumMsg(mLog, totalRuns, ""Collinear sets ""); + if (Constants.VERBOSE) { + Utils.prtNumMsg(mLog, nhits, ""Updates ""); + Utils.prtMsgTime(mLog, "" Finish Collinear"", time); + } + } + catch (Exception e) {ErrorReport.print(e, ""Compute colinear genes""); } + } + + /***************************************************************************************************** + * COLLINEAR SETS between two chromosomes + */ + private boolean step0BuildSets(int grpIdx1, int grpIdx2) { + try { + coSetNum=1; + if (!step1LoadFromDB(grpIdx1, grpIdx2)) return false; // fHitVec, rHitVec, geneMap1, geneMap2, gidxTnum + + if (!step2AssignRunNum(false, fHitVec)) return false; + if (!step2AssignRunNum(true, rHitVec)) return false; + + if (!step3SaveToDB()) return false; + + geneMap1.clear(); geneMap2.clear(); gidxTnum.clear(); + fHitVec.clear(); rHitVec.clear(); csHitVec.clear(); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Build collinear "" + chrs); return false; } + } + + /************************************************************* + * Create hit and gene maps + * Create hitMap from gene_overlap>1: the pseudo_hits_annot table can hold multiple occurrences of a hit. + * It can hit on one or both side, and multiple genes on one side (overlapping, contained, or close) + * Use the two from the pseudo_hits table + */ + private boolean step1LoadFromDB(int grpIdx1, int grpIdx2) { + try { + Gene gObj; + Hit hObj; + ResultSet rs; + + // Hits with 2 genes - annot1 and annot2 have the best overlap; ignore others; + String sql = ""select PH.idx, PH.strand, PH.hitnum, PH.annot1_idx, PH.annot2_idx "" + + "" from pseudo_hits AS PH "" + + "" LEFT JOIN pseudo_block_hits AS PBH ON PBH.hit_idx=PH.idx"" + + "" where PH.grp1_idx="" + grpIdx1 + "" and PH.grp2_idx="" + grpIdx2; + if (isSelf && grpIdx1==grpIdx2) sql += "" AND PH.start1 > PH.start2 ""; // DIR_SELF CAS577 + sql += "" and PH.gene_overlap>1 order by PH.hitnum"";// algo1 does not enter them ordered + + rs = dbc2.executeQuery(sql); + while (rs.next()) { + int i=1; + int hidx = rs.getInt(i++); + String str = rs.getString(i++); + int hitnum = rs.getInt(i++); + int gidx1= rs.getInt(i++); + int gidx2 = rs.getInt(i++); + + boolean inv = (str.contains(""+"") && str.contains(""-"")); + + hObj = new Hit(hidx, hitnum, gidx1, gidx2); + if (inv) rHitVec.add(hObj); + else fHitVec.add(hObj); + } + if (rHitVec.size()==0 && fHitVec.size()==0) return true; // not an error + + // All genes + String ssql = ""select idx, tag, start, end, genenum, strand, (end-start) as len from pseudo_annot "" + + "" where type='gene' and grp_idx=""; + String osql = "" order by start ASC, len DESC""; + + int tnum1=1; + rs = dbc2.executeQuery(ssql + grpIdx1 + osql); + while (rs.next()) { + int idx = rs.getInt(1); // tag start end genenum strand + gObj = new Gene(idx, tnum1, rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getInt(5), rs.getString(6)); + geneMap1.put(tnum1, gObj); // using tnum keeps them ordered by start + gidxTnum.put(idx, tnum1); + tnum1++; + } + + int tnum2=1; // uses same gidxTnum but starts over numbering (idx are unique) + rs = dbc2.executeQuery(ssql + grpIdx2 + osql); + while (rs.next()) { + int idx = rs.getInt(1); + gObj = new Gene(idx, tnum2, rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getInt(5), rs.getString(6)); + geneMap2.put(tnum2, gObj); + gidxTnum.put(idx, tnum2); + tnum2++; + } + rs.close(); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Load from DB "" + chrs); return false; } + } + + /************************************************************* + * Using genenums so do not have to worry about gene overlaps; hits are to best + * Example of reverse: + * Hit Gene1 Gene2 + * Row1 767 1930 2040 r1G2-r2G2 + * Row2 768 1931 2039 if bInv r2G1-r2G2 else r1G2-r2G2 + * Row3 769 1932 2038 + * 1. backRow1 allows for co-mingled coSets. + * 2. could possibly miss a set at very end, but if the 1st loop row2 xHitVec) { + try { + HashSet coHitSet = new HashSet (); + int row1=0, row2=0, nHits = xHitVec.size(); + int r1G1=0, r1G2=0, r2G1=0, r2G2=0; + int savRow1, backRow1=0, d1=0, d2=0; + Hit hObj1=null, hObj2=null; + boolean bNewCo=true; + int cnt=0, max = xHitVec.size()*100; + + while (row1 < nHits-1 && row2 < nHits) { + hObj1 = xHitVec.get(row1); + if (hObj1.setNum>0) { + row1++; + continue; + } + savRow1 = row1; + + if (bNewCo) { + coHitSet.add(row1); // start new one + bNewCo = false; + } + + r1G1 = gidxTnum.get(hObj1.gidx1); + r1G2 = gidxTnum.get(hObj1.gidx2); + + row2 = row1+1; + while (row2 < nHits) { // either breaks or row2++ + hObj2 = xHitVec.get(row2); + if (hObj2.setNum>0) { + row2++; + continue; + } + r2G1 = gidxTnum.get(hObj2.gidx1); + r2G2 = gidxTnum.get(hObj2.gidx2); + + d1 = r2G1 - r1G1; + d2 = (!bInv) ? r2G2 - r1G2 : r1G2 - r2G2; + + if (d1==1 && d2==1) { + if (!coHitSet.contains(row2)) coHitSet.add(row2); + else dprt(""***found already: "" + row2); + + if (backRow1==0) backRow1=row1+1; // at beginning of this coSet, may skip entries, so start + row1 = row2; + + break; + } + else if (d1>1 && (d2>1 || d2<1)) { + if (coHitSet.size()>1) { // finish current set + for (int i: coHitSet) { + xHitVec.get(i).setNum = coSetNum; + xHitVec.get(i).setSize = coHitSet.size(); + } + coSetNum++; + } + if (backRow1!=0) row1=backRow1; // only have value if there was a coSet, i.e. row1 can only become this backRow value once + else row1++; + + backRow1=0; + coHitSet.clear(); + bNewCo=true; + + break; + } + else { + row2++; + } + } + if (savRow1==row1) row1++; // prevent endless loops; often happens with backRow + + if (++cnt % 10000 == 0) + symap.Globals.rprt(""Iterations: "" + cnt + "" Row: "" + row1 + "" of "" + nHits + "" rows for "" + chrs); + + if (cnt>max) { // insurance: in case a bizarre situation causes an endloop + symap.Globals.eprt(""Too many iterations: "" + cnt + "" Row1: "" + row1 + "" of "" + nHits); + prtLine(bInv, coHitSet,""C"", hObj1, hObj2, r1G1, r1G2, r2G1, r2G2, row1, row2, d1, d2); + break; + } + } + if (coHitSet.size()>1) { // finish last set + for (int i: coHitSet) { + xHitVec.get(i).setNum = coSetNum; + xHitVec.get(i).setSize = coHitSet.size(); + } + coSetNum++; // add 1 for inv + } + // put all hits in coset in csHitVec for save to db + for (Hit ht : xHitVec) { + if (ht.setSize>0) csHitVec.add(ht); + } + if (cnt> nHits+10) dprt(""Iterations "" + cnt); // cnt is generally < nHits + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Build sets "" + chrs); return false; } + } + /*************************************************** + * Trace and verify print routines + */ + private void prtWrong() { // unexpected situation... + HashMap csetMap = new HashMap (); + Set cset; + + for (Hit hObj : csHitVec) { + if (hObj.setNum==0) continue; + + int tnum1 = gidxTnum.get(hObj.gidx1); + int tnum2 = gidxTnum.get(hObj.gidx2); + + if (csetMap.containsKey(hObj.setNum)) cset = csetMap.get(hObj.setNum); + else { + cset = new Set(hObj.setSize); + csetMap.put(hObj.setNum, cset); + } + cset.add(tnum1, tnum2); + } + + for (int rn : csetMap.keySet()) { + cset = csetMap.get(rn); + int tsz = cset.tnum1.size(); + if (tsz!=cset.sz) dprt(""Error in set Size "" + chrs + "" "" + cset.sz + ""."" + rn + "" hits "" + tsz); + + for (int i=0; i tnum1 = new Vector (); + Vector tnum2 = new Vector (); + } + private void prtLine(boolean bInv, HashSet coHitSet ,String xxx, Hit hObj1, Hit hObj2, + int t1G1, int t1G2, int t2G1, int t2G2, int r1, int r2, int d1, int d2) { + + String t1Tag1 = geneMap1.get(t1G1).tag; String t2Tag1 = geneMap1.get(t2G1).tag; + String t1Tag2 = geneMap2.get(t1G2).tag; String t2Tag2 = geneMap2.get(t2G2).tag; + + String x1 = (d1==1)? ""T"" : ""F""; if (t1Tag1.equals(t2Tag1)) x1=""=""; + String x2 = (d2==1)? ""T"" : ""F""; if (t1Tag2.equals(t2Tag2)) x2=""="";; + + String s1 = String.format(""%s %s%s #%d.%d; R %3d %3d; D %5d %5d; "", + xxx, x1, x2, coHitSet.size(), coSetNum, r1, r2, d1, d2); + int h2 = (hObj2 != null) ? hObj2.hitnum : 0; + String s2 = String.format(""#%-4d #%-4d; t1 %4d %4d; t2 %4d %4d; gn1 %7s %7s; gn2 %7s %7s"", + hObj1.hitnum, h2, t1G1, t2G1, t1G2, t2G2, t1Tag1, t2Tag1, t1Tag2, t2Tag2); + dprt(""AP: "" + s1+s2); + } + private void dprt(String msg) {symap.Globals.dprt(""AP: "" + msg);} + + ///////////////////////////////////////////////////////////////// + /*****************************************************************/ + private boolean step3SaveToDB() { + try { + // Reassign coset num based on size and hitnum + Collections.sort(csHitVec, new Comparator() { + public int compare(Hit a1, Hit a2) { + if (a2.setSize==a1.setSize) return a1.hitnum - a2.hitnum; + return a2.setSize - a1.setSize; + } + }); + coSetNum=1; + HashMap numMap = new HashMap (); + for (Hit ht : csHitVec) { + if (numMap.containsKey(ht.setNum)) { + ht.setNum = numMap.get(ht.setNum); + } + else { + numMap.put(ht.setNum, coSetNum); + ht.setNum = coSetNum++; + } + } + prtWrong(); // just checking + + PreparedStatement ps = dbc2.prepareStatement(""update pseudo_hits set runsize=?, runnum=? where idx=?""); + for (Hit hObj : csHitVec) { + ps.setInt(1, hObj.setSize); + ps.setInt(2, hObj.setNum); + ps.setInt(3, hObj.hidx); + ps.addBatch(); + } + ps.executeBatch(); + + if (isSelf) { // mirror collinear for self + dbc2.executeUpdate(""update pseudo_hits as ph1, pseudo_hits as ph2 "" + + "" set ph2.runsize=ph1.runsize, ph2.runnum=ph1.runnum "" + + "" where ph1.pair_idx="" + mPairIdx + "" and ph2.pair_idx="" + mPairIdx + + "" and ph1.idx=ph2.refidx""); + } + if (Globals.DEBUG && isSelf) { // -dd + int [] cntSizeSet = {0,0,0,0,0}; + HashSet set = new HashSet (); + for (Hit hObj : csHitVec) { + if (set.contains(hObj.setNum)) continue; + + set.add(hObj.setNum); + int rsize = hObj.setSize; + if (rsize==2) cntSizeSet[0]++; else if (rsize==3) cntSizeSet[1]++; + else if (rsize<=5) cntSizeSet[2]++; else if (rsize<=10) cntSizeSet[3]++; else cntSizeSet[4]++; + } + int tot = cntSizeSet[0]+cntSizeSet[1]+cntSizeSet[2]+cntSizeSet[3]+cntSizeSet[4]; + if (tot>0) Globals.prt(String.format(""%10s 2: %,-5d 3: %,-5d 4-5: %,-5d 6-10: %,-5d >10: %,-5d Total: %,d"", chrs, + cntSizeSet[0], cntSizeSet[1], cntSizeSet[2], cntSizeSet[3], cntSizeSet[4], tot)); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Save sets to database "" + chrs); return false; } + } + /****************************************************************** + * annot_hit: idx annot1_hit annot2_hit (best two overlaps) + */ + private class Hit { + private Hit(int idx, int hitnum, int gidx1, int gidx2) { + this.hidx = idx; + this.hitnum=hitnum; + this.gidx1= gidx1; + this.gidx2= gidx2; + } + private int hidx, hitnum; // hitnum debugging only + private int gidx1=-1, gidx2=-1; // best + private int setSize=0, setNum=0; // to be saved to db + } + + /****************************************************** + * After v556 rewrite, do not need Gene at all, but keep for debugging */ + private class Gene { + private Gene(int idx, int tnum, String tag, int start, int end, int genenum, String strand) { + this.tag = Utilities.getGenenumFromDBtag(tag); + } + private String tag=""""; + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/Utils.java",".java","8006","237","package backend; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.util.zip.GZIPInputStream; + +import symap.Globals; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; + +/******************************************************** + * Utils for A&S + * msgToFile prints to file and terminal, but not ProgressDialog + * msg and appendText prints to file, terminal, ProgressDialog + */ +public class Utils { + public static void sleep(int milliseconds) { + try{ Thread.sleep(milliseconds); } + catch (InterruptedException e) { } + } + // time + public static long getTime() { return System.currentTimeMillis();} + + public static String getElapsedTime(long startTime) { + return Utilities.getDurationString(getTime()-startTime); + } + public static void prtMsgTimeFile(ProgressDialog prog, String msg, long startTime) { + String t = Utilities.getDurationString(getTime()-startTime); + prog.msgToFile(String.format(""%-30s %s"", msg, t)); + } + public static void prtMsgTime(ProgressDialog prog, String msg, long startTime) { + String t = Utilities.getDurationString(getTime()-startTime); + prog.msg(String.format(""%-30s %s"", msg, t)); + } + public static void prtMsgTimeDone(ProgressDialog prog, String msg, long startTime) { + String t = Utilities.getDurationString(getTime()-startTime); + String m = String.format(""%-35s %s \n\n"", msg, t); + + if (prog!=null) prog.msg(m); + else System.out.println(m); + } + + // Memory and time + public static long getTimeMem() { System.gc(); return System.currentTimeMillis();} + + public static void prtTimeMemUsage(ProgressDialog prog, String title, long startTime) { + prog.msgToFile(getTimeMemUsage(title, startTime) + ""\n\n""); + } + public static void prtTimeMemUsage(String title, long startTime) { + System.out.print(getTimeMemUsage(title, startTime) + ""\n\n""); + } + public static String getTimeMemUsage(String title, long startTime) { + Runtime rt = Runtime.getRuntime(); + long total_mem = rt.totalMemory(); + long free_mem = rt.freeMemory(); + long used_mem = total_mem - free_mem; + String mem = String.format(""%.2fMb"", ((double)used_mem/1000000.0)); + + String str = Utilities.getDurationString(getTime() - startTime); + return String.format(""%-50s %-8s %10s"", title, mem, str); + } + public static String getMemUsage() { + Runtime rt = Runtime.getRuntime(); + long total_mem = rt.totalMemory(); + long free_mem = rt.freeMemory(); + long used_mem = total_mem - free_mem; + String mem = String.format(""%.2fMb"", ((double)used_mem/1000000.0)); + + return String.format(""Memory %s\n\n"", mem); + } + // no time + public static void prtMsgFile(ProgressDialog prog, String msg) { + prog.msgToFile(msg); + } + public static void prtIndentMsgFile(ProgressDialog prog, int indent, String msg) { + String x = """"; + for (int i=0; i0) prtNumMsg(prog, num, msg); + } + + public static void prtNumMsg(int num, String msg) { + Globals.prt(String.format(""%,10d %s "", num, msg)); + } + + public static void die(String msg) { + System.err.println(""Fatal error: "" + msg); + System.exit(-1); + } + /***************************************************************************/ + public static String fileFromPath(String path) { + int i = path.lastIndexOf(""/""); + if (i<=0) return path; + return path.substring(i+1); + } + public static String pathOnly(String path) { + int i = path.lastIndexOf(""/""); + if (i<=0) return path; + return path.substring(0, i); + } + public static BufferedReader openGZIP(String file) { + try { + File f = new File (file); + if (!file.endsWith("".gz"")) { + if (f.exists()) + return new BufferedReader ( new FileReader (f)); + } + if (file.endsWith("".gz"")) { + FileInputStream fin = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fin); + InputStreamReader xover = new InputStreamReader(gzis); + return new BufferedReader(xover); + } + } + catch (Exception e) { + ErrorReport.print(e, ""Cannot open file "" + file); + } + return null; + } + // The prefix must be present. if no prefix, just use the given name. + public static String parseGrpName(String name, String prefix){ + name = name + "" ""; // hack, otherwise we need two cases in the regex + + String regx = "">\\s*("" + prefix + "")(\\w+)\\s?.*""; + Pattern pat = Pattern.compile(regx,Pattern.CASE_INSENSITIVE); + Matcher m = pat.matcher(name); + if (m.matches()) return m.group(2); + + return parseGrpFullName(name); + } + public static String parseGrpFullName(String in){ + String regx = "">\\s*(\\w+)\\s?.*""; + Pattern pat = Pattern.compile(regx,Pattern.CASE_INSENSITIVE); + Matcher m = pat.matcher(in); + if (m.matches()) return m.group(1); + + return null; + } + /******************************************************** + * DONE + */ + public static boolean checkDoneFile(String dir) { + File d = new File(dir); + if (!d.exists() || d.isFile()) return false; + + File f = new File(d,""all"" + Constants.doneSuffix); + + if (f.exists()) return true; + + return false; + } + public static int checkDoneMaybe(String dir) { // no all.done file + File d = new File(dir); + if (!d.exists() || d.isFile()) return 0; + + int numFiles=0; + for (File x : d.listFiles()) { + if (!x.isFile()) continue; + if (x.isHidden()) continue; + + String path = x.getName(); + String name = path.substring(path.lastIndexOf(""/"")+1, path.length()); + if (name.endsWith(Constants.doneSuffix)) continue; // do not care for Manager; AlignMain further checks + + if (name.endsWith(Constants.mumSuffix)) numFiles++; + } + return numFiles; + } + public static void writeDoneFile(String dir) { + try { + File f = new File(dir); + File d = new File(f,""all"" + Constants.doneSuffix); + d.createNewFile(); + } + catch (Exception e) {ErrorReport.print(e, ""Cannot write done file to "" + dir);} + } + public static String getDateStr(long l) { + DateFormat sdf = new SimpleDateFormat(""dd-MMM-yyyy hh:mm a""); + return sdf.format(l); + } + // Pre-v569 did not have "".txt"" suffix; this checks and renames + public static File getParamsFile(String dir, String fileName) { + try { + if (!util.FileDir.dirExists(dir)) return null; + + File pfile = new File(dir,fileName); + if (pfile.isFile()) return pfile; // exists with new name + + String oldName = fileName.replace("".txt"", """"); // old name + File ofile = new File(dir,oldName); + if (!ofile.isFile()) return null; // no new or old name + + boolean b = ofile.renameTo(pfile); + if (!b) return null; + + return pfile; + } + catch (Exception e) {ErrorReport.print(e, ""Could not open "" + dir +""/"" + fileName); return null;} + } + /****************************************************************************/ + + public static boolean intervalsTouch(int s1,int e1, int s2, int e2) { + return intervalsOverlap(s1,e1,s2,e2,0); + } + + static public boolean intervalsOverlap(int s1,int e1, int s2, int e2, int max_gap) { + int gap = Math.max(s1,s2) - Math.min(e1,e2); + return (gap <= max_gap); + } + + // Returns the amount of the overlap (negative for gap) + public static int intervalsOverlap(int s1,int e1, int s2, int e2) { + int gap = Math.max(s1,s2) - Math.min(e1,e2); + return -gap; + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/DoLoadProj.java",".java","4813","148","package backend; + +import java.io.FileWriter; +import java.util.Vector; + +import database.DBconn2; +import symap.manager.ManagerFrame; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ErrorReport; +import util.ProgressDialog; + +/******************************************************************************** + * DoLoadProj - calls SeqLoadMain and AnnotLoadMain; Called from ManagerFrame; + * All ProgressDialog must call finish in order to close fw + *******************************************************************************/ +public class DoLoadProj { + private DBconn2 dbc2; + private ManagerFrame frame; + private FileWriter fw; + + public DoLoadProj(ManagerFrame frame, DBconn2 dbc2, FileWriter fw) { + this.dbc2 = dbc2; + this.frame = frame; + this.fw = fw; + } + /********************************************************************/ + public void loadAllProjects(Vector selectedProjVec) { + ErrorCount.init(); + + final ProgressDialog progress = new ProgressDialog(frame, + ""Loading All Projects"", ""Loading all projects"" , true, fw); // Writes version and date to file + progress.closeIfNoErrors(); + + Thread loadThread = new Thread() { + public void run() { + boolean success = true; + progress.appendText("">>> Load all projects ("" + selectedProjVec.size() + "")""); + + for (Mproject mProj : selectedProjVec) { + if (mProj.getStatus() != Mproject.STATUS_ON_DISK) continue; + + try { + progress.appendText("">>> Load "" + mProj.getDBName()); + mProj.createProject(); + success = new SeqLoadMain().run(dbc2, progress, mProj); + + if (success && !Cancelled.isCancelled()) { + AnnotLoadMain annot = new AnnotLoadMain(dbc2, progress, mProj); + success = annot.run( mProj.getDBName()); + } + + if (!success || Cancelled.isCancelled()) { + System.out.println(""Removing project from database "" + mProj.getDBName()); + mProj.removeProjectFromDB(); + } + else mProj.saveParams(mProj.xLoad); + + if (Cancelled.isCancelled()) break; + } + catch (Exception e) { + success = false; + ErrorReport.print(e, ""Loading all projects""); + } + } + if (!progress.wasCancelled()) progress.finish(success); + } + }; + progress.start( loadThread ); // blocks until thread finishes or user cancels + } + /********************************************************************************/ + public void loadProject(final Mproject mProj) { // Reload Project deletes project before calling + ErrorCount.init(); + + final ProgressDialog progress = new ProgressDialog(frame, + ""Loading Project"", ""Loading project "" + mProj.getDBName() + "" ..."", true, fw); + progress.closeIfNoErrors(); + + Thread loadThread = new Thread() { + public void run() { + boolean success = true; + + try { + progress.appendText("">>> Load "" + mProj.getDBName()); + + mProj.createProject(); + success = new SeqLoadMain().run(dbc2, progress, mProj); + + if (success && !Cancelled.isCancelled()) { + AnnotLoadMain annot = new AnnotLoadMain(dbc2, progress, mProj); + success = annot.run( mProj.getDBName()); + } + + if (!success || Cancelled.isCancelled()) { + System.out.println(""Removing project from database "" + mProj.getDBName()); + mProj.removeProjectFromDB(); + } + else mProj.saveParams(mProj.xLoad); + } + catch (Exception e) { + success = false; + ErrorReport.print(e, ""Loading project""); + } + finally { + if (!progress.wasCancelled()) progress.finish(success); + } + } + }; + progress.start( loadThread ); // blocks until thread finishes or user cancels + } + /********************************************************************************/ + public void reloadAnno(final Mproject mProj) { + String title = ""Reload annotation""; + String msg = "">>>Reloading annotation "" + mProj.getDBName(); + final ProgressDialog progress = new ProgressDialog(frame, title, msg + "" ..."", true, fw); + progress.closeIfNoErrors(); + + Thread loadThread = new Thread() { + public void run() { + boolean success = true; + progress.appendText(msg); + + try { + mProj.removeAnnoFromDB(); + + AnnotLoadMain annot = new AnnotLoadMain(dbc2, progress, mProj); + success = annot.run(mProj.getDBName()); + + if (!success || Cancelled.isCancelled()) { + System.out.println(""Removing annotation from database "" + mProj.getDBName()); + mProj.removeAnnoFromDB(); + } + else mProj.saveParams(mProj.xLoad); + } + catch (Exception e) { + success = false; + ErrorReport.print(e, ""Run Reload""); + } + finally { + if (!progress.wasCancelled()) progress.finish(success); + } + } + }; + progress.start( loadThread ); // blocks until thread finishes or user cancels + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/Log.java",".java","963","50","package backend; + +/******************************************** + * see ProgressDialog for writing to LOAD.log and symap.log + */ +import java.io.FileWriter; +import java.io.IOException; + +import util.ErrorReport; + +public class Log { + public FileWriter logFile = null; + + public Log(FileWriter fw) { // backend.AlignRun, backend.Log + logFile = fw; + } + + public Log(String filePath) throws IOException { + this( new FileWriter(filePath,false) ); + } + + public void msg(String s) { + System.out.println(s); + + if (logFile != null) { + try { + logFile.write(s + ""\n""); + logFile.flush(); + } + catch(Exception e) { + ErrorReport.print(e, ""Cannot write to log file""); + } + } + } + public void msgToFile(String s) { + if (logFile != null) { + try { + logFile.write(s + ""\n""); + logFile.flush(); + } + catch(Exception e) { + ErrorReport.print(e, ""Cannot write to log file""); + } + } + } + public void write(char c) { + System.out.print(c); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AlignRun.java",".java","9002","258","package backend; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Writer; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.channels.ClosedByInterruptException; + +import symap.Ext; +import util.ErrorReport; +import util.Utilities; +import util.FileDir; + +/************************************* + * Executes the alignment program for one query_to_target where either may have >1 chromosomes/scaffold + */ +public class AlignRun implements Comparable +{ + protected static final int STATUS_UKNOWN = 0; + protected static final int STATUS_QUEUED = 1; + protected static final int STATUS_RUNNING = 2; + protected static final int STATUS_ERROR = 3; + protected static final int STATUS_DONE = 4; + + protected int alignNum; + protected String program, args; + + private File f1, f2; + private String resDir, alignLogDirName; + private String outRoot, outFile; + private long startTime; + + private Process process; + private int status, nExitValue = -1; + + protected AlignRun(String program, String args, + File f1, File f2, String resdir, String alignLogDirName) + { + this.program = program; + this.args = args; + this.f1 = f1; + this.f2 = f2; + this.resDir = resdir; + + this.outRoot = Constants.getNameAlignFile(f1.getName(), f2.getName()); + + this.outFile = resDir + outRoot + Constants.mumSuffix; + this.alignLogDirName = alignLogDirName; + + if (outputFileExists()) this.status = STATUS_DONE; + else this.status = STATUS_QUEUED; + } + + protected synchronized void setStatus(int n) {status = n;} + protected synchronized int getStatus() {return status;} + protected synchronized boolean isQueued() {return status == STATUS_QUEUED;} + protected synchronized boolean isRunning() {return status == STATUS_RUNNING;} + protected synchronized boolean isError() {return status == STATUS_ERROR;} + protected synchronized boolean isDone() {return status == STATUS_DONE;} + + protected String toStatus() { + String s = Utilities.pad( getDescription(), 40 ) + "" ""; + if (isError()) s += ""Error occurred ("" + nExitValue + "")""; + else if (isRunning()) s += Utilities.getDurationString( getRunTime() ); + else if (isDone()) s += ""Finished""; + else if (isQueued()) s += ""Queued""; + else s += ""Unknown""; + return s; + } + private boolean outputFileExists() { + File f1 = new File(outFile + Constants.doneSuffix); + if (f1 != null && f1.exists()) { + File f2 = new File(outFile); + if (f2 != null && f2.exists()) + return true; + } + return false; + } + protected String getDescription() { + return f1.getName() + "" to "" + f2.getName(); + } + + protected long getRunTime() { + return System.currentTimeMillis() - startTime; + } + + protected boolean doAlignment() { + int rc = -1; + String cmd=""""; + + try { + startTime = System.currentTimeMillis(); + setStatus(STATUS_RUNNING); + + String doneFile = outFile + Constants.doneSuffix; + FileDir.deleteFile(doneFile); + + String query = f1.getPath(); + String targ = f2.getPath(); + + String runLogName = alignLogDirName + outRoot + "".log""; + FileWriter runFW = new FileWriter(runLogName); + Log runLog = new Log(runFW); + + // Make command + String intFilePath = resDir + outRoot + ""."" + program; + String deltaFilePath = intFilePath + "".delta""; + + if (Ext.isMummer4Path()) { + query = f1.getAbsolutePath(); + targ = f2.getAbsolutePath(); + intFilePath = new File(intFilePath).getAbsolutePath(); + deltaFilePath = new File(deltaFilePath).getAbsolutePath(); + } + + String mummerPath = Ext.getMummerPath(); + if (!mummerPath.equals("""") && !mummerPath.endsWith(""/"")) mummerPath += ""/""; + + // Run promer or nucmer + cmd = mummerPath + program + "" "" + args + "" -p "" + intFilePath + "" "" + targ + "" "" + query; + rc = runCommand(cmd, runFW, runLog); // send output and log messages to same file + + // Run show-coords // nucmer rc=1 + if (rc == 0) { + String parms = (program.equals(Ext.exPromer) ? ""-dlkT"" : ""-dlT""); // -k to remove secondary frame hits + cmd = mummerPath + Ext.exCoords + "" "" + parms + "" "" + deltaFilePath; + rc = runCommand(cmd, new FileWriter(outFile), runLog); + runLog.msg( ""#"" + alignNum + "" done: "" + Utilities.getDurationString(getRunTime()) ); + } + else runLog.msg( ""#"" + alignNum + "" fail: "" + Utilities.getDurationString(getRunTime()) ); + + if (rc == 0) { + cleanup(); // Cleanup intermediate files. + FileDir.checkCreateFile(doneFile, ""PS done""); + setStatus(STATUS_DONE); + } + else { + ErrorReport.print(""#"" + alignNum + "" rc"" + rc + "" Failed: "" + cmd); + setStatus(STATUS_ERROR); + } + runFW.close(); + + } catch (Exception e) { + ErrorReport.print(e, ""Running command: "" + cmd); + setStatus(STATUS_ERROR); + } + return (rc == 0); + } + + private void cleanup() { + String intFilePath = resDir + outRoot + ""."" + program; + if (Constants.MUM_NO_RM) {// command line -mum; user to keep all args + System.out.println(""For mummer files, see "" + resDir); + return; + } + FileDir.deleteFile(intFilePath + "".delta""); // appears to be the only one MUMmer keeps if successfully completes + FileDir.deleteFile(intFilePath + "".cluster""); + FileDir.deleteFile(intFilePath + "".mgaps""); + FileDir.deleteFile(intFilePath + "".aaqry""); // promer only + FileDir.deleteFile(intFilePath + "".aaref""); // promer only + FileDir.deleteFile(intFilePath + "".ntref""); // nucmer only + } + + protected void interrupt() { + setStatus(AlignRun.STATUS_ERROR); + process.destroy(); // terminate process + try { + process.waitFor(); // wait for process to terminate + } + catch (Exception e) { ErrorReport.print(e, ""Interrupt process""); } + cleanup(); + } + + protected int runCommand (String strCommand, Writer runFW, Log runLog) {// runFW and runLog go to same file + try { + boolean bDone = false; + System.err.println(""#"" + alignNum + "" "" + strCommand); + + if (runLog != null) + runLog.msgToFile(""#"" + alignNum + "" "" + strCommand); // log file for this run + + // Execute command + String [] x = strCommand.split(""\\s+""); + process = Runtime.getRuntime().exec(x); + + // Capture stdout and stderr + InputStream stdout = process.getInputStream(); + BufferedReader brOut = new BufferedReader( new InputStreamReader(stdout) ); + InputStream stderr = process.getErrorStream(); + BufferedReader brErr = new BufferedReader( new InputStreamReader(stderr) ); + try { + synchronized ( stdout ) { + while ( !bDone || brErr.ready() || brOut.ready()) { + // Send the sub-processes stderr to out stderr or log + while (brErr.ready()) { + if (runFW != null) runFW.write(brErr.read()); + else if (runLog != null) runLog.write((char)brErr.read()); + else System.err.print((char)brErr.read()); + } + + // Consume stdout so the process doesn't hang... + while (brOut.ready()) { + if (runFW != null) runFW.write(brOut.read()); + else if (runLog != null) runLog.write((char)brOut.read()); + else System.out.print((char)brOut.read()); + } + + if ( runFW != null )runFW.flush(); + + stdout.wait( 1000 /*milliseconds*/ ); // sleep if nothing to do + + try { + nExitValue = process.exitValue(); // throws exception if process not done + bDone = true; + } + catch ( Exception err ) { } + } + } + } + catch ( ClosedByInterruptException ignore ) { } + catch ( InterruptedException ignore ) { } + + if (nExitValue != 0) + runLog.msg( ""Alignment program error code: "" + nExitValue ); + + // Kill the process if it's still running (exception occurred) + if ( !bDone ) { + interrupt(); + runLog.msg( ""Interrupted #"" + alignNum + "": "" + Utilities.getDurationString(getRunTime()) ); + } + + // Clean up + if (runFW != null) runFW.flush(); + + try { + // Prevent ""too many open files"" error + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + process.destroy(); + process = null; + } + catch (IOException e) { } + } catch (Exception e) {ErrorReport.print(e, ""Run command""); } + + return nExitValue; + } + + public int compareTo(AlignRun p) {// goes into queue sorted ascending order + if (p != null) + return getDescription().compareTo(p.getDescription() ); + return -1; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AnchorMain.java",".java","18143","492","package backend; + +import java.io.File; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.HashMap; +import java.util.TreeMap; + +import backend.anchor1.AnchorMain1; +import backend.anchor2.AnchorMain2; +import database.DBconn2; +import symap.Globals; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ErrorReport; +import util.ProgressDialog; + +/************************************************************** + * AnchorMain: + * Performs the set up computations for computing clustered hits. + * It then calls the anchor1 or anchor2 code. It finishes by computing the gene NumHits + * + * Filename: e.g. arab_cc.cabb_f1.mum + * Mproj1 (arab) is query and Mproj2 (cabb) is target; target coords (cabb) comes before query (arab) + */ +public class AnchorMain { + public boolean doAlgo1=false; + private boolean isSelf=false; + + // variables may be accessed directly by AnchorMain1 or AnchorMain2 + public DBconn2 dbc2; + public ProgressDialog plog=null; + public Mpair mp; + public int pairIdx; + public boolean bInterrupt; + + public AnchorMain(DBconn2 dbc2, ProgressDialog log, Mpair mp) { + this.dbc2 = dbc2; + this.plog = log; + this.mp = mp; + if (mp!=null) { // Null for Mproject.removeProjectFromDB; + this.pairIdx = mp.getPairIdx(); + doAlgo1 = (mp.isAlgo1(Mpair.FILE)); + } + } + + protected boolean run(Mproject pj1, Mproject pj2) throws Exception { + try { + /** setup **/ + long startTime = Utils.getTimeMem(); + isSelf = pj1.getIdx()==pj2.getIdx(); + + String proj1Name = pj1.getDBName(), proj2Name = pj2.getDBName(); + if (isSelf) plog.msg(""\nStart calculating cluster hits for "" + proj1Name + "" self synteny""); + else plog.msg(""\nStart calculating cluster hits for "" + proj1Name + "" and "" + proj2Name); + + String resultDir = Constants.getNameResultsDir(proj1Name, proj2Name); // e.g. data/seq_results/p1_to_p2 + if (!util.FileDir.pathExists(resultDir)) { + plog.msg(""Cannot find pair directory "" + resultDir); + ErrorCount.inc(); + return false; + } + String alignDir = resultDir + Constants.alignDir; + + File dh = new File(alignDir); + if (!dh.exists() || !dh.isDirectory()) return Constants.rtError(""/align directory does not exist "" + alignDir); + plog.msg("" Alignment files in "" + alignDir); + + /** execute **/ + if (doAlgo1) { + AnchorMain1 an = new AnchorMain1(this); + boolean b = an.run(pj1, pj2, dh); if (!b) return false; + } + else { + AnchorMain2 an = new AnchorMain2(this); + boolean b = an.run(pj1, pj2, dh); if (!b) return false; + } + if (Cancelled.isCancelled()) {dbc2.close(); return false; } + + saveHitNum(); + saveAnnoHitCnt(true); + + /** Run before pseudo **/ + if (pj1.hasGenes() && pj2.hasGenes()) { + AnchorPost collinear = new AnchorPost(pairIdx, pj1, pj2, dbc2, plog); + collinear.collinearSets(); + } + if (Cancelled.isCancelled()) {dbc2.close(); return false; } + + // Numbers pseudo genes; must be after collinear; + if (mp.isNumPseudo(Mpair.FILE)) new Pseudo().addPseudo(); + + /** finish **/ + long modDirDate = new File(resultDir).lastModified(); // add for Pair Summary with 'use existing files' + mp.setPairProp(""pair_align_date"", Utils.getDateStr(modDirDate)); + if (!Constants.VERBOSE) Globals.rclear(); + Utils.prtMsgTimeDone(plog, ""Finish clustering hits"", startTime); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Run load anchors""); return false;} + } + protected void interrupt() {bInterrupt = true; } + + /*************************************************************** + * Assign hitnum, with them ordered by start1 ASC, len DESC + * isSelf: just do upper part of diagonal: only number if refidx=0 + */ + private boolean saveHitNum() { + try { + Globals.rprt(""Compute and save hit#""); + TreeMap grpMap1 = mp.mProj1.getGrpIdxMap(); + TreeMap grpMap2 = mp.mProj2.getGrpIdxMap(); + + for (int g1 : grpMap1.keySet()) { + for (int g2 : grpMap2.keySet()) { + if (isSelf && g1 hitNumMap = new HashMap (); + int hitcnt=1; + ResultSet rs = dbc2.executeQuery(""select idx, (end1-start1) as len from pseudo_hits "" + + "" where grp1_idx= "" + g1 + "" and grp2_idx="" + g2 + "" and refidx=0"" // refidx for isSelf + + "" order by start1 ASC, len DESC""); + + while (rs.next()) { + int hidx = rs.getInt(1); + hitNumMap.put(hidx, hitcnt); + hitcnt++; + } + rs.close(); + Globals.rprt(""Hits for "" + grpMap1.get(g1) + "":"" + grpMap2.get(g2) + "" "" + hitcnt); + + // save + PreparedStatement ps = dbc2.prepareStatement(""update pseudo_hits set hitnum=? where idx=?""); + for (int idx : hitNumMap.keySet()) { + int num = hitNumMap.get(idx); + ps.setInt(1, num); + ps.setInt(2, idx); + ps.addBatch(); + } + ps.executeBatch(); + } + } + Globals.rclear(); + + if (isSelf) { // mirror hitnum for self + dbc2.executeUpdate(""update pseudo_hits as ph1, pseudo_hits as ph2 "" + + "" set ph2.hitnum=ph1.hitnum "" + + "" where ph1.pair_idx="" + pairIdx + "" and ph2.pair_idx="" + pairIdx + + "" and ph1.idx=ph2.refidx""); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""compute gene hit cnts""); return false;} + } + /******************************************************************** + * Count number of hits per gene; these include all pairwise projects + * This includes isSelf, but self hits get counted for both sides of the diagonal + */ + public void saveAnnoHitCnt(boolean bPrt) { // public for Mpair.removePairFromDB; also called for command line -nh + if (bPrt) Globals.rprt(""Compute and save gene numHits...""); + + TreeMap idxList1 = mp.mProj1.getGrpIdxMap(); + TreeMap idxList2 = mp.mProj2.getGrpIdxMap(); + + for (int idx : idxList1.keySet()) + if (!saveAnnotHitCnt(idx, idxList1.get(idx))) return; + for (int idx : idxList2.keySet()) + if (!saveAnnotHitCnt(idx, idxList2.get(idx))) return; + + Globals.rclear(); + } + // This counts all hits in the database for a give grpIdx, so it is across pairs. + // This does not distinguish above and below diagonal for self-synteny; that will require pairIdx. + public boolean saveAnnotHitCnt(int grpIdx, String grpName) { // public for Mproject.removeProjectFromDB + try { + dbc2.executeUpdate(""update pseudo_annot set numhits=0 "" + + "" where grp_idx="" + grpIdx + "" and type='gene'""); // numhits is used by pseudo too; + ResultSet rs = dbc2.executeQuery(""select count(*) from pseudo_annot where grp_idx="" + grpIdx); + int cnt = (rs.next()) ? rs.getInt(1) : 0; + if (cnt==0) return true; // this is not a failure + + // CAS579c changed 4/14/25; no Version update for it. + dbc2.tableCheckModifyColumn(""pseudo_annot"", ""numhits"", ""INTEGER unsigned default 0""); + + HashMap geneCntMap = new HashMap (); + + rs = dbc2.executeQuery(""select pa.idx "" + + ""from pseudo_annot as pa "" + + ""join pseudo_hits_annot as pha on pha.annot_idx = pa.idx "" + + ""join pseudo_hits as ph on pha.hit_idx = ph.idx "" + + ""where pa.type='gene' and pa.grp_idx="" + grpIdx); // works for isSelf too + + while (rs.next()) { + int aidx = rs.getInt(1); + if (geneCntMap.containsKey(aidx)) geneCntMap.put(aidx,geneCntMap.get(aidx)+1); + else geneCntMap.put(aidx, 1); + } + rs.close(); + + PreparedStatement ps = dbc2.prepareStatement(""update pseudo_annot set numhits=? where idx=?""); + for (int idx : geneCntMap.keySet()) { + int num = geneCntMap.get(idx); + // if (num>255) num=255; // tinyint unsigned max is 255; CAS579c is Integer now + ps.setInt(1, num); + ps.setInt(2, idx); + ps.addBatch(); + } + ps.executeBatch(); + ps.close(); + + Globals.rclear(); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""compute gene hit cnts""); return false;} + } + // Called in Clear Pair as the pseudo are pair A&S specific + // numhits is used for the pairIdx for pseudo, otherwise it is the number of hits in the DB to the gene + public boolean removePseudo() { + try { + String where = ""where type='"" + Globals.pseudoType + ""' and numhits="" + pairIdx; + + int before = dbc2.executeCount(""select count(*) from pseudo_annot "" + where); + dbc2.executeUpdate(""delete from pseudo_annot "" + where); + int after = dbc2.executeCount(""select count(*) from pseudo_annot "" + where); + + Globals.tprt(String.format(""Remove pseudo %,d annotation (%,d->%,d)"",(before-after), before, after)); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""remove pseudo from pseudo_annot""); return false;} + } + /** For release v5.6.5 flag -pseudo **/ + protected boolean addPseudoFromFlag() { + try { + // This cascades to remove pseudo_hit_annot rows also + int cnt = dbc2.executeCount(""select count(*) from pseudo_annot "" + + ""where type='"" + Globals.pseudoType + ""' and numhits="" + pairIdx); + if (cnt>0) { // wipes out ALL species-species pseudo's; only do when testing + Globals.tprt(""Existing pseudo to remove: "" + cnt); + + removePseudo(); + + if (!doAlgo1) { + dbc2.executeUpdate(""update pseudo_hits set annot1_idx=0, annot2_idx=0 "" + + ""where pair_idx= "" + pairIdx + "" and htype='nn'"" ); + dbc2.executeUpdate(""update pseudo_hits set annot1_idx=0 "" + + ""where pair_idx= "" + pairIdx + "" and (htype='nE' or htype='nI')"" ); + dbc2.executeUpdate(""update pseudo_hits set annot2_idx=0 "" + + ""where pair_idx= "" + pairIdx + "" and (htype='En' or htype='In')"" ); + } + else {// cannot easily zero out annot1_idx and annot2_idx for algo1 g1 hits; but it is only way to know which gene is missing + Globals.prt(""Warning: -pseudo is being run on algo1, this will only work the first time.""); + Globals.prt(""You may need to re-run A&S for the complete synteny analysis""); + return false; + } + } + return new Pseudo().addPseudo(); + } + catch (Exception e) {ErrorReport.print(e, ""Add pseudo from flag""); return false;} + } + /******************************************************* + * Add so can be used in Cluster and Report as regular genes; + * Assigns sequentially along chromosome regardless of what the target chromosome is + * which allows all numbers to be unique; but it may lead to gaps for a give chrQ-chrT + */ + private class Pseudo { + private Mproject mProj1, mProj2; + private int [] cntPseudo = {0,0}; + private String [] annoKey = {""desc"",""desc""}; + private String chrPair=""""; + + private Pseudo() { + this.mProj1 = mp.mProj1; + this.mProj2 = mp.mProj2; + + try { // Give pseudo desc=Not annotated; Use same Desc/Product as used by the project .gff file + for (int i=0; i<2; i++) { + int idx = (i==0) ? mProj1.getID() : mProj2.getID(); + ResultSet rs = dbc2.executeQuery(""SELECT keyname, count FROM annot_key "" + + "" WHERE proj_idx = "" + idx); + while(rs.next()) { + String key = rs.getString(1); + int cnt = rs.getInt(2); + String keylc = key.toLowerCase(); + + if (keylc.equals(""desc"") || keylc.equals(""product"") || keylc.equals(""description"")) { + annoKey[i] = key; + if (cnt>50) break; + } + } + } + } + catch (Exception e) {ErrorReport.print(e, ""Could not get annotation keys"");} + } + /*****************************************************/ + private boolean addPseudo() { + try { + plog.msg("" Assign pseudo genes""); + + TreeMap grpMap1 = mp.mProj1.getGrpIdxMap(); + String grpList1 = """"; + for (int g1 : grpMap1.keySet()) { + if (grpList1.equals("""")) grpList1 += g1; + else grpList1 += "","" + g1; + } + TreeMap grpMap2 = mp.mProj2.getGrpIdxMap(); + String grpList2 = """"; + for (int g2 : grpMap2.keySet()) { + if (grpList2.equals("""")) grpList2 += g2; + else grpList2 += "","" + g2; + } + + int cnt=1; + for (int g1 : grpMap1.keySet()) { + chrPair = mProj1.getDisplayName() + "" "" + mProj1.getGrpFullNameFromIdx(g1); + + String where = "" where grp1_idx= "" + g1 + "" and grp2_idx IN ("" + grpList2 + "") and annot1_idx=0 ""; + + if (!addPseudoGrpGrp(g1, where, ""annot1_idx"", 0, cnt++, grpMap1.size())) return false; + } + cnt=1; + for (int g2 : grpMap2.keySet()) { + chrPair = mProj2.getDisplayName() + "" "" + mProj2.getGrpFullNameFromIdx(g2); + + String where = "" where grp1_idx IN ("" + grpList1 + "") and grp2_idx="" + g2 + "" and annot2_idx=0 ""; + + if (!addPseudoGrpGrp(g2, where, ""annot2_idx"", 1, cnt++, grpMap2.size())) return false; + } + + Utils.prtNumMsg(plog, cntPseudo[0], + String.format(""Pseudo %s %,d Pseudo %s "", mProj1.getDisplayName(), cntPseudo[1], mProj2.getDisplayName())); + return true; + } + catch (Exception e) {Globals.prt(""""); ErrorReport.print(e, ""add pseudos""); return false;} + } + /******************************************************* + * Assign one side at a time; find all that have annotN_idx=0 and update + */ + private boolean addPseudoGrpGrp(int grpIdx, String where, String annoStr, int i, int cntGrp, int maxGrp) { + try { + String type = Globals.pseudoType; + + // Must count pseudo too so as to not repeat pseudo numbers + int genes = dbc2.executeCount(""select max(genenum) from pseudo_annot where grp_idx=""+ grpIdx); + int geneStart = genes; + if (genes==0) geneStart = 1; + else { + int rem = genes%100; + int add = 100-rem; + geneStart += add; + } + int genenum = geneStart; + + // find pseudo + String select = (i==0) ? "" idx, start1, end1, strand"" : "" idx, start2, end2, strand""; + String order = (i==0) ? "" order by start1"" : "" order by start2""; + + HashMap hitGeneMap = new HashMap (); // geneNum, hitIdx + String sql = ""select "" + select + "" from pseudo_hits "" + where + order; + + ResultSet rs = dbc2.executeQuery(sql); + while (rs.next()) { + int hitIdx = rs.getInt(1); + int start = rs.getInt(2); + int end = rs.getInt(3); + String strand = rs.getString(4); + String [] tok = strand.split(""/""); + if (tok.length==2) strand = tok[i]; + + Hit ht = new Hit(hitIdx, start, end, strand); + hitGeneMap.put(genenum, ht); + genenum++; + } + rs.close(); + + if (Globals.TRACE) { // CAS579c was rprt, which was immediately written over leaving trailing stuff + String dn = (i==0) ? mProj1.getDisplayName() : mProj2.getDisplayName(); + String chr = (i==0) ? mProj1.getGrpFullNameFromIdx(grpIdx) : mProj2.getGrpFullNameFromIdx(grpIdx); + String msg = String.format(""Pseudo %-20s Genes %,6d Start %,6d "", (dn+"" ""+chr), genes, geneStart); + Globals.prt(String.format(""%,5d %s"", hitGeneMap.size(),msg)); + } + if (hitGeneMap.size()==0) return true; + + cntPseudo[i] += hitGeneMap.size(); + + // pseudo_annot + Globals.rclear(); + String name= ""ID=pseudo-"" + mProj1.getDBName() +""-""+mProj2.getDBName() + + "";"" + annoKey[i] + ""=Not annotated; ""; + + int countBatch=0, cnt=0; + PreparedStatement ps = dbc2.prepareStatement(""insert into pseudo_annot "" + + ""(grp_idx, type, genenum, tag, numhits, name, strand, start, end ) "" + + ""values (?,?,?,?,?,?,?,?,?)""); + for (int gn : hitGeneMap.keySet()) { + Hit ht = hitGeneMap.get(gn); + + ps.setInt(1, grpIdx); + ps.setString(2, type); + ps.setInt(3, gn); + ps.setString(4, gn + ""."" + Globals.pseudoChar); // tag gn.~ + ps.setInt(5, pairIdx); // numhits=pairIdx so it can be remove on Pair Remove + ps.setString(6, name); + ps.setString(7, ht.strand); + ps.setInt(8, ht.start); + ps.setInt(9, ht.end); + ps.addBatch(); + + countBatch++; cnt++; + if (countBatch==1000) { + countBatch=0; + ps.executeBatch(); + Globals.rprt(cnt + "" added pseudo "" + chrPair); + } + } + if (countBatch>0) ps.executeBatch(); + ps.close(); + + // pseudo_hit; first, get newly created idx + rs = dbc2.executeQuery(""select idx, genenum from pseudo_annot "" + + ""where type='"" + type + ""' and grp_idx="" + grpIdx); + while (rs.next()) { + int annoIdx = rs.getInt(1); + int gn = rs.getInt(2); + if (hitGeneMap.containsKey(gn)) // could be from a previous grp pair + hitGeneMap.get(gn).annotIdx = annoIdx; + } + rs.close(); + + countBatch=cnt=0; + ps = dbc2.prepareStatement(""update pseudo_hits set "" + annoStr + ""=? where idx=?"");// gene_overlap stays 0 or 1 + for (Hit ht: hitGeneMap.values()) { + ps.setInt(1, ht.annotIdx); + ps.setInt(2, ht.hitIdx); + ps.addBatch(); + + countBatch++; cnt++; + if (countBatch==1000) { + countBatch = 0; + ps.executeBatch(); + Globals.rprt(cnt + "" added pseudo to hit "" + chrPair); + } + } + if (countBatch>0) ps.executeBatch(); + ps.close(); + + // pseudo_hit_annot; olap, exlap, annot2_idx are all 0 + countBatch=cnt=0; + ps = dbc2.prepareStatement(""insert ignore into pseudo_hits_annot "" + + ""(hit_idx, annot_idx, olap, exlap, annot2_idx) values (?,?,0,0,0)""); + for (Hit ht: hitGeneMap.values()) { + ps.setInt(1, ht.hitIdx); + ps.setInt(2, ht.annotIdx); + ps.addBatch(); + + countBatch++; cnt++; + if (countBatch==1000) { + countBatch=0; + ps.executeBatch(); + Globals.rprt(cnt + "" added pseudo-hit table "" + chrPair); + } + } + if (countBatch>0) ps.executeBatch(); + ps.close(); + Globals.rclear(); + return true; + } + catch (Exception e) {Globals.prt(""""); ErrorReport.print(e, ""add pseudos""); return false;} + } + private class Hit { + int hitIdx, start, end, annotIdx; + String strand; + + private Hit (int hitIdx, int start, int end, String strand) { + this.hitIdx = hitIdx; + this.start = start; + this.end = end; + this.strand = strand; + } + } + } // end Pseudo class +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/DoAlignSynPair.java",".java","13349","372"," package backend; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileWriter; +import java.util.Date; +import java.util.TreeMap; +import javax.swing.JFrame; + +import backend.synteny.SyntenyMain; +import database.DBconn2; +import symap.manager.Mpair; +import symap.manager.Mproject; +import symap.manager.SumFrame; +import symap.manager.ManagerFrame; +import util.Cancelled; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; +import util.Popup; + +/********************************************************** + * DoAlignSynPair; Calls AlignMain, AnchorMain and SyntenyMain; Called from ManagerFrame + * + * When called, DoLoadProj has been executed: + * the Sequence and Annotation have been loaded + * the GeneNum assigned + * Calls AlignMain + * Calls AnchorMain + * calls AnchorMain1 or AnchorMain2, which assign hits to genes + * Note: Demo1 has many genes with identical coords but diff strands; + * both algorithms seem to be inconsistent as to which is assigned as the major hit. + * It makes a difference to collinear, as only the major are processed. + * computes hit# and assigns hitcnt to genes (for Query Singles) + * Calls SyntenyMain + * Calls AnchorPost which creates collinear sets from blocks + */ + +public class DoAlignSynPair extends JFrame { + private static final long serialVersionUID = 1L; + private DBconn2 dbc2; + private Mpair mp; + + public void run(ManagerFrame frame, DBconn2 dbc2, Mpair mp, boolean closeWhenDone, int maxCPUs, boolean bAlignDone) { + + this.dbc2 = dbc2; + this.mp = mp; + + Mproject mProj1 = mp.mProj1; + Mproject mProj2 = mp.mProj2; + String dbName1 = mProj1.getDBName(); + String dbName2 = mProj2.getDBName(); + String toName = (mProj1 == mProj2) ? dbName1 + "" to self (includes mirrored hits)"": dbName1 + "" to "" + dbName2; + + FileWriter syFW = symapLog(mProj1,mProj2); + String alignLogDir = buildLogAlignDir(mProj1,mProj2); + + String msg = (mProj1 == mProj2) ? ""Self-synteny "" + dbName1 + "" ..."" : ""Synteny "" + toName + "" ...""; + + final ProgressDialog diaLog = new ProgressDialog(this, ""Running Synteny"", msg, true, syFW); // write version and date + + String v = (Constants.VERBOSE) ? "" Verbose"" : "" !Verbose""; + diaLog.msgToFileOnly("">>> "" + toName + v); + + if (mp.bPseudo) { + pseudoOnly(diaLog, mProj1, mProj2); + return; + } + if (Constants.CoSET_ONLY) { + collinearOnly(diaLog, mProj1, mProj2); + return; + } + if (Constants.NUMHITS_ONLY) { + numHitsOnly(diaLog, mProj1, mProj2); + return; + } + if (mp.bSynOnly) mp.removeSyntenyFromDB(); + else mp.renewIdx(); // Remove existing and restart, sets projIdx; + + String chgMsg = (bAlignDone) ? mp.getChgClustSyn(Mpair.FILE) : mp.getChgAllParams(Mpair.FILE); // Saved to DB in SumFrame + diaLog.msg(chgMsg); + diaLog.closeWhenDone(); + + final AlignMain aligner = new AlignMain(dbc2, diaLog, mp, maxCPUs, alignLogDir); + if (aligner.mCancelled) return; + + final AnchorMain anchors = new AnchorMain(dbc2, diaLog, mp ); + + final SyntenyMain synteny = new SyntenyMain(dbc2, diaLog, mp ); + + final Thread statusThread = new Thread() { + public void run() { + + while (aligner.notStarted() && !Cancelled.isCancelled()) Utils.sleep(1000); + if (aligner.getNumRemaining() == 0 && aligner.getNumRunning() == 0) return; + if (Cancelled.isCancelled()) return; + + // Alignments\n list errors and current\nStatus + String status = ""\nAlignments: running "" + aligner.getNumRunning() + "", completed "" + aligner.getNumCompleted(); + if (aligner.getNumRemaining()>0) status += "", queued "" + aligner.getNumRemaining(); + if (aligner.getNumErrors()>0) status += "", errors "" + aligner.getNumErrors(); + + diaLog.updateText(""\nRunning alignments:\n"", aligner.getStatusSummary() + status + ""\n""); + + while (aligner.getNumRunning()>0 || aligner.getNumRemaining()>0) { + if (Cancelled.isCancelled()) return; + Utils.sleep(10000); + if (Cancelled.isCancelled()) return; + + // same as before loop + status = ""\nAlignments: running "" + aligner.getNumRunning() + "", completed "" + aligner.getNumCompleted(); + if (aligner.getNumRemaining()>0) status += "", queued "" + aligner.getNumRemaining(); + if (aligner.getNumErrors()>0) status += "", errors "" + aligner.getNumErrors(); + + diaLog.updateText(""\nRunning alignments:\n"", aligner.getStatusSummary() + status + ""\n""); + } + diaLog.updateText(""Alignments:"" , ""Completed "" + aligner.getNumCompleted() + ""\n\n""); + } + }; + + // Perform alignment, load anchors and compute synteny; cancel and success like original + // each 'run' makes a new connection from dbc2 + final Thread alignThread = new Thread() { + public void run() { + boolean success = true; + + try { + long timeStart = Utils.getTime(); + + /** Align **/ + success &= aligner.run(); + + if (Cancelled.isCancelled()) { + diaLog.setVisible(false); + diaLog.setCancelled(); + return; + } + if (!success) { + diaLog.finish(false); + return; + } + + if (Cancelled.isCancelled()) return; + + /** Anchors **/ + long synStart = Utils.getTime(); // need time for symap part only + success = (mp.bSynOnly) ? true : anchors.run( mProj1, mProj2); // add anchors, cluster, number, collinear, pseudo; bSynOnly + + if (Cancelled.isCancelled()) return; + if (!success) { + diaLog.finish(false); + return; + } + + /** Synteny **/ + success &= synteny.run( mProj1, mProj2); + + if (Cancelled.isCancelled()) return; + if (!success) { + diaLog.finish(false); + return; + } + Utils.prtMsgTimeDone(diaLog, ""Complete Clustering + Synteny"", synStart); + + /** Finish **/ + String alignParams = aligner.getParams(); + mp.saveParamsToDB(alignParams); // deletes all pair_props, then add params + + new SumFrame(dbc2, mp); + + diaLog.appendText("">> Summary for "" + toName + ""\n""); + printStats(diaLog, mProj1, mProj2); + + Utils.prtMsgTimeDone(diaLog, ""Complete MUMmer + SyMAP"", timeStart); + } + catch (OutOfMemoryError e) { + success = false; + statusThread.interrupt(); + diaLog.msg( ""Not enough memory - increase 'mem' in symap script""); + Popup.showOutOfMemoryMessage(diaLog); + } + catch (Exception e) { + success = false; + ErrorReport.print(e,""Running alignment""); + statusThread.interrupt(); + } + diaLog.finish(success); + } + }; + + diaLog.addActionListener( new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.out.println(e.getActionCommand()); + // Stop aligner and wait on monitor threads to finish + aligner.interrupt(); + anchors.interrupt(); + try { + alignThread.wait(5000); + statusThread.wait(5000); + } + catch (Exception e2) { } + + // Threads should be done by now, but kill just in case + alignThread.interrupt(); + statusThread.interrupt(); + + // Close dialog + diaLog.setVisible(false); + if (e.getActionCommand().equals(""Cancel"")) { + diaLog.setCancelled(); + Cancelled.cancel(); + } + } + }); + + alignThread.start(); + statusThread.start(); + diaLog.start(); // blocks until thread finishes or user cancels + + if (diaLog.wasCancelled()) { // Remove partially-loaded alignment + try { + Thread.sleep(1000); + String msgx = ""Confirm: Remove "" + mp.toString() + "" from database (slow if large database)"" + + ""\nCancel: The user removes the database and starts over""; + + if (Popup.showConfirm2(""Remove pair"", msgx)) { + System.out.println(""Cancel alignment (removing alignment from DB)""); + mp.removePairFromDB(true); // redo numHits; + System.out.println(""Removal complete""); + } + else System.out.println(""Remove database and restart""); + } + catch (Exception e) { ErrorReport.print(e, ""Removing alignment"");} + } + else if (closeWhenDone) { + diaLog.dispose(); + } + + System.out.println(""--------------------------------------------------""); + frame.refreshMenu(); + try { + if (syFW != null) { + if (Cancelled.isCancelled()) syFW.write(""Cancelled""); + syFW.write(""\n-------------- done "" + new Date().toString() + "" --------------------\n""); + syFW.close(); + } + } + catch (Exception e) {} + } // end of run + /**********************************************************************/ + private FileWriter symapLog(Mproject p1, Mproject p2) { + FileWriter ret = null; + try { + File pd = new File(Constants.logDir); + if (!pd.isDirectory()) pd.mkdir(); + + String pairDir = Constants.logDir + p1.getDBName() + Constants.projTo + p2.getDBName(); + pd = new File(pairDir); + if (!pd.isDirectory()) pd.mkdir(); + + File lf = new File(pd,Constants.syntenyLog); + ret = new FileWriter(lf, true); // append + System.out.println(""\nAppend to log file: "" + + pairDir + ""/"" + Constants.syntenyLog + "" (Length "" + Utilities.kMText(lf.length()) + "")""); + } + catch (Exception e) {ErrorReport.print(e, ""Creating log file"");} + return ret; + } + + private void printStats(ProgressDialog prog, Mproject p1, Mproject p2) { + int pairIdx = mp.getPairIdx(); + if (pairIdx<=0) return; + + TreeMap counts = new TreeMap(); + + try { + int cnt = dbc2.executeCount(""select count(*) from pseudo_hits where pair_idx="" + pairIdx); + counts.put(""nhits"", cnt); + + cnt = dbc2.executeCount(""select count(*) from pseudo_block_hits as pbh join pseudo_hits as ph on pbh.hit_idx=ph.idx "" + + "" where ph.pair_idx="" + pairIdx); + counts.put(""blkhits"", cnt); + + cnt = dbc2.executeCount(""select count(*) from pseudo_hits where gene_overlap > 0 and pair_idx="" + pairIdx); + counts.put(""genehits"", cnt); + + cnt = dbc2.executeCount(""select count(*) from blocks where pair_idx="" + pairIdx); + counts.put(""blocks"", cnt); + } + catch (Exception e) {ErrorReport.print(e, ""Gtting counts""); } + + Utils.prtNumMsg(prog, counts.get(""nhits""), ""hits""); + Utils.prtNumMsg(prog, counts.get(""blocks""), ""synteny blocks""); + Utils.prtNumMsg(prog, counts.get(""genehits""), ""gene hits""); + Utils.prtNumMsg(prog, counts.get(""blkhits""), ""synteny hits""); + } + + private String buildLogAlignDir(Mproject p1, Mproject p2) { + try { + String logName = Constants.logDir + p1.getDBName() + Constants.projTo + p2.getDBName(); + if (util.FileDir.dirExists(logName)) System.out.println(""Log alignments in directory: "" + logName); + else util.FileDir.checkCreateDir(logName, true /* bPrt */); + return logName + ""/""; + } + catch (Exception e){ErrorReport.print(e, ""Creating log file"");} + return null; + } + /*** Add Pseudo - parameters pull-down - permanent ***/ + private void pseudoOnly(ProgressDialog mLog, Mproject mProj1, Mproject mProj2) { + try { + mLog.msg(""Only add pseudo-genes""); + + String st = ""SELECT idx FROM pairs WHERE proj1_idx='"" + mProj1.getIdx() + ""' AND proj2_idx='"" + mProj2.getIdx() +""'""; + int mPairIdx = dbc2.getIdx(st); + if (mPairIdx<=0) { + mLog.msg(""Cannot find project pair in database for "" + mProj1.getDisplayName() + "","" + mProj2.getDisplayName()); + dbc2.close(); return; + } + AnchorMain anchors = new AnchorMain(dbc2, mLog, mp); + anchors.addPseudoFromFlag(); + + String params = dbc2.executeString(""select params from pairs where idx="" + mp.getPairIdx()); + mp.saveParamsToDB(params); // re-enter params and update NOW(), then update pair_props + + new SumFrame(dbc2, mp, ""Number pseudo""); // only so it will show the updated version + System.out.println(""--------------------------------------------------""); + } + catch (Exception e){ErrorReport.print(e, ""Creating log file""); } + } + /** Collinear only: -cs command line, visible when recent changed **********************/ + private void collinearOnly(ProgressDialog mLog, Mproject mProj1, Mproject mProj2) { + try { + mLog.msg(""Only run collinear set algorithm""); + if (!mProj1.hasGenes() || !mProj2.hasGenes()) { + mLog.msg(""Both projects must have genes for the collinear set algorithm""); + dbc2.close(); return; + } + + String st = ""SELECT idx FROM pairs WHERE proj1_idx='"" + mProj1.getIdx() + ""' AND proj2_idx='"" + mProj2.getIdx() +""'""; + int mPairIdx = dbc2.getIdx(st); + if (mPairIdx<=0) { + mLog.msg(""Cannot find project pair in database for "" + mProj1.getDisplayName() + "","" + mProj2.getDisplayName()); + dbc2.close(); return; + } + AnchorPost collinear = new AnchorPost(mPairIdx, mProj1, mProj2, dbc2, mLog); + collinear.collinearSets(); + + mp.saveUpdate(); + new SumFrame(dbc2, mp); + System.out.println(""--------------------------------------------------""); + } + catch (Exception e){ErrorReport.print(e, ""Creating log file""); } + } + + /*** Update NumHits: -nh command line, visible when recent change ***/ + private void numHitsOnly(ProgressDialog mLog, Mproject mProj1, Mproject mProj2) { + try { + mLog.msg(""Compute NumHits Only...""); + if (!mProj1.hasGenes() || !mProj2.hasGenes()) { + mLog.msg(""Both projects must have genes to have numHits""); + dbc2.close(); return; + } + AnchorMain anchors = new AnchorMain(dbc2, mLog, mp); + anchors.saveAnnoHitCnt(true); + new SumFrame(dbc2, mp, ""Recompute numHits""); // only so it will show the updated version + System.out.println(""--------------------------------------------------""); + } + catch (Exception e){ErrorReport.print(e, ""Creating log file""); } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/AnnotLoadPost.java",".java","7888","255","package backend; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Vector; +import java.util.HashMap; +import java.util.TreeMap; + +import symap.Globals; +import symap.manager.Mproject; +import database.DBconn2; +import util.Cancelled; +import util.ErrorReport; +import util.ProgressDialog; + +/****************************************************** +* AnchorsPost uses genenum for collinear computation +* The 2D gene placement algorithm uses the pseudo_annot.genenum but not the suffix from the pseudo_annot.tag +*/ + +public class AnnotLoadPost { + private final int MAX_GAP_FOR_OLAP=0; + private ProgressDialog plog; + private DBconn2 dbc2; + private Mproject mProj; + + private HashMap geneMap = new HashMap (); + private Vector geneOrder = new Vector (); + private int genenum; + private boolean isSuccess=true; + private int totexonUpdate=0, totgeneUpdate=0, totOverlap=0, totContained=0, totGeneNum=0; + + public AnnotLoadPost(Mproject project, DBconn2 dbc2, ProgressDialog log) { + this.mProj = project; + this.dbc2 = dbc2; + this.plog = log; + } + public boolean run(boolean hasAnnot) { + try { + if (!hasAnnot) { + plog.msg("" No assignment of #exons and tags to genes""); + return true; + } + plog.msg("" Assign #exons and tags to genes""); + + dbc2.executeUpdate(""update pseudo_annot, xgroups set pseudo_annot.genenum=0 "" + + ""where pseudo_annot.grp_idx=xgroups.idx and xgroups.proj_idx="" + mProj.getIdx()); + + TreeMap grpIdxList = mProj.getGrpIdxMap(); + for (int idx : grpIdxList.keySet()){ + computeGeneNum(idx, grpIdxList.get(idx)); if (!isSuccess) return isSuccess; + computeTags(idx, grpIdxList.get(idx)); if (!isSuccess) return isSuccess; + } + Globals.rclear(); + Utils.prtNumMsg(plog, totGeneNum, ""Unique gene numbers""); + Utils.prtNumMsg(plog, totOverlap, ""Overlapping genes""); + Utils.prtNumMsg(plog, totContained, ""Contained genes""); + + Utils.prtNumMsg(plog, totgeneUpdate, ""Gene update""); + Utils.prtNumMsg(plog, totexonUpdate, ""Exon update (avg "" + + String.format(""%.3f"", (float) totexonUpdate/(float)totgeneUpdate) + "")""); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Post process annotation""); return false;} + } + /********************************************************* + * Assign Gene# + */ + private void computeGeneNum(int grpIdx, String grpName) { + try { + ResultSet rs = dbc2.executeQuery( + ""select idx,start,end from pseudo_annot where grp_idx="" + grpIdx + + "" and type='gene' order by start asc""); + + while (rs.next()){ + GeneData gd = new GeneData (); + gd.idx = rs.getInt(1); + gd.start = rs.getInt(2); + gd.end = rs.getInt(3); + geneMap.put(gd.idx, gd); + geneOrder.add(gd.idx); + } + if (Cancelled.isCancelled()) {isSuccess=false;return;} + + Vector numList = new Vector (); + for (int idx : geneOrder) { + GeneData gd = geneMap.get(idx); + + boolean bUseNum=false; + + // go through all because because isContained and isOverlap add counts + for (GeneData gx : numList) { + if (gx.isContained(gd)) bUseNum=true; + else if (gx.isOverlap(gd)) bUseNum=true; + } + if (bUseNum) { + gd.genenum = genenum; + numList.add(gd); + } + else { + assignSuf(genenum, numList); // end current num + numList.clear(); + + genenum++; // start new num + gd.genenum = genenum; + numList.add(gd); + } + } + assignSuf(genenum, numList); // last one + + for (GeneData gd : geneMap.values()) gd.tag = gd.genenum + ""."" + gd.suffix; + + Globals.rprt(grpName + "" "" + genenum + "" genes""); + totGeneNum+= genenum; + genenum=0; + } + catch (Exception e) {ErrorReport.print(e, ""Compute gene order""); isSuccess=false;} + } + private void assignSuf(int genenum, Vector numList) { + if (numList.size()<=1) return; + + char [] alpha = {'a','b','c','d','e','f','g','h', 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; + int ialpha=0, icnt=1; + + // assign gd.suf to each + boolean isRepeat=false; + for (GeneData gd : numList) { + gd.suffix += alpha[ialpha++]+""""; + if (isRepeat) gd.suffix += icnt+""""; + + if (ialpha>=alpha.length) { + if (!isRepeat) { + isRepeat=true; + Globals.tprt(numList.size() + "" overlapping genes for gene #"" + genenum); + } + ialpha=0; + icnt++; + } + if (Globals.TRACE) { + if (gd.cntHasIn>3 || gd.cntOverlap>3) + Globals.tprt(""Gene #"" + gd.genenum + gd.suffix + + "" has contained "" + gd.cntHasIn + "" overlap "" + gd.cntOverlap); + if (gd.cntIsIn>1) + Globals.tprt(""Gene #"" + gd.genenum + gd.suffix + "" is contained in "" + gd.cntIsIn + "" genes""); + } + } + } + /************************************************************ + * Assign tags for Genes and Exons + */ + private void computeTags(int grpIdx, String grpName) { + try { + // Create exon list per gene; provides exon cnt for gene, and exonIdx for tag update + ResultSet rs = dbc2.executeQuery(""select idx, gene_idx, start, end from pseudo_annot "" + + ""where grp_idx="" + grpIdx + "" and type='exon'""); + + int err=0; + while (rs.next()) { + int idx = rs.getInt(1); + int gene_idx = rs.getInt(2); + + if (geneMap.containsKey(gene_idx)) { + GeneData gd = geneMap.get(gene_idx); + gd.exonIdx.add(idx); + gd.exonLen += (rs.getInt(4)-rs.getInt(3)+1); + } + else { + err++; + if (err>10) break; + System.err.println(""Unexpected GFF input: no gene "" + gene_idx + "" for exon "" + idx); + } + } + rs.close(); + if (Cancelled.isCancelled()) {isSuccess=false;return;} + + // WRITE write to db; names parsed in Annotation.java getLongDescription + PreparedStatement ps = dbc2.prepareStatement( + ""update pseudo_annot set genenum=?, tag=? where idx=?""); + + int exonUpdate=0, geneUpdate=0, cntBatch=0; + + for (int geneidx : geneOrder) { + GeneData gene = geneMap.get(geneidx); + + // Annotation.java and Sequence.java depends on this format! Gene #dn (d, dbp( + String elen = String.format("" %,d"", gene.exonLen); + String tag = gene.tag + "" ("" + gene.exonIdx.size() + elen + "")""; + + // update gene + ps.setInt(1, gene.genenum); + ps.setString(2, tag); + ps.setInt(3, gene.idx); + ps.addBatch(); + cntBatch++; geneUpdate++; + + // update gene's exons + int nExon=1; + for (int i=0; i5000) { + if (Cancelled.isCancelled()) {isSuccess=false;return;} + ps.executeBatch(); + cntBatch=0; + Globals.rprt(grpName + "" count "" + exonUpdate + "" exons for "" + geneUpdate + "" genes""); + } + } + Globals.rclear(); + if (cntBatch>0) ps.executeBatch(); + totexonUpdate += exonUpdate; + totgeneUpdate += geneUpdate; + + geneMap.clear(); geneOrder.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Assign tags""); isSuccess=false;} + } + + /************************************************************/ + private class GeneData { + int idx, start, end, genenum; + String tag; + String suffix=""""; + Vector exonIdx = new Vector (); + int exonLen=0; + + boolean isContained(GeneData gd) { + if (gd.start >= start && gd.end <= end) { + cntHasIn++; + gd.cntIsIn++; + totContained++; + return true; + } + return false; + } + private boolean isOverlap(GeneData gd) { + int gap = Math.min(end,gd.end) - Math.max(start,gd.start); + if (gap <= MAX_GAP_FOR_OLAP) return false; + cntOverlap++; + gd.cntOverlap++; + totOverlap++; + return true; + } + int cntHasIn=0, cntIsIn=0, cntOverlap=0; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/SeqLoadMain.java",".java","14993","426","package backend; + +import java.io.File; +import java.io.BufferedReader; +import java.util.TreeSet; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.sql.ResultSet; + +import database.DBconn2; +import symap.Globals; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ErrorReport; +import util.ProgressDialog; +import blockview.BlockViewFrame; + +/***************************************** + * Load chromosome/draft/LG sequences to SyMAP database. + * Also fix bad chars if any + */ +public class SeqLoadMain { + static int projIdx = 0; + private static final int CHUNK_SIZE = Constants.CHUNK_SIZE; + private static final int MAX_GRPS = BlockViewFrame.MAX_GRPS; + private static final int MAX_COLORS = BlockViewFrame.maxColors; + private Mproject mProj; + private DBconn2 tdbc2=null; + private ProgressDialog plog; + + private Vector seqFiles = new Vector(); + private String saveSeqDir="""", projName; + private long modDirDate=0; + private int totalnSeqs=0, cntFile=0, totalSeqIgnore=0, totalBasesWritten=0; + private Vector grpList = new Vector(); + + protected boolean run(DBconn2 dbc2, ProgressDialog plog, Mproject mProj) throws Exception { + try { + tdbc2 = new DBconn2(""SeqLoad-""+ DBconn2.getNumConn(), dbc2); + this.plog = plog; + this.mProj = mProj; + projName = mProj.getDBName(); + projIdx = mProj.getIdx(); + + long startTime = Utils.getTime(); + plog.msg(""Loading sequences for "" + projName); + + if (!getSeqFiles()) return false; + if (Cancelled.isCancelled()) return rtError(""User cancelled""); + + if (!loadSeqFiles()) return false; + if (Cancelled.isCancelled()) return rtError(""User cancelled""); + + /* ************************************************************ */ + // print on View + mProj.saveProjParam(""proj_seq_date"", Utils.getDateStr(modDirDate)); + mProj.saveProjParam(""proj_seq_dir"", saveSeqDir); + + if (cntFile>1) { + plog.msg(""Total:""); + if (totalSeqIgnore>0) + plog.msg(String.format(""%,5d sequences %,10d bases %,4d sequences ignored"", totalnSeqs, totalBasesWritten, totalSeqIgnore)); + else plog.msg(String.format(""%,5d sequences %,10d bases "", totalnSeqs, totalBasesWritten)); + } + if (totalnSeqs >= MAX_COLORS) + plog.msg(""+++ There are "" + MAX_COLORS + "" distinct colors for blocks -- there will be duplicates""); + + if (totalnSeqs >= MAX_GRPS){ + plog.msg(""+++ More than "" + MAX_GRPS + "" sequences loaded!""); + plog.msg("" Unless you are ordering draft contigs,""); + plog.msg("" It is recommended to reload with a higher Minimum Length setting, before proceeding""); + plog.msg("" Use script/lenFasta.pl to determine Minimum Length to use to reduce number of loaded sequences""); + } + updateSortOrder(grpList); + tdbc2.close(); + + Utils.prtTimeMemUsage(plog, ""Finish load sequences"", startTime); + } catch (Exception e) {ErrorReport.print(e, ""Seq Load Main""); return false;} + return true; + } + /*************************************************************** + * Get vector of sequence files + */ + private boolean getSeqFiles() { + try { + String projDir = Constants.seqDataDir + projName; + String seqFileName = mProj.getSequenceFile(); + + if (seqFileName.equals("""")) { + String seqDir = projDir + Constants.seqSeqDataDir; // created with Add Project + plog.msg("" Sequence_files "" + seqDir + "" (Default location)""); + + if (!util.FileDir.pathExists(seqDir)) { + return rtError(""Sequence files not found in "" + seqDir); + } + File sdf = new File(seqDir); + if (sdf.exists() && sdf.isDirectory()) { + saveSeqDir = seqDir; + modDirDate = sdf.lastModified(); + + File[] fs = sdf.listFiles(); + Arrays.sort(fs); // If separate files, order is random; this isn't necessary, but nice + + for (File f2 : fs) { + if (!f2.isFile() || f2.isHidden()) continue; // macOS add ._ files in tar + String name = f2.getAbsolutePath(); + for (String suf : Constants.fastaFile) { + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + seqFiles.add(f2); + break; + } + } + } + } + else { + return rtError(""Cannot find sequence directory "" + seqDir); + } + } + else { + String[] fileList = seqFileName.split("",""); + String xxx = (fileList.length>1) ? (fileList.length + "" files "") : seqFileName; + plog.msg("" User specified sequence files - "" + xxx); + for (String filstr : fileList) { + if (filstr == null) continue; + if (filstr.trim().equals("""")) continue; + File f = new File(filstr); + + if (!f.exists()) { + plog.msg(""*** Cannot find sequence file "" + filstr + "" - try to continue...""); + } + else if (f.isDirectory()) { + saveSeqDir = f.getAbsolutePath(); + modDirDate = f.lastModified(); + + for (File f2 : f.listFiles()) { + if (!f2.isFile() || f2.isHidden()) continue; // macOS add ._ files in tar + + String name = f2.getAbsolutePath(); + for (String suf : Constants.fastaFile) { + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + seqFiles.add(f2); + break; + } + } + } + } + else { + saveSeqDir = Utils.pathOnly(f.getAbsolutePath()); + modDirDate = f.lastModified(); + + String name = f.getAbsolutePath(); + for (String suf : Constants.fastaFile) { + if (name.endsWith(suf) || name.endsWith(suf+"".gz"")) { + seqFiles.add(f); + break; + } + } + } + } + } + if (seqFiles.size()==0) + return rtError(""No sequence files ending in "" + Constants.fastaList + ""!!""); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Getting sequence files""); return false;} + } + /*************************************************************** + * Load sequence files + */ + private boolean loadSeqFiles() { + try { + String prefix = mProj.getGrpPrefix(); + if (prefix.contentEquals("""")) plog.msg("" No sequence prefix supplied (See Parameters - Group prefix)""); + else plog.msg("" Load sequences with '"" + prefix + ""' prefix (See Parameters - Group prefix)""); + + int minSize = mProj.getMinSize(), readSeq=0; + plog.msg(String.format("" Load sequences > %,dbp (See Parameters - Minimum length)"", minSize)); + + TreeSet grpNamesSeen = new TreeSet(); + TreeSet grpFullNamesSeen = new TreeSet(); + + // For all files, Scan and upload the sequences + for (File f : seqFiles) { + int nBadCharLines = 0, seqIgnore = -1, seqPrefixIgnore=0, nSeqs=0; + long basesWritten = 0; + + cntFile++; + plog.msg(""Reading "" + f.getName()); + + StringBuffer curSeq = new StringBuffer(); + String grpName = null, grpFullName = null, firstTok=null, line; + + BufferedReader fh = Utils.openGZIP(f.getAbsolutePath()); + + while ((line = fh.readLine()) != null) { + + if (line.startsWith(""#"") || line.isEmpty()) continue; + + if (line.startsWith("">"")) { + if (grpName != null && curSeq.length() >= minSize) { + if (!grpNamesSeen.contains(grpName) && !grpFullNamesSeen.contains(grpFullName)){ + grpList.add(grpName); + grpNamesSeen.add(grpName); + grpFullNamesSeen.add(grpFullName); + nSeqs++; + basesWritten += curSeq.length(); + Globals.rprt(String.format(""%s: %,d"", grpName,curSeq.length())); + + // load sequence + String chrSeq = curSeq.toString(); // prevent two copies in memory at once + curSeq.setLength(0); + + uploadSequence(grpName,grpFullName,chrSeq,f.getName(),totalnSeqs+1); + + chrSeq = null; + System.gc(); + } + else { + plog.msgToFile(""+++ Dup seqid: "" + grpName + "" ("" + firstTok + "") skipping...""); + } + } else seqIgnore++; + + readSeq++; + if (readSeq%100 == 0) Globals.rprt(""Read sequences "" + readSeq); + + grpName = null; firstTok = grpFullName = """"; + curSeq.setLength(0); + + if (!parseHasPrefix(line, prefix)){ + seqPrefixIgnore++; + if (seqPrefixIgnore<=3) plog.msgToFile(""+++ Invalid prefix, ignore: "" + line); + if (seqPrefixIgnore==3) plog.msgToFile(""+++ Surpressing further invalid prefix ""); + continue; + } + + grpName = Utils.parseGrpName(line,prefix); + grpFullName = Utils.parseGrpFullName(line); + if (grpName==null || grpFullName==null || grpName.equals("""") || grpFullName.equals("""")){ + return rtError(""Unable to parse group name from:"" + line); + } + String [] tl = line.split("" ""); + firstTok = (tl.length>0) ? tl[0] : Utils.parseGrpFullName(line); + } + else if (grpName!=null) { // sequence for valid grpName + line = line.replaceAll(""\\s+"",""""); + + if (line.matches("".*[^agctnAGCTN].*"")) { + nBadCharLines++; + line = line.replaceAll(""[^agctnAGCTN]"", ""N""); + } + curSeq.append(line); + } + + if (Cancelled.isCancelled()) { + fh.close(); + return rtError(""User cancelled""); + } + } // end reading file + fh.close(); + + if (grpName != null && curSeq.length() >= minSize) {// load last sequence + grpList.add(grpName); + nSeqs++; + basesWritten += curSeq.length(); + Globals.rprt(String.format(""%s: %,d"", grpName,curSeq.length())); + + String chrSeq = curSeq.toString(); + curSeq.setLength(0); + uploadSequence(grpName, grpFullName, chrSeq, f.getName(), totalnSeqs+1); + chrSeq=""""; + } + else if (curSeq.length()>0) seqIgnore++; + curSeq.setLength(0); + + if (seqIgnore==0) plog.msg(String.format(""%,5d sequences %,10d bases"", nSeqs, basesWritten)); + else plog.msg(String.format(""%,5d sequences %,10d bases %,4d sequences ignore"", nSeqs, basesWritten, seqIgnore)); + + if (nBadCharLines > 0) { + plog.msg(""+++ "" + nBadCharLines + "" lines contain characters that are not AGCT; replaced by N""); + mProj.saveProjParam(""badCharLines"","""" + nBadCharLines); + } + totalSeqIgnore += seqIgnore; + totalBasesWritten += basesWritten; + totalnSeqs += nSeqs; + } // end loop through files + + if (totalnSeqs==0) return rtError( ""No sequences were loaded! Read the documentation on 'input'.""); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Loading sequences""); return rtError(""Fatal error"");} + catch (OutOfMemoryError e){ + tdbc2.shutdown(); + ErrorReport.prtMem(); + System.out.println(""\n\nOut of memory! Modify the symap script 'mem=' line to specify higher memory.\n\n""); + System.exit(0); + return false; + } + } + private boolean parseHasPrefix(String name, String prefix){ + if (prefix.equals("""")) return true; + + String regx = ""\\s*("" + prefix + "")(\\w+)\\s?.*""; + Pattern pat = Pattern.compile(regx,Pattern.CASE_INSENSITIVE); + + String n = name + "" ""; // hack, otherwise we need two cases in the regex + if (n.startsWith("">"")) n = n.substring(1); + Matcher m = pat.matcher(n); + if (m.matches()) return true; + return false; + } + /***********************************************************************/ + private void uploadSequence(String grp, String fullname, String seq, String file, int order) { + try { + // First, create the group; FIXME check for duplicates + tdbc2.executeUpdate(""INSERT INTO xgroups VALUES('0','"" + projIdx + ""','"" + + grp + ""','"" + fullname + ""',"" + order + "",'0')"" ); + String sql = ""select max(idx) as maxidx from xgroups where proj_idx="" + projIdx; + ResultSet rs = tdbc2.executeQuery(sql); + rs.next(); + int grpIdx = rs.getInt(""maxidx""); + + // max int in java is 2,147,483,647 (max human chr is 249M); can't test, run out of memory trying + int seqlen = -1; + try {seqlen = seq.length();} // may set to a negative number + catch (Exception e) {seqlen = -1;} + if (seqlen<0) { + String x = String.format(""Chromosome sequence from file %s is length %,d"", file, seq.length()); + ErrorReport.print(x); + x = String.format(""The maximum allowed is %,d"", Integer.MAX_VALUE); + ErrorReport.die(x); + } + tdbc2.executeUpdate(""insert into pseudos (grp_idx,file,length) values("" + grpIdx + "",'"" + file + ""',"" + seqlen + "")""); + + // Finally, upload the sequence in chunks + for (int chunk = 0; chunk*CHUNK_SIZE < seq.length(); chunk++) { + int start = chunk*CHUNK_SIZE; + int len = Math.min(CHUNK_SIZE, seq.length() - start ); + + String cseq = seq.substring(start,start + len ); + String st = ""INSERT INTO pseudo_seq2 VALUES('"" + grpIdx + ""','"" + chunk + ""','"" + cseq + ""')""; + tdbc2.executeUpdate(st); + } + } + catch (Exception e) { + ErrorReport.print(e, ""Fail load sequence: "" + projIdx + ""','"" + grp + ""','"" + fullname + ""',"" + order); + Globals.prt("" This can happen if a project was just removed and another added immediately.""); + } + } + /**************************************************************************/ + private boolean rtError(String msg) { + plog.msgToFile(""*** "" + msg); + ErrorCount.inc(); + tdbc2.close(); + + try { + if (projIdx > 0) { + mProj.removeProjectFromDB(); + plog.msg(""Remove partially loaded project from database""); + } + } + catch (Exception e) {ErrorReport.print(e, ""Removing project due to load failure"");} + + return false; + } + /***********************************************************************/ + private void updateSortOrder(Vector grpList) { + try { + int minIdx = tdbc2.executeCount(""select min(idx) from xgroups where proj_idx="" + projIdx); + tdbc2.executeUpdate(""update xgroups set sort_order = idx+1-"" + minIdx + "" where proj_idx="" + projIdx); + GroupSorter gs = new GroupSorter(); + + Collections.sort(grpList,gs); + + for (int i = 1; i <= grpList.size(); i++) { + String grp = grpList.get(i-1); + tdbc2.executeUpdate(""update xgroups set sort_order="" + i + "" where proj_idx="" + projIdx + + "" and name='"" + grp + ""'""); + } + } + catch (Exception e) {ErrorReport.print(e, ""Loading sequence - fail ordering them""); }; + } + // Calculate order to be saved in xgroups + private class GroupSorter implements Comparator{ + public GroupSorter(){} + + // If prefix defined in parameters, it is stripped off already + public int compare(String g1, String g2) { + + if (g1.equals(g2)) return 0; + boolean areNumbers = true; + try { + Integer.parseInt(g1); + Integer.parseInt(g2); + } + catch(Exception e) {areNumbers = false;} + + if (areNumbers) return Integer.parseInt(g1) - Integer.parseInt(g2); + + int nMatch = 0; // Look for a matching prefix; + while (nMatch < g1.length() && nMatch < g2.length() && g1.charAt(nMatch)==g2.charAt(nMatch)) nMatch++; + if(nMatch == g1.length()) return -1; // all of g1 matched, hence must come before g2 alphabetically + if(nMatch == g2.length()) return 1; + + String suff1 = g1.substring(nMatch); + String suff2 = g2.substring(nMatch); + + + areNumbers = true; // are these suffixes numeric?? + try { + Integer.parseInt(suff1); + Integer.parseInt(suff2); + } + catch(Exception e) {areNumbers = false;} + + if (areNumbers) return Integer.parseInt(suff1) - Integer.parseInt(suff2); + + return g1.compareTo(g2); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/Arg.java",".java","18195","402","package backend.anchor2; + +import backend.Constants; +import symap.Globals; + +/*************************************************************** + * Constants and input Parameters for backend.anchor2 only + */ +public class Arg { + // Command line; all default false + protected static boolean VB = (Globals.TRACE || Constants.VERBOSE); + protected static boolean TRACE = Globals.TRACE; // for developers + protected static boolean WRONG_STRAND_PRT = Constants.WRONG_STRAND_PRT; // Print wrong strand + + // Useful constants + protected static char UNK='?', MAJOR='+', MINOR='*', FILTER='F', IGN='I', PILE='P'; // HitPair flags; MAJOR and MINOR saved + protected static String FLAG_DESC = ""? unknown; + major; * minor; F filter; I Ignore; P pile""; + + protected static final int NONE = -1; + protected static final int T=0, Q=1, TQ=2; + protected static final String [] side = {""T"", ""Q"", ""TQ""}; + + protected static final int typeUnk=0, type0=1, type1t=2, type1q=3, type2=4; + protected static final String [] strType = {""Unk"",""G0"", ""G1t"", ""G1q"", ""G2""}; + protected static final String sEE=""EE"", sEI=""EI"", sIE=""IE"", sII=""II"", sEn=""En"", snE=""nE"", sIn=""In"", snI=""nI"", snn=""nn""; // HitPair.htype + + // defaults from AI Chat Bot; used in setLenFromGenes + protected static final int plantIntronLen = 500, plantGeneLen = 3500; // plants (introns 150-500, genes 2k-5k) + protected static final int mamIntronLen = 4500, mamGeneLen = 25000; // mammalians (introns 3k-5.4k, genes 20k-30k) + + // G2 RBH, !RBH - the base values for the parameter scales + private static double pExonScale=1.0, pGeneScale=1.0, pG0LenScale=1.0, pLenScale=1.0; + private static final double [] fLowExonCov2 = {20,25}; // exon coverage and percent fraction of each exon + private static final double [] fLowGeneCov2 = {25,35, 50}; // hit-gene overlap/genL + public static int iPpMinGxLen= 300; // access in symap.manager.PairParams + private static final int [] fMinLen = {300, 1000, 5000, 10000}; // 300 is documented as smallest non-perfect + + protected static final double dLenRatio=0.5; // g1 and g0; + private static final double [] dMinCov = {60.0, 80.0, 97.0}; // used directly with iPpMinMaxCov in g2 and g1 for gene&exon + + /***** Constants/Heuristics in code ****/ + // Set in setFromParams using above final values and parameter scale values + private static double [] dPpLowExonCov2={0,0}, dPpLowGeneCov2={0,0,0}; // scale * fLow... + private static int [] iPpMinLen= {0,0,0,0}; // fMinLen * lenScale; usually for xMaxLen, but g1 exon + public static int iPpMinG0Len= 1000; // access in symap.manager.PairParams + private static double dMinG0Cov = 40.0; + + // Set from gene models: see setLenFromGenes + protected static int iGmIntronLen2x = (plantIntronLen+mamIntronLen)/2; // G0 max intron; G1 special case; default for no anno + protected static int iGmIntronLen4x = (int) ((plantIntronLen+mamIntronLen)/1.5); // G1 max intron + protected static int iGmIntronLenRm = 1000; + protected static int iGmGeneLen = (plantGeneLen+mamGeneLen)/2; // not used + protected static int [] iGmLowHitGapCov2 = {20,40,60}; // set in setLen; hitScore = (summed-merged-hits/clustered-hit-length)% + + // Other + protected static final double minEE=0.001; // HitPair: ExonScore great enough to be called exon, e.g. EE type + + // GrpPairPile + protected static boolean pEE=true, pEI=true, pEn=false, pII=false, pIn=false; // piles to keep; set directly in AnchorMain + protected static int topN = 2; // set from AnchorMain2 from Pair Parameters + protected static final double bigOlap = 0.4; + /******************************************* + * Functions + ******************************************/ + protected static void setVB() {VB = Globals.TRACE || Constants.VERBOSE;} + + /* Set from AnchorMain2 Parameters */ + protected static String setFromParams(double exonScale, double geneScale, double g0Scale, double lenScale) { + pExonScale = exonScale; pGeneScale = geneScale; pG0LenScale = g0Scale; pLenScale = lenScale; + + for (int i=0; i1500 + if (iGmIntronLen4x15000) iGmIntronLen4x = 15000; + + iGmIntronLen2x = intronAvg[T]+intronAvg[Q]; + if (iGmIntronLen2xmamIntronLen*2) iGmIntronLen2x = mamIntronLen*2; // rather have multiple clusters than too long gaps + + iGmIntronLenRm = (int) (iGmIntronLen2x * 0.5); + if (iGmIntronLenRm<1000) iGmIntronLenRm = 1000; // even for plants, dangling <1000 is okay + if (iGmIntronLenRm>2500) iGmIntronLenRm = 2500; // mammal + + iGmLowHitGapCov2[0] = (int) Math.round((exonGeneCov[T]+exonGeneCov[Q])/2); // 7% for hsa/pan; 60% cabb/arab + if (iGmLowHitGapCov2[0]>20) iGmLowHitGapCov2[0]=20; + + iGmLowHitGapCov2[1] = iGmLowHitGapCov2[0]*2; + iGmLowHitGapCov2[2] = iGmLowHitGapCov2[0]*3; // for non-gene + + iGmGeneLen = Math.min(geneAvg[T],geneAvg[Q]); + + String m1 = String.format(""Gene models: intron 4x %,d 2x %,d rm %,d hitGapCov %,d %,d %,d from gene-exon cover"", + iGmIntronLen4x, iGmIntronLen2x, iGmIntronLenRm, iGmLowHitGapCov2[0], iGmLowHitGapCov2[1], iGmLowHitGapCov2[2]); + + return ""#"" + m1+ ""\n""; // remark for trace files and stdout + } + + /***** functions for scoring *****/ + /* G2 */ + + /* G2 de-weed: This weeds out low scores, where there are many in hsa-pan */ + protected static boolean bG2isOkay(HitPair hpr) { + double e=0.1, g=2.0; + if (hpr.pExonHitCov[T]iPpMinLen[1] && (bMinQ && bMinT)) return bRet(hpr, "" Plen1"", true); //1000 + if (hpr.xMaxCov>iPpMinLen[2] && (bMinQ || bMinT)) return bRet(hpr, "" Plen2"", true); //5000 + if (hpr.xMaxCov>iPpMinLen[3] && hpr.lenRatio>dLenRatio && + hpr.pExonHitFrac[T]>dMinCov[0] && hpr.pExonHitFrac[Q]>dMinCov[0]) return bRet(hpr, "" Plen3"", true); // 10000 + //Reject + if (hpr.xMaxCov0 && cntQ>0) { + if ((!bMinQ && !bMinT) || !hpr.htype.equals(sEE)) return bRet(hpr, "" MAJ""+(cntT+cntQ), false); + } + + // Scaled exon, gene, hit tests -- these are fairly loose to try to get hits to genes that do not have one + if (idx==1 && cntT==0 && cntQ==0) idx=0; // neither has major, so be lenient + + cntT=cntQ=0; + String note="" ""; + + double eOlap = dPpLowExonCov2[idx]; + if (hpr.pExonHitCov[T] > eOlap || hpr.pExonHitFrac[T] > eOlap) cntT++; else note += "" Et""; + if (hpr.pExonHitCov[Q] > eOlap || hpr.pExonHitFrac[Q] > eOlap) cntQ++; else note += "" Eq""; + + // Capture EI or II with these 2; test Gene Olap so accept long introns; + double gOlap = (!hpr.htype.equals(sEE)) ? (dPpLowGeneCov2[idx]*2.0) : dPpLowGeneCov2[idx]; + if (hpr.pGeneHitCov[T] > gOlap || hpr.pGeneHitOlap[T] > gOlap) cntT++; else note += "" Gt""; + if (hpr.pGeneHitCov[Q] > gOlap || hpr.pGeneHitOlap[Q] > gOlap) cntQ++; else note += "" Gq""; + + if (hpr.nHits > 1) { + if (hpr.pHitGapCov[T] > iGmLowHitGapCov2[idx]) cntT++; else note += "" Ht""; + if (hpr.pHitGapCov[Q] > iGmLowHitGapCov2[idx]) cntQ++; else note += "" Hq""; + } + if (cntT==0 || cntQ==0) return bRet(hpr, "" Ff0"" + note, false); + if (cntT==1 && cntQ==1) return bRet(hpr, "" Ff1"" + note, false); + + return bRet(hpr, "" Ps"" + note, true); + } + + /* G1 - this rejects many ones that could be in a block, but it tries to just pass the 'interesting' ones; + * otherwise, there are way too many due to the unconstrained non-gene side */ + protected static boolean bG1passCov(int X, HitPair hpr) { + if (hpr.flag==FILTER || hpr.nHits==0) return false; + int Y = (hpr.tGene!=null) ? Q : T; + + // 1. Reject clearly bad: (1) unequal hit coverage (2) low exon/gene coverage; E<25, G<1; can hit one tiny exon, so use frac + if (hpr.pHitGapCov[Y]*3 < hpr.pHitGapCov[X] || hpr.lenRatio<(dLenRatio/2.0)) return bRet(hpr, "" Fgp"", false); + + if (hpr.pExonHitFrac[X]< dPpLowExonCov2[1] && + hpr.pGeneHitCov[X]<1.0 && hpr.pGeneHitOlap[X]<1.0) return bRet(hpr, "" Fgn"", false); + + // 2. Accept perfect and near perfect + if (bGxisPerfect(1, X, hpr)) return true; // accept perfect + + if (hpr.xMaxCov>iPpMinLen[2] && bGxPcov(X, hpr)) return true; // accept 5000*scale and Good + + // 3. Reject intron only: (1) <3000, (2) GeneCov&Olap<50*scale (3) Cov X&Y < 60 (4) lenRatio<0.5 + if (!hpr.htype.contains(""E"")) { + if (hpr.xMaxCov iPpMinLen[1]*2) ? 0 : 1; // >2000 less stringent (20,25) else (25,35) + + if (hpr.pExonHitCov[X] > dPpLowExonCov2[idx] || hpr.pExonHitFrac[X] > dPpLowExonCov2[idx]) cnt++; else note += "" Fe""; + if (hpr.pGeneHitCov[X] > dPpLowGeneCov2[idx] || hpr.pGeneHitOlap[X] > dPpLowGeneCov2[idx]) cnt++; else note += "" Fg""; + + if (hpr.nHits>1) {// If mostly intron, want few gaps; however, the exon/gene can fail but have long hit to intron + int cov = (hpr.pExonHitCov[X] > dPpLowExonCov2[idx]) ? (int) dMinCov[0] : (int) dMinCov[1]; // 20,25; 60,80 + if (hpr.pHitGapCov[X] > cov && hpr.pHitGapCov[Y] > cov) cnt++; else note += "" Fih""; // gap>60|80 + if (hpr.xMaxCov>iPpMinLen[3] && hpr.lenRatio>dLenRatio) cnt++; else note += "" Fil""; // len>10000 + } + if (cnt<=1) return bRet(hpr, "" Ff"" + cnt + note, false); + + return bRet(hpr, "" Ps"" + cnt + note, true); + } + + private static boolean bGxisPerfect(int idx, int X, HitPair hpr) { + double p = dMinCov[idx+1]; // 80, 97 + if (hpr.pExonHitCov[X] < p) return false; + if (hpr.pGeneHitOlap[X]< p) return false; + if (hpr.pHitGapCov[X] < p) return false; + + if (TRACE) hpr.note += "" Perf"" + side[X]+ idx; + return true; + } + private static boolean bGxPcov(int X, HitPair hpr) { + double e = dMinCov[0] * pExonScale, g = dMinCov[0] * pGeneScale; + if (hpr.pExonHitCov[X] < e && hpr.pExonHitFrac[X] < e) return false; + if (hpr.pGeneHitCov[X] < g && hpr.pGeneHitOlap[X] < g) return false; + if (hpr.pHitGapCov[X] < iGmLowHitGapCov2[1]) return false; + + if (TRACE) hpr.note += "" Pmin"" + side[X]; + return true; + } + /* G0 *******************/ + protected static boolean bG0passCov(HitPair hpr) { + if (hpr.lenRatio=1000) ? (diff/1000) + ""k"" : diff+""""; + sdiff = (Math.abs(diff)>=1000000) ? (diff/1000000) + ""M"" : sdiff; + + if (isNeg) sdiff = ""-"" + sdiff; + else sdiff = "" "" + sdiff; + return sdiff; + } + protected static String side(int ix) { + if (ix<0) return ""N""; + if (ix<=2) return side[ix]; + else return ""?""; + } + protected static String htType(Gene tg, Gene qg) { + if (tg!=null && qg!=null) return strType[type2]; + if (tg==null && qg!=null) return strType[type1q]; + if (tg!=null && qg==null) return strType[type1t]; + return strType[type0]; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/GrpPairPile.java",".java","7321","246","package backend.anchor2; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.TreeMap; + +import backend.Utils; +import symap.Globals; +import util.ErrorReport; +import util.ProgressDialog; + +/************************************************************* + * Find overlapping HitPairs; mark Pile + */ +public class GrpPairPile { + static private final int T=Arg.T, Q=Arg.Q; + static private final double FperBin=backend.Constants.FperBin; // 0.8*matchLen top piles to save + + // from GrpPair + private GrpPair grpPairObj; + private ProgressDialog plog; + private ArrayList clustList = null; + private int clArrLen; + + // Working - discarded pile hits are Pile + private ArrayList pileList = new ArrayList (); + + private boolean bSuccess=true; + + protected GrpPairPile (GrpPair grpPairObj) { + this.grpPairObj = grpPairObj; + plog = grpPairObj.plog; + + clustList = grpPairObj.gxPairList; + + clArrLen = clustList.size(); + } + protected boolean run() { + Globals.tprt(""Find piles from "" + clArrLen); + + identifyPiles(); if (!bSuccess) return false; + createPiles(); if (!bSuccess) return false; + filterPiles(); if (!bSuccess) return false; + return bSuccess; + } + + //////////////////////////////////////////////////////////////////////////// + private void identifyPiles() { + try { + for (int X=0; X<2; X++) { // T piles, then Q piles (correct for saveDB) + HitPair.sortByXstart(X, clustList); // sorts by T/Q start; eq/ne mixed + + int cBin=1; + + for (int r1=0; r10) return false; // Gap + + olap = -olap; + int len0 = end0-start0+1; + int len1 = end1-start1+1; + + double x1 = (double) olap/(double)len0; + if (x1>Arg.bigOlap) return true; + + double x2 = (double) olap/(double)len1; + if (x2>Arg.bigOlap) return true; + + return false; + } + + ///////////////////////////////////////////////////////////////////////////////// + private void createPiles() { + try { + // create cluster pile sets; pile# is Key + TreeMap tPileMap = new TreeMap (); // key: pile[T] + TreeMap qPileMap = new TreeMap (); // key: pile[Q] + + Pile pHt; + for (HitPair hpr : clustList) { + if (hpr.pile[T]>0) { + if (!tPileMap.containsKey(hpr.pile[T])) { + pHt = new Pile(T, hpr.pile[T]); + tPileMap.put(hpr.pile[T], pHt); + } + else pHt = tPileMap.get(hpr.pile[T]); + pHt.addHit(hpr); + } + if (hpr.pile[Q]>0) { + if (!qPileMap.containsKey(hpr.pile[Q])) { + pHt = new Pile(Q, hpr.pile[Q]); + qPileMap.put(hpr.pile[Q], pHt); + } + else pHt = qPileMap.get(hpr.pile[Q]); + pHt.addHit(hpr); + } + } + + // finalize + for (Pile pile : tPileMap.values()) pileList.add(pile); + + for (Pile pile : qPileMap.values()) pileList.add(pile); + + Globals.tprt(tPileMap.size(), ""Piles for T""); + Globals.tprt(qPileMap.size(), ""Piles for Q""); + tPileMap.clear(); qPileMap.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Creating piles""); bSuccess=false;} + } + + /********************************************** + * Keep all Arg.isGoodPileHit and the 1st topN !Arg.isGoodPileHit && hpr.xMaxCov>thresh + * Heuristic using anchor1 Top N and 0.8 + */ + private void filterPiles() { + try { + int cntInPile=0, cntFil=0; + + sortPiles(pileList); // by maxCov + + for (Pile pile : pileList) { + cntInPile += pile.hprList.size(); + + sortForPileTopN(pile.hprList); // sort by xMaxCov + + int thresh = pile.hprList.get(0).xMaxCov; + thresh *= FperBin; // 0.8 so keep 80% of mTopN matchLen + + int tn=0; + for (HitPair hpr : pile.hprList) { + if (hpr.flag==Arg.PILE || Arg.isGoodPileHit(hpr)) continue; + + if (hpr.xMaxCov=Arg.topN) { + hpr.flag = Arg.PILE; + cntFil++; + } + tn++; // accept TopN that are !Arg.isGoodPileHit(hpr) + } + } + grpPairObj.mainObj.cntPileFil += cntFil; + if (Arg.TRACE) { + Utils.prtIndentMsgFile(plog, 1, String.format(""%,10d Piles Hits in piles %,d Filtered pile hits %d"", + pileList.size(), cntInPile, cntFil)); + } + } + catch (Exception e) {ErrorReport.print(e, ""Prune clusters""); bSuccess=false;} + } + //////////////////////////////////////////////////////////////// + protected void prtToFile(PrintWriter fhOutRep, String chrs) { + try { + fhOutRep.println(""Repetitive clusters for "" + chrs); + + for (Pile ph : pileList) { + fhOutRep.println(""\n"" + ph.toResults()); + + for (HitPair cht : ph.hprList) + fhOutRep.println("" "" + cht.toPileResults()); + } + } + catch (Exception e) {ErrorReport.print(e, ""Write reps to file""); bSuccess=false;} + } + protected static void sortForPileTopN(ArrayList gpList) { // GrpPairPile heuristic topN + Collections.sort(gpList, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + if (h1.xMaxCov>h2.xMaxCov) return -1; + if (h1.xMaxCovh2.nHits) return -1; + if (h1.nHits gpList) { // GrpPairPile heuristic topN + Collections.sort(gpList, + new Comparator() { + public int compare(Pile h1, Pile h2) { + if (h1.xMaxCov>h2.xMaxCov) return -1; + if (h1.xMaxCovh2.hprList.size()) return -1; + if (h1.hprList.size() hprList = new ArrayList (); + + private Pile(int X, int pnum) {this.X = X; this.pnum=pnum;} + + private void addHit(HitPair ht) { + hprList.add(ht); + tmin = Math.min(ht.hpStart[T], tmin); + qmin = Math.min(ht.hpStart[Q], qmin); + tmax = Math.max(ht.hpEnd[T], tmax); + qmax = Math.max(ht.hpEnd[Q], qmax); + xMaxCov = Math.max(ht.xMaxCov, xMaxCov); + } + + private String toResults() { + String msg = String.format(""%s%-5d #%3d T[%,10d %,10d %,6d] Q[%,10d %,10d %,d] >>>>>>>>>>>>>>>>>>>>>>>>"", + Arg.side[X], pnum, hprList.size(), tmin, tmax, (tmax-tmin), qmin, qmax, (qmax-qmin)); + return msg; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/Hit.java",".java","8598","242","package backend.anchor2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; + +/******************************************************************* + * Hit created when MUMmer read; overlap with genes are calculated at the same time + * A hit is either GG, Gn, nG, or nn; a hit can be to multiple T and/or Q overlapping genes + * A second Hit constructor is for merging hits in HitPair + */ +public class Hit { + private static final int T=Arg.T, Q=Arg.Q; + + protected int bin=0; // set in G2,G1,G0; + protected int bin2=0; // G2 when multiple genes overlap, can have a HPR where no ht.bin=hpr.bin, which messes up setMinor + // G1,G0 temporary use + // Mummer + protected int hitNum; // order found in Mummer; used in the final check of sort + protected int id=0, sim=0, maxLen; + protected int [] hStart, hEnd, hLen; // frames not used; does not seem to coincide with hits along a gene + protected String sign; // +/+, +/-, etc + protected boolean isStEQ=true; // same strand (T) diff strand (F) + + // set during read mummer + protected HashMap tGeneMap = null, qGeneMap=null; + + // set in GrpPairGx.mkGenePair + protected HashSet gxPair = new HashSet (); + protected int cntGene=0; + + /************************************************* + * AnchorMain2.runReadMummer; this is the main hit used everywhere + */ + protected Hit(int hitCnt, int id, int sim, int [] start, int [] end, int [] len, + int [] grpIdx, String sign, int [] frame) { + this.hitNum=hitCnt; + this.id = id; + this.sim=sim; + this.hStart = start; + this.hEnd = end; + this.hLen = len; + this.maxLen = Math.max(len[T],len[Q]); + this.sign = sign; + isStEQ = Arg.isEqual(sign); + } + protected void addGene(int X, Gene gn, int exonCov) { + if (X==T && tGeneMap==null) tGeneMap = new HashMap (); + if (X==Q && qGeneMap==null) qGeneMap = new HashMap (); + + HashMap geneMap = (X==T) ? tGeneMap : qGeneMap; + + HitGene hg = new HitGene(gn, exonCov); + geneMap.put(gn.geneIdx, hg); + } + protected void mkGenePairs() throws Exception { // GrpPairGx.g2PairHits; + if (tGeneMap==null || qGeneMap==null) return; + if (gxPair.size()>0) return; // already made for EQ, now use for NE + + for (Integer tgn : tGeneMap.keySet()) { + for (Integer qgn : qGeneMap.keySet()) { + gxPair.add(tgn + "":"" + qgn); + } + } + } + protected void setBin(int hbin) { + if (bin>0) bin2= hbin; + else bin = hbin; + } + protected void addGeneHit(Gene tgene, Gene qgene) { + cntGene++; + + HitGene thg = tGeneMap.get(tgene.geneIdx); + thg.cnt++; + HitGene qhg = qGeneMap.get(qgene.geneIdx); + qhg.cnt++; + } + protected int getExonCov(int X, Gene gn) { // rmEndHits + HashMap geneMap = (X==T) ? tGeneMap : qGeneMap; + if (geneMap==null) return 0; + + if (geneMap.containsKey(gn.geneIdx)) return geneMap.get(gn.geneIdx).exonCov; + + return 0; + } + // for G1, ygene is null, + protected void rmGeneFromHit(int X, Gene xgene, Gene ygene) { // do not remove from geneMap because may be used by another + cntGene--; + + HashMap geneMap = (X==T) ? tGeneMap : qGeneMap; + if (geneMap!=null) { + if (geneMap.containsKey(xgene.geneIdx)) { + HitGene hg = geneMap.get(xgene.geneIdx); + hg.cnt--; + } + else symap.Globals.tprt(""No gene "" + xgene.geneTag + "" for hit #"" + hitNum); + } + if (ygene!=null) { + geneMap = (X!=T) ? tGeneMap : qGeneMap; + if (geneMap.containsKey(ygene.geneIdx)) { + HitGene hg = geneMap.get(ygene.geneIdx); + hg.cnt--; + } + else symap.Globals.tprt(""No gene "" + xgene.geneTag + "" for hit #"" + hitNum); + } + } + + protected boolean bHitsAnotherExon(int X, Gene xgene) { // rmEndHits + if (cntGene==1) return false; // even if only hits intron, its not overlapping another + HashMap geneMap = (X==T) ? tGeneMap : qGeneMap; + + if (!geneMap.containsKey(xgene.geneIdx)) { + symap.Globals.tprt(""****No "" + xgene.geneTag); + return false; + } + + HitGene xhg = geneMap.get(xgene.geneIdx); + if (xhg.exonCov==0) return true; // this one falls in intron, let other gene use it + + int bestCov=0; + for (HitGene hg : geneMap.values()) { + if (hg!=xhg && hg.exonCov>0 && hg.cnt>0) bestCov = Math.max(bestCov, hg.exonCov); + } + if (bestCov==0) return false; + return (xhg.exonCov < bestCov); // this hits) { // Gene.gHitList for toResults + Collections.sort(hits, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (h1.isStEQ && !h2.isStEQ) return -1; + if (!h1.isStEQ && h2.isStEQ) return 1; + + if (h1.hStart[X] < h2.hStart[X]) return -1; + if (h1.hStart[X] > h2.hStart[X]) return 1; + if (h1.hEnd[X] > h2.hEnd[X]) return -1; + if (h1.hEnd[X] < h2.hEnd[X]) return 1; + return 0; + } + } + ); + } + // HitPair.hitList: HitPair.setScores, setSubs; GrpPairGx rmEndsHitsG1/G2, runG0 + protected static void sortXbyStart(int X, ArrayList hits) throws Exception { + Collections.sort(hits, + new Comparator() { + public int compare(Hit h1, Hit h2) { + if (h1.hStart[X] < h2.hStart[X]) return -1; + if (h1.hStart[X] > h2.hStart[X]) return 1; + if (h1.hEnd[X] > h2.hEnd[X]) return -1; + if (h1.hEnd[X] < h2.hEnd[X]) return 1; + + int Y = (X==Arg.Q) ? Arg.T : Arg.Q; + if (h1.hStart[Y] < h2.hStart[Y]) return -1; + if (h1.hStart[Y] > h2.hStart[Y]) return 1; + if (h1.hEnd[Y] > h2.hEnd[Y]) return -1; + if (h1.hEnd[Y] < h2.hEnd[Y]) return 1; + + return 0; + } + } + ); + } + + /******** prtToFile on -tt ******************/ + protected String toDiff(Hit last) { + int maxGap = Arg.iGmIntronLenRm; + String sdiff1="""", sdiff2="""", td="""", qd=""""; + if (last!=null) { + int olap = Arg.pGap_nOlap(last.hStart[T], last.hEnd[T], hStart[T], hEnd[T]); // Negative is gap; make Olap neg + sdiff1 = Arg.int2Str(olap); // returns string prefixed with - or blank + if (Math.abs(olap)>maxGap) td = "" T"" + olap; + olap = Arg.pGap_nOlap(last.hStart[Q], last.hEnd[Q], hStart[Q], hEnd[Q]); + sdiff2 = Arg.int2Str(olap); + if (Math.abs(olap)>maxGap) qd = "" Q"" + olap; + } + String pre = ""n""; + if (bBothGene()) pre=""g""; + else if (bEitherGene()) pre=""e""; + String sbin = String.format("" %7s "", (pre + bin)); + if (bin2>0) sbin += ""gg"" + bin2 + "" ""; + String e = isStEQ ? "" EQ"" : "" NE""; + e += sign; + String ext = sbin + toGeneStr() + e + "" ""; + String coords = String.format(""#%-6d [Q %,10d %,10d %,5d %5s] [T %,10d %,10d %,5d %5s] [ID %3d]"", + hitNum, hStart[Q], hEnd[Q], hLen[Q], sdiff1, hStart[T], hEnd[T], hLen[T], sdiff2, id); + return coords + ext + qd + td; + } + protected String toGeneStr() { + String tmsg="""", qmsg=""""; + if (tGeneMap!=null && tGeneMap.size()>0) { + for (HitGene hg : tGeneMap.values()) { + if (hg.exonCov>0) tmsg += "" Et""; + else tmsg += "" It""; + tmsg += hg.xgene.geneTag + hg.xgene.strand + hg.cnt; + } + } + if (tmsg=="""") tmsg=""t--""; + if (qGeneMap!=null && qGeneMap.size()>0) { + for (HitGene hg : qGeneMap.values()) { + if (hg.exonCov>0) qmsg += "" Eq""; + else qmsg += "" Iq""; + qmsg += hg.xgene.geneTag + hg.xgene.strand + hg.cnt; + } + } + if (qmsg=="""") qmsg=""q--""; + return ""["" + qmsg + ""]["" + tmsg + ""]"" + cntGene + "" ""; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/HitPair.java",".java","16261","419","package backend.anchor2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; + +import util.ErrorReport; + +/************************************************************* + * Cluster hit; Set of joined hits for g2, g1, or g0 + */ +public class HitPair { + private static final int T=Arg.T, Q=Arg.Q, TQ=Arg.TQ; + private static int CNT_HPR=1; + + protected int nHpr = 1; // for sorting identical hitpairs of overlapping genes + protected int gtype = Arg.typeUnk; // ""Unk"",""G0"", ""G1t"", ""G1q"", ""G2"" + protected char flag = Arg.UNK; // Major, Minor, Filter, Dup, Ign, Pile + protected int bin = 0; // GrpPairGx set for hpr, then reset in GrpPair + + protected int [] hpStart = {Integer.MAX_VALUE, Integer.MAX_VALUE}; + protected int [] hpEnd = {0,0}; + + protected ArrayList hitList = new ArrayList (); // subhits + protected int nHits = 0; + protected boolean isStEQ = true; // same strand (T) diff strand (F) + protected boolean isRst = true; // g2 genes correspond to hit strand, g2 are on +/- but hit is +/+ + protected boolean isOrder = true; + + protected Gene tGene=null, qGene=null; + protected double [] pExonHitFrac = {0.0, 0.0, 0.0}; // % fraction of each exon hit + protected double [] pExonHitCov = {0.0, 0.0, 0.0}; // % exons covered by hits; T,Q,TQ + protected double [] pGeneHitCov = {0.0, 0.0, 0.0}; // % gene covered by hits; T,Q,TQ + protected double [] pGeneHitOlap = {0.0, 0.0, 0.0}; // % hitLen/gLen; T,Q,TQ -- G0 for non-gene, sum of hits + protected double [] pHitGapCov = {0.0, 0.0, 0.0}; // % hitCov/hitLen;T,Q,TQ + + protected int [] geneIdx = {0, 0}; // geneIdx + protected double lenRatio=0; // g2 geneLen/geneLen; g1,g0 hprLen/hprLen + protected int xSumId=0, xSumSim=0, xMaxCov=0; // Saved in DB; xMaxCov is used for filters + + // Cluster + protected int cHitNum=0; // after all processing including pile; assigned in GrpPair.createCluster + protected boolean bEE=false, bEI=false, bII=false, bEn=false, bIn=false, bnI=false, bnn=false; // for GrpPairPile filter on piles + protected boolean bBothGene=false, bOneGene=false, bNoGene=false; + protected String sign=""""; // */-, etc set in setScores + protected String targetSubHits="""", querySubHits=""""; // concatenated hits for DB + protected String htype=Arg.snn; // EE, EI, etc + + // GrpPairPile + protected int [] pile = {0,0}; // closely overlapping clusters; see GrpPairPile + + // Used for trace + protected String note=""""; + + protected HitPair(int type, Gene tGene, Gene qGene, boolean isEQ) { + this.gtype = type; // see Arg.type; G2, G1t, G1q, G0 + this.tGene = tGene; + this.qGene = qGene; + this.geneIdx[T] = (tGene!=null) ? tGene.geneIdx : 0; + this.geneIdx[Q] = (qGene!=null) ? qGene.geneIdx : 0; + this.isStEQ = isEQ; + + bBothGene = (tGene!=null && qGene!=null); + bOneGene = (tGene!=null && qGene==null) || (tGene==null && qGene!=null); + bNoGene = (tGene==null && qGene==null); + nHpr=CNT_HPR++; + } + protected HitPair(HitPair cpHpr) { + this.gtype = cpHpr.gtype; + this.tGene = cpHpr.tGene; + + this.qGene = cpHpr.qGene; + this.geneIdx[T] = cpHpr.geneIdx[T]; + this.geneIdx[Q] = cpHpr.geneIdx[Q]; + this.isStEQ = cpHpr.isStEQ; + + this.bBothGene = cpHpr.bBothGene; + this.bOneGene = cpHpr.bOneGene; + this.bNoGene = cpHpr.bNoGene; + this.nHpr = cpHpr.nHpr; + } + protected void addHit(Hit ht) { + hitList.add(ht); + for (int x=0; x<2; x++) { + if (hpStart[x] > ht.hStart[x]) hpStart[x] = ht.hStart[x]; + if (hpEnd[x] < ht.hEnd[x]) hpEnd[x] = ht.hEnd[x]; + } + } + protected void rmHit(int X, Gene xgene, Gene ygene, int i) { + try { + Hit htrm = hitList.get(i); + + if (xgene!=null || ygene!=null) htrm.rmGeneFromHit(X, xgene, ygene); + hitList.remove(i); + + nHits = hitList.size(); + if (nHits==0) { + flag = Arg.FILTER; + return; + } + + for (int x=0; x<2; x++) { + hpStart[x]=Integer.MAX_VALUE; + hpEnd[x]=0; + for (Hit ht : hitList) { + if (hpStart[x] > ht.hStart[x]) hpStart[x] = ht.hStart[x]; + if (hpEnd[x] < ht.hEnd[x]) hpEnd[x] = ht.hEnd[x]; + } + } + setScoresMini(); + } + catch (Exception e) {ErrorReport.print(e, ""rmHit"");} + } + + protected void crossRef() { + if (tGene!=null) tGene.gHprList.add(this); + if (qGene!=null) qGene.gHprList.add(this); + } + protected void crossRefClear() { + if (tGene!=null) tGene.gHprList.clear(); + if (qGene!=null) qGene.gHprList.clear(); + } + + /******************************************************* + * Scores: hit, exon, gene, id & len + * Everything here is needed for filtering, sorting...; finishSubs has the rest + */ + protected void setScores() throws Exception { + try { + nHits = hitList.size(); + boolean isG0 = (tGene==null && qGene==null); + int [] totHprLen = {0,0}; + int [] sumMergeHits = {0,0}; + ArrayList mergedHits ; + + // TQ p scores + for (int X=0; X<2; X++) { + Hit.sortXbyStart(X, hitList); // SORT + + if (X==T) { // only need to check for one side after sort + for (int i=0; i hitList.get(j).hStart[Q]); + } + } + + mergedHits = calcMergeHits(X); + + totHprLen[X] = hpEnd[X]-hpStart[X]+1; + for (Hit ht : mergedHits) + sumMergeHits[X] += (ht.hEnd[X]-ht.hStart[X]+1); + pHitGapCov[X] = ((double)sumMergeHits[X]/(double)totHprLen[X]) * 100.0; // %coverage + + Gene xGene = (X==T) ? tGene : qGene; + if (xGene!=null) { + int hs = mergedHits.get(0).hStart[X]; + int he = mergedHits.get(mergedHits.size()-1).hEnd[X]; + pGeneHitOlap[X] = ((double) Arg.pOlapOnly(hs, he, xGene.gStart, xGene.gEnd)/ (double)xGene.gLen)*100.0; + + double [] scores = xGene.scoreExonsGene(mergedHits); + pExonHitFrac[X] = scores[0]; // % fraction cover of each exon + pExonHitCov[X] = scores[1]; // % total summed exons covered in hits - no regard for individual exons + pGeneHitCov[X] = scores[2]; // % hit/gene; was percent hit coverage of genes, but bad for long introns + } + else if (isG0) pGeneHitOlap[X] = sumMergeHits[X]; + } // end X loop + + // Sum values for each hit + double [] sumHitSim = {0,0}; + double [] sumHitId = {0,0}; + int [] sumHitLen = {0,0}; + + for (int X=0; X<2; X++) { + double sumId=0, sumSim=0; + for (Hit ht : hitList) { + sumSim += ht.sim * ht.hLen[X]; + sumId += ht.id * ht.hLen[X]; + sumHitLen[X] += ht.hLen[X]; + } + sumHitId[X] = (double)sumId /(double)sumHitLen[X]; + sumHitSim[X] = (double)sumSim/(double)sumHitLen[X]; + } + // Saved in DB - only xMaxCov is used in Piles for threshold + int ix = (sumMergeHits[T] > sumMergeHits[Q]) ? T : Q; + xMaxCov = sumMergeHits[ix]; + xSumId = (int) Math.round(sumHitId[ix]); + xSumSim = (int) Math.round(sumHitSim[ix]); + + setSign(); // make sign agree with gene strands; + + if (tGene!=null && qGene!=null) { // nHitOlap can be the same for overlapping genes; so use length + if (tGene.gLen < qGene.gLen) lenRatio = (double)tGene.gLen/(double)qGene.gLen; + else lenRatio = (double)qGene.gLen/(double)tGene.gLen; + } + else { + if (totHprLen[0] < totHprLen[1]) lenRatio = (double)totHprLen[0]/(double)totHprLen[1]; + else lenRatio = (double)totHprLen[1]/(double)totHprLen[0]; + } + + // TQ + pExonHitFrac[TQ]= pExonHitFrac[T]+ pExonHitFrac[Q]; + pExonHitCov[TQ] = pExonHitCov[T] + pExonHitCov[Q]; + pGeneHitCov[TQ] = pGeneHitCov[T] + pGeneHitCov[Q]; + pGeneHitOlap[TQ]= pGeneHitOlap[T]+ pGeneHitOlap[Q]; + pHitGapCov[TQ] = pHitGapCov[T] + pHitGapCov[Q]; + + if (tGene==null && qGene==null) { + htype=""nn""; + bnn=true; + return; + } + double p = Arg.minEE; + if (pExonHitCov[T]>p && pExonHitCov[Q]>p) {htype=Arg.sEE; bEE=true;} + else if (pExonHitCov[T]>p && geneIdx[Q]>0) {htype=Arg.sIE; bEI=true;} + else if (pExonHitCov[Q]>p && geneIdx[T]>0) {htype=Arg.sEI; bEI=true;} + else if (pExonHitCov[T]>p && geneIdx[Q]==0) {htype=Arg.snE; bEn=true;} + else if (pExonHitCov[Q]>p && geneIdx[T]==0) {htype=Arg.sEn; bEn=true;} + else if (geneIdx[T]>0 && geneIdx[Q]>0) {htype=Arg.sII; bII=true;} + else if (geneIdx[T]>0) {htype=Arg.snI; bIn=true;} + else if (geneIdx[Q]>0) {htype=Arg.sIn; bnI=true;} + } + catch (Exception e) {ErrorReport.print(e, ""Setting scores""); throw e;} + } + /** is Hit signs same as gene signs; set isRst=false if not **/ + protected void setSign() { + try { + sign = hitList.get(0).sign; + boolean isHitEQ = Arg.isEqual(sign); + if (gtype==Arg.type0 || gtype==Arg.type2) { // get best order (g2 used for printout) + int same=0, diff=0; + for (Hit ht :hitList) { + if (ht.sign.equals(sign)) same++; + else diff++; + } + if (diff>same) sign = sign.charAt(2) + ""/"" + sign.charAt(0); + } + // sign - checked in GrpPairGx for consistency + if (tGene!=null && qGene!=null) { + boolean isGnEQ = tGene.strand.equals(qGene.strand); + isRst = (isGnEQ==isHitEQ); + sign = (isRst) ? qGene.strand + ""/"" + tGene.strand : sign; + } + else if (qGene!=null) { + if (isHitEQ) sign = qGene.strand + ""/"" + qGene.strand; + else if (qGene.strand.equals(""+"")) sign = ""+/-""; + else sign = ""-/+""; + } + else if (tGene!=null) { + if (isHitEQ) sign = tGene.strand + ""/"" + tGene.strand; + else if (tGene.strand.equals(""+"")) sign = ""-/+""; + else sign = ""+/-""; + } + } + catch (Exception e) {ErrorReport.print(e, ""Setting sign""); throw e;} + } + // For G1 because do not need all scores yet + protected void setScoresMini() { + nHits = hitList.size(); + int [] totHPRlen = {0,0}; + totHPRlen[Q] = hpEnd[Q]-hpStart[Q]+1; + totHPRlen[T] = hpEnd[T]-hpStart[T]+1; + if (totHPRlen[0] < totHPRlen[1]) lenRatio = (double)totHPRlen[0]/(double)totHPRlen[1]; + else lenRatio = (double)totHPRlen[1]/(double)totHPRlen[0]; + } + /* For setScores: The hits overlap, so merge the overlapping ones. + * There is a similar method in mapper.HitData and closeup.SeqHitsbut with different data structures */ + protected ArrayList calcMergeHits(int X) { + try { + if (nHits==1) return hitList; + + ArrayList subSet = new ArrayList (); + + for (Hit ht : hitList) { // sorted on X + boolean found=false; + + for (Hit sh : subSet) { + int olap = Arg.pGap_nOlap(sh.hStart[X], sh.hEnd[X], ht.hStart[X], ht.hEnd[X]); + if (olap>0) continue; // gap + + found=true; + if (ht.hEnd[X] > sh.hEnd[X]) sh.hEnd[X] = ht.hEnd[X]; + if (ht.hStart[X] < sh.hStart[X]) sh.hStart[X] = ht.hStart[X]; + + break; + } + if (!found) { + Hit sh = new Hit(X, ht.hStart[X], ht.hEnd[X]); + subSet.add(sh); + } + } + return subSet; + } + catch (Exception e) {ErrorReport.print(e, ""merge hits""); return null;} + } + /////////////////////////////////////////////////////////////// + // All processing done at this point except Piles and final filter; values to save to DB + protected void setSubs() throws Exception { + try { + targetSubHits=querySubHits=""""; + + Hit.sortXbyStart(Q, hitList); // This is the order anchor1 does it - must be the same + for (Hit ht : hitList) { + targetSubHits += ht.hStart[T] + "":"" + ht.hEnd[T] + "",""; + querySubHits += ht.hStart[Q] + "":"" + ht.hEnd[Q] + "",""; + } + targetSubHits.substring(0, targetSubHits.length()-1); + querySubHits.substring(0, querySubHits.length()-1); + } + catch (Exception e) {ErrorReport.print(e, ""finish subs""); } + } + protected int getGeneOverlap() { + if (geneIdx[T]>0 && geneIdx[Q]>0) return 2; + if (geneIdx[T]>0 || geneIdx[Q]>0) return 1; + return 0; + } + protected double getGeneCov(int X) { + if (X==Arg.T && tGene!=null) { + int cov = Arg.pOlapOnly(hpStart[T], hpEnd[T], tGene.gStart, tGene.gEnd); + return (double) cov/(double)tGene.gLen; + } + if (X==Arg.Q && qGene!=null) { + int cov = Arg.pOlapOnly(hpStart[Q], hpEnd[Q], tGene.gStart, tGene.gEnd); + return (double) cov/(double)qGene.gLen; + } + return 0.0; + } + /***************************************************************************/ + protected static void sortByXstart(int X, ArrayList hpr) { // GrpPair.saveClusterHits, GrpPairPile.identifyPiles + Collections.sort(hpr, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + if (h1.hpStart[X] < h2.hpStart[X]) return -1; + if (h1.hpStart[X] > h2.hpStart[X]) return 1; + if (h1.hpEnd[X] > h2.hpEnd[X]) return -1; + if (h1.hpEnd[X] < h2.hpEnd[X]) return 1; + return 0; + } + } + ); + } + protected void clear() { + hitList.clear(); + } + // symap -wsp outputs this; documented in SystemHelp under Clusters; see GrpPairGx.runG2.processWS + protected String toWSResults() { + String eq = isStEQ ? "" ="" : ""!=""; + eq = qGene.strand + ""/"" + tGene.strand + "" "" + eq; + + String locq = String.format(""[%5.1f %5.1f %,7dbp]"", pExonHitCov[Q], pGeneHitCov[Q], (hpEnd[Q]-hpStart[Q]+1)); + String loct = String.format(""[%5.1f %5.1f %,7dbp]"", pExonHitCov[T], pGeneHitCov[T], (hpEnd[T]-hpStart[T]+1)); + + return String.format(""%-5d %-8s %-10s %-10s %s %s "", nHits, eq, qGene.geneTag, tGene.geneTag, locq, loct); + } + /********* prtToFile *************************************************/ + protected String toResultsGene() { + String n1 = (qGene!=null) ? qGene.geneTag : ""None""; n1 = String.format(""Q#%-6s"", n1); + String n2 = (tGene!=null) ? tGene.geneTag : ""None""; n2 = String.format(""T#%-6s"", n2); + + String cb = (cHitNum==0) ? String.format(""[b%-5d]"", bin) : String.format(""[CL%-5d b%-5d]"", cHitNum, bin); + + String mb = String.format(""%s %s %s %s"", flag, cb, n1, n2); + String me = String.format(""[E %5.1f %5.1f | %5.1f %5.1f]"", pExonHitCov[Q], pExonHitCov[T], pExonHitFrac[Q], pExonHitFrac[T]); + String mg = String.format(""[G %5.1f %5.1f | %5.1f %5.1f]"", pGeneHitCov[Q], pGeneHitCov[T], pGeneHitOlap[Q], pGeneHitOlap[T]); + String mh = String.format(""[H %5.1f %5.1f]"", pHitGapCov[Q], pHitGapCov[T]); + String m4 = String.format(""[M %,6d %,6d %,6d %.2f]"", xMaxCov, Arg.hprLen(Q,this), Arg.hprLen(T,this), lenRatio); + + String eq = (isStEQ) ? ""EQ"" : ""NE""; + String ws = (!isRst && tGene!=null && qGene!=null) ? ""WS"" +sign : "" "" + sign; // hit sign does not agree with gene + String m5 = String.format(""%s #%3d %s"", eq, nHits, ws); + + return String.format(""%s %s %s %s %s %s"", mb, me, mg, mh, m4, m5); + } + protected String toResults(String chrs, boolean bHits) { + String pil = (pile[T]>0 || pile[Q]>0) ? String.format(""[P%3d P%3d]"", pile[Q], pile[T]) : """"; + String id = String.format(""[id %2d]"", xSumId); + String o = (!isOrder) ? ""DO"" : "" ""; + + String msg; + if (tGene==null && qGene==null) { + String cb = (cHitNum==0) ? String.format(""[b%-5d]"", bin) : String.format(""[CL%-5d b%-5d]"", cHitNum, bin); + String ms = String.format(""[S %,6d %,6d]"", (int) hpStart[Q], (int)hpStart[T]); + String mo = String.format(""[C %,6d %,6d]"", (int) pGeneHitOlap[Q], (int)pGeneHitOlap[T]); + String mh = String.format(""[H %5.1f %5.1f]"", pHitGapCov[Q], pHitGapCov[T]); + String ml = String.format(""[%.2f]"", lenRatio); + String m3 = String.format(""%s #%d %s %-12s %s %s"", pil, nHits, o, note, id, chrs); + msg = String.format("">%-3s:%c %s TQ%d %s %s %s %s %s"", Arg.strType[gtype], flag, cb, nHpr, ms, mo, mh, ml, m3); + } + else { + String m1 = String.format("">%s:"", htype); + String m3 = String.format(""%s %s %-12s %s %s"", pil, o, note, id, chrs); + msg = String.format(""%s%s %s"", m1, toResultsGene(), m3); + } + if (bHits) { + Hit last=null; + for (Hit ht: hitList) { + String m=""""; + if (last!=null) { + if (ht.bin!=last.bin && last.bin!=0 && ht.bin!=0) m="" DIFF""; + if (ht.isStEQ!=last.isStEQ) m+=""Q""; + } + msg += ""\n"" + ht.toDiff(last) + m; + last = ht; + } + } + return msg; + } + protected String toPileResults() { + String loc = String.format(""[Q %,10d %,10d][T %,10d %,10d]"", hpStart[Q],hpEnd[Q], hpStart[T], hpEnd[T]); + String s = (note.contains(""Split"")) ? ""BinSpl "" : """"; // created from bin split + String n1 = (tGene!=null) ? tGene.geneTag : ""None""; + String n2 = (qGene!=null) ? qGene.geneTag : ""None""; + + return String.format( + "">%-3s:%c %s %,7d Q#%-6s T#%-6s [P %5d %5d] %s #%d %s %s"", + Arg.strType[gtype], flag, htype, xMaxCov, n1, n2, pile[Q],pile[T], loc, nHits, sign, s); + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/GrpPair.java",".java","18705","541","package backend.anchor2; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.TreeMap; + +import backend.Utils; +import database.DBconn2; +import symap.Globals; +import util.ErrorReport; +import util.ProgressDialog; + +/************************************************************** + * Performs all processing for a chrT-chrQ; save results to DB; frees memory + * The genes and hits are specific to the pair; + * the genes are copies since each gene can align to more than one chr + * the hits are unique to the GrpPair + */ +public class GrpPair { + static public final int T=Arg.T, Q=Arg.Q; + + // Input Args + private int tGrpIdx=-1, qGrpIdx=-1; + protected AnchorMain2 mainObj; + protected ProgressDialog plog; // also used directly by GrpPairGx and GrpPairPile + protected String tChr="""", qChr=""""; + protected String traceHeader = """"; + + // Only genes from this tChr-qChr that have hits; built when the MUMmer file is read; used by GrpPairGx + protected TreeMap tGeneMap = new TreeMap (); // key: geneIdx + protected TreeMap qGeneMap = new TreeMap (); // key: geneIdx + + // Only hits between tChr-qChr; built from MUMmer file, used by GrpPairGx + protected ArrayList grpHitList= new ArrayList (); + + // GrpPairGx creates gxPairList, turned into clusters, used for saveAnnoHits for Major and Minor + private GrpPairGx gpGxObj; + protected ArrayList gxPairList; + + // GrpPairPile removes piles + private GrpPairPile gpPileObj; + + private boolean bSuccess=true; + + protected GrpPair(AnchorMain2 anchorObj, int grpIdxT, String projT, String chrT, + int grpIdxQ, String projQ, String chrQ, ProgressDialog plog) { + this.mainObj = anchorObj; + + this.tChr = chrT; + this.tGrpIdx = grpIdxT; + + this.qChr = chrQ; + this.qGrpIdx = grpIdxQ; + + this.plog = plog; + + traceHeader = projQ + ""-"" + chrQ + "" "" + projT + ""-"" + chrT + "" "" + mainObj.fileName; + } + + /***************************************** + * The following two are populated during read mummer; Only hits and genes belonging to the chr pair are added + */ + protected void addHit(Hit ht) { + grpHitList.add(ht); + } + protected void addGeneHit(int X, Gene gn, Hit ht) { + try { + TreeMap geneMap = (X==T) ? tGeneMap : qGeneMap; + + Gene cpGn; + if (geneMap.containsKey(gn.geneIdx)) cpGn = geneMap.get(gn.geneIdx); + else { + cpGn = (Gene) gn.copy(); // needs to be copy because gene can hit multiple chrs (diff hitList) + geneMap.put(cpGn.geneIdx, cpGn); + } + int exonCov = cpGn.addHit(ht); + + ht.addGene(X, cpGn, exonCov); + } + catch (Exception e) {ErrorReport.print(e, ""GrpPair: clone gene, add hit""); System.exit(-1);} + } + + /************************************************************** + * All processing is performed and saved for this group pair + * Each grp-grp pair starts the nBin where the last grp-grp pair left off + */ + protected boolean buildClusters() { + if (Arg.TRACE) Utils.prtIndentMsgFile(plog, 1, ""Compute clusters for Q-"" + qChr + "" and T-"" + tChr); + + gpGxObj = new GrpPairGx(this); // filtered g2,g1,g0 hitpairs; create gxPairList + bSuccess = gpGxObj.run(); if (fChk()) return false; + gxPairList = gpGxObj.getPairList(); + + gpPileObj = new GrpPairPile(this); // remove piles + bSuccess = gpPileObj.run(); if (fChk()) return false; + + HitPair.sortByXstart(Q, gxPairList); // SORT + createClustersFromHPR(); if (fChk()) return false; + + saveClusterHits(); if (fChk()) return false; + + saveAnnoHits(); if (fChk()) return false; + + prtTrace(); + + return true; + } + + /************************************************************** + * Clusters assignments and gxPairList are 1-to-1 for Major + * grpClHitList only contains Major non-filtered + * gxPairList contains info to save Minor + */ + private void createClustersFromHPR() { + try { + Globals.tprt("">> Create clusters for "" + traceHeader); + + HashMap bin2clMap = new HashMap (gxPairList.size()); + + int clBin=1; + for (HitPair hpr : gxPairList) { + if (hpr.bin!=0 && hpr.flag==Arg.MAJOR) { + hpr.cHitNum = hpr.cHitNum = clBin++; + bin2clMap.put(hpr.bin, hpr); + } + } + + // transfer clNum to minor; needed for saveAnnoHits + for (HitPair hp : gxPairList) { + if (hp.bin!=0 && hp.flag==Arg.MINOR) { + if (bin2clMap.containsKey(hp.bin)) { // if not exist, major was filtered + HitPair clHit = bin2clMap.get(hp.bin); + hp.cHitNum = clHit.cHitNum; + } + } + } + } + catch (Exception e) {ErrorReport.print(e, ""GrpPair createClusters""); bSuccess=false;} + } + + /////////////////////////////////////////////////////////////////////// + private void saveClusterHits() { + try { + DBconn2 tdbc2 = mainObj.tdbc2; + int pairIdx = mainObj.mPair.getPairIdx(); + int proj1Idx = mainObj.mProj1.getIdx(); + int proj2Idx = mainObj.mProj2.getIdx(); + + int cntG2=0, cntG1=0, cntG0=0, countBatch=0, cntSave=0, cntFil=0; + int cntDOeq=0, cntDOne=0; + + tdbc2.executeUpdate(""alter table pseudo_hits modify countpct integer""); + + String sql = ""insert into pseudo_hits (hitnum, pair_idx,"" + + ""proj1_idx, proj2_idx, grp1_idx, grp2_idx,"" + + ""pctid, cvgpct, countpct, score, htype, gene_overlap, strand,"" + + ""annot1_idx, annot2_idx, start1, end1, start2, end2, query_seq, target_seq)""; + + PreparedStatement ps = tdbc2.prepareStatement(sql + + ""VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ""); + + for (HitPair hpr : gxPairList) { + if (hpr.flag!=Arg.MAJOR) {cntFil++; continue;} + + if (!hpr.isOrder) { + if (hpr.isStEQ) cntDOeq++; else cntDOne++; + } + hpr.setSubs(); + + int i=1; + ps.setInt(i++, hpr.cHitNum); // this gets reset in AnchorMain, but used to map saveAnnoHits + ps.setInt(i++, pairIdx); + ps.setInt(i++, proj1Idx); + ps.setInt(i++, proj2Idx); + ps.setInt(i++, qGrpIdx); + ps.setInt(i++, tGrpIdx); + + ps.setInt(i++, hpr.xSumId); // pctid Avg%Id + ps.setInt(i++, hpr.xSumSim); // cvgpct; unsigned tiny int; now Avg%Sim + ps.setInt(i++, hpr.nHits); // countpct; unsigned tiny int; now #SubHits + ps.setInt(i++, hpr.xMaxCov); // score; max coverage + ps.setString(i++, hpr.htype) ; // htype EE, EI, etc + ps.setInt(i++, hpr.getGeneOverlap()); // geneOlap 0,1,2 + ps.setString(i++, hpr.sign); // Strand + + ps.setInt(i++, hpr.geneIdx[Q]); + ps.setInt(i++, hpr.geneIdx[T]); + ps.setInt(i++, hpr.hpStart[Q]); + ps.setInt(i++, hpr.hpEnd[Q]); + ps.setInt(i++, hpr.hpStart[T]); + ps.setInt(i++, hpr.hpEnd[T]); + + ps.setString(i++, hpr.querySubHits); + ps.setString(i++, hpr.targetSubHits); + + ps.addBatch(); + countBatch++; cntSave++; + if (countBatch==1000) { + countBatch=0; + ps.executeBatch(); + } + if (cntSave%10000==0) Globals.rprt(cntSave + "" loaded""); + + if (hpr.geneIdx[Q]>0 && hpr.geneIdx[T]>0) cntG2++; + else if (hpr.geneIdx[Q]>0 || hpr.geneIdx[T]>0) cntG1++; + else cntG0++; + } + if (countBatch>0) ps.executeBatch(); + ps.close(); + + mainObj.cntG2 += cntG2; + mainObj.cntG1 += cntG1; + mainObj.cntG0 += cntG0; + mainObj.cntClusters += cntSave; + + String msg1 = String.format(""Clusters %s-%s"", qChr, tChr); + if (Arg.VB) { + String msg2 = (AnchorMain2.bTrace) ? String.format(""Disorder (EQ,NE) %,4d %,4d "", cntDOeq, cntDOne) : """"; + String msg = String.format(""%-20s Both genes %,6d One gene %,6d No gene %,6d %s"", msg1, cntG2, cntG1, cntG0, msg2); + Utils.prtIndentNumMsgFile(plog, 1, cntSave, msg); // format same as Blocks and Pseudos + if (AnchorMain2.bTrace) Utils.prtIndentNumMsgFile(plog, 1, cntFil, ""Filtered or minor""); + } + else Globals.rprt(String.format(""%,5d %s"", cntSave, msg1)); + } + catch (Exception e) {ErrorReport.print(e, ""save to database""); bSuccess=false;} + } + + /************************************ + * Save all gene-hit pairs in pseudo_hits_annot + */ + private void saveAnnoHits() { + try { + if (tGeneMap.size()==0 && qGeneMap.size()==0) return; + + if (Arg.TRACE) Utils.prtIndentMsgFile(plog, 1, ""Save hits to genes ""); + DBconn2 tdbc2 = mainObj.tdbc2; + + // Load hits from database; the clNum was set as the unique hitNum (which will be redone in anchorMain) + TreeMap clIdxMap = new TreeMap (); + String st = ""SELECT idx, hitnum FROM pseudo_hits WHERE gene_overlap>0 and "" + + ""grp1_idx="" + qGrpIdx + "" and grp2_idx="" + tGrpIdx; + + ResultSet rs = tdbc2.executeQuery(st); + while (rs.next()) clIdxMap.put(rs.getInt(2), rs.getInt(1)); // cHitNum, DB generated idx + rs.close(); + + // Save major and minor T and Q; major are sorted before minor + // NOTE: if hit X overlaps query geneIdx 1 and 2 and target geneIdx 3 and 4, it will save + // X 1 3, X 2 3, but not X 1 4 and X 1 4 because Unique(hitNum, annot_idx); since ALGO1 has + // annot2_idx of 0, cannot have Unique(hitNum, annot_idx, annot2_idx) + PreparedStatement ps = tdbc2.prepareStatement(""insert ignore into pseudo_hits_annot "" + + ""(hit_idx, annot_idx, olap, exlap, annot2_idx) values (?,?,?,?,?)""); + + int cntBatch=0, cntAll=0; + int [] count = {0,0}; + + for (HitPair hpr : gxPairList) { + if (hpr.bin==0 || hpr.gtype==Arg.type0) continue; + if (hpr.flag!=Arg.MAJOR && hpr.flag!=Arg.MINOR) continue; + if (!clIdxMap.containsKey(hpr.cHitNum)) continue; // could have been filtered + + int dbhitIdx = clIdxMap.get(hpr.cHitNum); + + if (hpr.qGene!=null && hpr.geneIdx[Q]>0) { + ps.setInt(1, dbhitIdx); + ps.setInt(2, hpr.geneIdx[Q]); + ps.setInt(3, intScore(hpr.pGeneHitOlap[Q])); // GeneHitCov->GeneHitOlap + ps.setInt(4, intScore(hpr.pExonHitCov[Q])); + ps.setInt(5, hpr.geneIdx[T]); + ps.addBatch(); + cntBatch++; + count[Q]++; + cntAll++; + } + if (hpr.tGene!=null && hpr.geneIdx[T]>0) { + ps.setInt(1, dbhitIdx); + ps.setInt(2, hpr.geneIdx[T]); + ps.setInt(3, intScore(hpr.pGeneHitOlap[T])); + ps.setInt(4, intScore(hpr.pExonHitCov[T])); + ps.setInt(5, hpr.geneIdx[Q]); + ps.addBatch(); + cntBatch++; + count[T]++; + cntAll++; + } + if (cntBatch>=1000) { + cntBatch=0; + ps.executeBatch(); + } + if (cntAll%10000 ==0) Globals.rprt("" "" + cntAll + "" loaded hit annotations""); + } + if (cntBatch> 0) ps.executeBatch(); + Globals.rclear(); + if (Arg.TRACE) { + String msg = String.format(""%,10d for %s; %,d for %s"", count[Q], qChr, count[T], tChr ); + Utils.prtIndentMsgFile(plog, 1, msg); + } + } + catch (Exception e) {ErrorReport.print(e, ""save annot hits ""); bSuccess=false;} + } + private int intScore(double score) { + if (score>99 && score<100.0) score=99.0; + else if (score>100.0) score=100.0; + else if (score>0 && score<1.0) score=1.0; + return (int) Math.round(score); + } + /////////////////////////////////////////////////////////////////////// + private boolean fChk() { + if (mainObj.failCheck() || !bSuccess) { + bSuccess=false; + return true; + } + return false; + } + protected void clear() { + for (Gene gn : tGeneMap.values()) gn.clear(); + tGeneMap.clear(); + + for (Gene gn : qGeneMap.values()) gn.clear(); + qGeneMap.clear(); + + for (Hit ht : grpHitList) ht.clear(); + grpHitList.clear(); + + gpGxObj.clear(); + } + //////////////////////////////////////////////////////////////////////// + // Appends when multiple groups + private void prtToFile() { + try { + if (!Arg.TRACE) return; + String chr = ""T "" + tChr+ "": Q "" + qChr; + + // Cluster Major and Minor written to DB + if (mainObj.fhOutCl!=null) { + mainObj.fhOutCl.println("">>>>Exon Score; Pair for "" + traceHeader); + mainObj.fhOutCl.println("" "" + Arg.FLAG_DESC); + + if (gpGxObj==null) mainObj.fhOutCl.println(""Error ""); + else { + mainObj.fhOutCl.println(""Save order""); + + for (HitPair hpr : gxPairList) + if (hpr.flag==Arg.MAJOR || hpr.flag==Arg.MINOR) + mainObj.fhOutCl.println(hpr.toResults(chr, true)+""\n""); + for (HitPair hpr : gxPairList) + if (hpr.flag!=Arg.MAJOR && hpr.flag!=Arg.MINOR) + mainObj.fhOutCl.println(hpr.toResults(chr, true)+""\n""); + } + } + // Hit + if (mainObj.fhOutHit!=null) { + mainObj.fhOutHit.println(""\n>Bin "" + toResults() + "" "" + traceHeader); + + Hit.sortBySignByX(Q, grpHitList); + mainObj.fhOutHit.println("">>PRT By Sign By X; G0 processed ---------------------------------------""); + Hit last=null; + for (Hit ht : grpHitList) { + mainObj.fhOutHit.println(ht.toDiff(last)); + last= ht; + } + } + + // Gene + if (mainObj.fhOutGene!=null) { + mainObj.fhOutGene.println(""\n>T GENEs with hits "" + traceHeader ); + + for (Gene gn : tGeneMap.values()) { + Hit.sortBySignByX(Q, gn.gHitList); + String x = gn.toResults(); + if (x!="""") mainObj.fhOutGene.println(""T"" + gn.toResults()); + } + + mainObj.fhOutGene.println(""\n>Q GENEs with hits "" + traceHeader); + + for (Gene gn : qGeneMap.values()) { + Hit.sortBySignByX(T, gn.gHitList); + String x = gn.toResults(); + if (x!="""") mainObj.fhOutGene.println(""Q"" + gn.toResults()); + } + } + // Pile + if (mainObj.fhOutPile!=null) { + mainObj.fhOutPile.println(mainObj.fileName); + gpPileObj.prtToFile(mainObj.fhOutPile, chr); + } + + } catch (Exception e) {ErrorReport.print(e, ""Print to file""); } + } + private void prtTrace() { + if (!Arg.TRACE) return; + prtToFile(); + + int [] limit = {1,3,6,12,10000000}; + int [] cntG0m = {0,0,0,0,0}; // major only + int [] cntG1m = {0,0,0,0,0}; + int [] cntG2m = {0,0,0,0,0}; + int [] cntG0t = {0,0,0,0,0}; // totals + int [] cntG1t = {0,0,0,0,0}; + int [] cntG2t = {0,0,0,0,0}; + int cntMin1=0, cntMin2=0, cntMin0=0, cntF1=0, cntF2=0, cntF0=0; + int cntIgn1=0, cntIgn2=0, cntIgn0=0, cntP1=0, cntP2=0, cntP0=0, cntUnk1=0, cntUnk2=0, cntUnk0=0; + int cntGgood1=0, cntGood2=0, cntGood0=0, cntDis1=0, cntDis2=0, cntDis0=0, cntDisNE1=0, cntDisNE2=0, cntDisNE0=0; + + for (HitPair hpr : gxPairList) { + // All pairs + + if (hpr.tGene==null && hpr.qGene==null) { + for (int i=0; i""+limit[3], + ""Minor*"", ""Filter"", ""Ign Unk"", ""Pile"", ""Good+"", ""Disorder (EQ,NE)""); + Utils.prtIndentMsgFile(plog, 1, msg); + + cnt=0; + for (int i=0; i""+limit[3]); + Globals.tprt(msg); + + cnt=0; + for (int i=0; i tGeneMap = null, qGeneMap = null; // key: geneIdx + private ArrayList grpHitList = null; // all hits for chrPair + + private ProgressDialog plog; + private String chrPair; + + // GrpPairs: create clusters from major, saveAnnoHits G2/G1 major and minor + private ArrayList gxFinalList = new ArrayList (); // all pairs for chrPair + + private boolean bSuccess=true; // used by all + + public GrpPairGx(GrpPair grpPairObj) { // GrpPair.buildClusters; uses gxPairList to finish and save + this.grpPairObj = grpPairObj; + plog = grpPairObj.plog; + + tGeneMap = grpPairObj.tGeneMap; + qGeneMap = grpPairObj.qGeneMap; + grpHitList = grpPairObj.grpHitList; + + chrPair = grpPairObj.qChr + "","" + grpPairObj.tChr; + + intronLen2xG1 = Arg.iGmIntronLen2x; + intronLen4xG2rm = Arg.iGmIntronLen4x; + intronLenRm = Arg.iGmIntronLenRm; + intronLenG0 = (intronLen4xG2rm>8000) ? 8000 : intronLen4xG2rm; + } + /***************************************************** + * All results are put in gxPairList + */ + protected boolean run() { + try { + new G2Pairs(); if (!bSuccess) return false;// G2: Genes are already assigned to genes + + new G1Pairs(); if (!bSuccess) return false;// G1: Make T or Q pseudo-genes + + new G0Pairs(); if (!bSuccess) return false;// G0: Make T and Q pseudo-genes + + /* Finish */ + + if (TRC) { + int cntEE=0, cntEI=0, cntIE=0, cntII=0, cntEn=0, cntnE=0, cntIn=0, cntnI=0, cntnn=0; + for (HitPair hpr : gxFinalList) { + if (hpr.flag!=Arg.MAJOR && hpr.flag!=Arg.MINOR) continue; + String t = hpr.htype; + if (t.equals(Arg.sEE)) cntEE++; else if (t.equals(Arg.sIE)) cntIE++; else if (t.equals(Arg.sEI)) cntEI++; + else if (t.equals(Arg.sII)) cntII++; else if (t.equals(Arg.sEn)) cntEn++; else if (t.equals(Arg.snE)) cntnE++; + else if (t.equals(Arg.sIn)) cntIn++; else if (t.equals(Arg.snI)) cntnI++; else if (t.equals(Arg.snn)) cntnn++; + } + Globals.tprt(String.format("" EE %,d IE %,d EI %,d II %,d En %,d nE %,d In %,d nI %,d nn %,d"", + cntEE, cntIE, cntEI, cntII, cntEn, cntnE, cntIn, cntnI, cntnn)); + Globals.tprt(String.format(""Finish pairs: %,d gxPairList Initial %s"", gxFinalList.size(), chrPair)); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""GrpPairGx run""); return false; } + } + + /** GrpPair.buildClusters **/ + protected ArrayList getPairList() {return gxFinalList;} + + protected void clear() {// cleared in GrpPair: gpHitList (and hits), tGeneMap, qGeneMap (and genes) + for (HitPair hp : gxFinalList) hp.clear(); + gxFinalList.clear(); + } + + /***************************************************************** + * G2: create GenePairList; a hit can go into multiple gene pairs, e.g. hit aligns to 1.a & 1.b -> 2. + * use gxPairList directly since it is first to use it + * Results: all Major/Minor Hprs will be assigned a bin along with their hits + ******************************************************************/ + private class G2Pairs { + private ArrayList g2HprList = new ArrayList (); // Final list, to be added to gxPairList + private ArrayList wsPairList = new ArrayList (); // wrong strand - for -wsp + private int numFilter=0, numWS=0, numRmEnd=0, numRmLow=0; + + private G2Pairs() { + if (tGeneMap.size()==0 || qGeneMap.size()==0) return; + + if (TRC) Utils.prtIndentMsgFile(plog, 0, "">>G2: Remove hit use len: "" + intronLen4xG2rm); + + runG2(true); if (!bSuccess) return; // A gene can have a same strand and a diff strand RBH, though rare + runG2(false); if (!bSuccess) return; + + processWS(); + grpPairObj.mainObj.cntG2Fil+=numFilter; + grpPairObj.mainObj.cntRmEnd+=numRmEnd; + grpPairObj.mainObj.cntRmLow+=numRmLow; + } + private void runG2(boolean isStEQ) { + if (tGeneMap.size()==0 || qGeneMap.size()==0) return; + + step1MkPairAndFilter(isStEQ); if (!bSuccess) return; // create g2HprList and filter + + step2SetBinAllG2(); if (!bSuccess) return; // set Major from RBH and GoodEnough, and set minor + + // Finalize and cleanup; sorted by start in last of step2 + for (HitPair hpr : g2HprList) gxFinalList.add(hpr); // will have flag=IGNs (or FILTER if TRACE), but will not be saved in DB + + prtTrace(isStEQ); + + for (Hit ht : grpHitList) ht.bin2=0; + if (!TRC) + for (HitPair hpr : g2HprList) hpr.crossRefClear(); + g2HprList.clear(); + } + /******************************************* + * create by finding gene-pairs of hits and filter: (1) EQ (2) NE + *******************************************/ + private void step1MkPairAndFilter(boolean isStEQ) { + try { + HashMap hprGeneMap = new HashMap (); // tgn.geneIdx:qgn.geneIdx -> hits + + // Build g2 multi and single hit pairs from genes with shared hits + for (Hit ht: grpHitList) { // Loop by hit assigning hpr to T-Q gene pairs + if (ht.isStEQ!=isStEQ) continue; + + ht.mkGenePairs(); // makes pairs; tgn.geneIdx + "":"" + qgn.geneIdx + if (ht.gxPair.size()==0) continue; + + for (String idxPair : ht.gxPair) { // Loop through pairs + HitPair nhp; + String [] tok = idxPair.split("":""); + Gene tGene = tGeneMap.get(Arg.getInt(tok[0])); + Gene qGene = qGeneMap.get(Arg.getInt(tok[1])); + + if (!hprGeneMap.containsKey(idxPair)) { + nhp = new HitPair(Arg.type2, tGene, qGene, isStEQ); + hprGeneMap.put(idxPair, nhp); + } + else nhp = hprGeneMap.get(idxPair); + + nhp.addHit(ht); + ht.addGeneHit(tGene, qGene); + } + } + + // Filter wrong strand - put rest on allHprList + ArrayList allHprList = new ArrayList (); + + for (HitPair hpr : hprGeneMap.values()) { + hpr.setSign(); + if (hpr.isRst) { + allHprList.add(hpr); // transfer to allHprList + } + else { // do not allow wrong strand; many singletons; + if (Arg.WRONG_STRAND_PRT && hpr.qGene!=null && hpr.tGene!=null) { + hpr.setScores(); // need for EE check and to prints scores + if (hpr.htype.equals(""EE"")) wsPairList.add(hpr); + } + else hpr.clear(); + numFilter++; numWS++; + } + } + hprGeneMap.clear(); + + // Filter bad ends + sortForAssignGx(TQ, TQ, allHprList); + for (int i=allHprList.size()-1; i>=0; i--) { // remove extend ends from least good first + HitPair hpr = allHprList.get(i); + hpr.setScoresMini(); + + while (hpr.nHits>1 && rmEndHitsG2(hpr)); // if rm, if nHits=0, filter is set. + } + + // Filter main + for (HitPair hpr : allHprList) { + if (hpr.nHits==0) {numFilter++; numRmEnd++; hpr.clear(); continue;} // all hits removed + + hpr.setScores(); + + if (!Arg.bG2isOkay(hpr)) {numFilter++; numRmLow++; hpr.clear(); continue;} // Removes many! + + if (Arg.bG2passCov(0, hpr)) { + g2HprList.add(hpr); + continue; + } + + hpr.flag=Arg.FILTER; + numFilter++; + + if (hpr.nHits>1) { + for (Hit ht : hpr.hitList) { // create separate HPRs for subhits, some may pass on their own + HitPair nhp = new HitPair(Arg.type2, hpr.tGene, hpr.qGene, isStEQ); + nhp.addHit(ht); + nhp.setScores(); + if (Arg.bG2passCov(0, nhp)) g2HprList.add(nhp); + } + } + if (TRC) g2HprList.add(hpr); // will have orig single/multi; will not have multi->single + else hpr.clear(); + } + allHprList.clear(); + } + catch (Exception e) {ErrorReport.print(e,""Compute g2 genes""); bSuccess=false;} + } + /******************************************************** + * Remove end hits if gap is intronLen (helps a lot) or large extends and is in another hit + * Return true if may be able to remove another + */ + private boolean rmEndHitsG2(HitPair hpr) { + try { + if (hpr.nHits==1) { + if (hpr.pExonHitCov[T]>=100.0 && hpr.pExonHitCov[Q]>=100.0 + && hpr.pGeneHitCov[T]>=100.0 && hpr.pGeneHitCov[Q]>=100.0) {hpr.note += "" s100""; return false; } + } + int gap=0, extend=0; + boolean bRm=false, bDidRm=false; + + for (int X=0; X<2; X++) { // X=T,Q; need to check hit=1 for the (2) test + Hit.sortXbyStart(X, hpr.hitList); + Gene xgene = (X==Q) ? hpr.qGene : hpr.tGene; + Gene ygene = (X==Q) ? hpr.tGene : hpr.qGene; + int Y = (X==Q) ? T : Q; + int olap = (int) Math.round((double)Arg.pOlapOnly(xgene.gStart, xgene.gEnd, hpr.hpStart[X], hpr.hpEnd[X])/2.0); + + /* Check 1st hit */ + bRm=false; + Hit ht0 = hpr.hitList.get(0); + + if (hpr.nHits>1) { // (1) start has large gap and hits intron + Hit ht1 = hpr.hitList.get(1); + gap = Math.abs(ht1.hStart[X] - ht0.hEnd[X])+1; + bRm = (gap>intronLen4xG2rm && ht0.getExonCov(X, xgene)==0); + + if (bRm && TRC) hpr.note += "" rm1""+Arg.side[X]; + } + if (!bRm) { // (2) extends passed start and is in another hpr + extend = (ht0.hStart[X] < xgene.gStart) ? xgene.gStart-ht0.hStart[X] : 0; + if (extend>100) { + if (extend > olap || ht0.getExonCov(X, xgene)==0) { // see if overlaps another + bRm = ht0.bHitsAnotherExon(X, xgene) && ht0.bHitsAnotherExon(Y, ygene); + if (bRm && TRC) hpr.note += "" rm1x""+Arg.side[X]+""-""+ht0.hitNum; + } + } + } + if (bRm) { // Remove 1st hit + hpr.rmHit(X, xgene, ygene, 0); // remove hit and genes from hit, sets flag=FILTER if nHits==0 + if (hpr.nHits==0) return false; + bDidRm=true; + } + + /* Check end hit */ + bRm=false; + int sz = hpr.hitList.size()-1; + + ht0 = hpr.hitList.get(sz); + if (hpr.nHits>1) { // (1) end with gap and hits intron + Hit ht1 = hpr.hitList.get(sz-1); + gap = Math.abs(ht0.hStart[X] - ht1.hEnd[X]); + bRm = (gap>intronLen4xG2rm && ht0.getExonCov(X, xgene)==0); + if (bRm && TRC) hpr.note += "" rmN""+Arg.side[X]; + } + if (!bRm) { // (2) extends passed end and is in another hpr + extend = (ht0.hEnd[X] > xgene.gEnd) ? ht0.hEnd[X]-xgene.gEnd : 0; + if (extend>100) { + if (extend>olap || ht0.getExonCov(X, xgene)==0) { + bRm = ht0.bHitsAnotherExon(X, xgene) && ht0.bHitsAnotherExon(Y, ygene); + if (bRm && TRC) hpr.note += "" rmNx""+Arg.side[X]+""-""+ht0.hitNum; + } + } + } + if (bRm) { // Remove last hit + hpr.rmHit(X, xgene, ygene, sz); + if (hpr.nHits==0) return false; + bDidRm=true; + } + } // end X=TQ loop + + return bDidRm; + } + catch (Exception e) {ErrorReport.print(e,""Compute g2 genes""); bSuccess=false; return false;} + } + /********************************************************* + * Assign major, minor and assign bin to multi and single + * g2HprList - complete set + ********************************************************/ + private void step2SetBinAllG2() { + try { + // Make list of HPRs for each gene + for (HitPair hpr : g2HprList) hpr.crossRef(); + + for (Gene gn : qGeneMap.values()) { + if (gn.gHprList.size()>1) + sortForAssignGx(Q, T, gn.gHprList); // gn.gHprList will have best first + } + for (Gene gn : tGeneMap.values()) { + if (gn.gHprList.size()>1) + sortForAssignGx(T, Q, gn.gHprList); // gn.gHprList will have best first + } + + sortForAssignGx(TQ,TQ, g2HprList); // sort by score - multi and single + HashMap majorMap = new HashMap (); // bin, HitPair; used in setMinor for lookup + + // Loop Major RBH: find best major using RBH genes; these have already passed cov test idx=0 + for (HitPair hpr : g2HprList) { + if (hpr.flag!=Arg.UNK) continue; // Not Arg.FILTER + + if (hpr != hpr.qGene.gHprList.get(0) || + hpr != hpr.tGene.gHprList.get(0)) continue; // not RBH + + for (Hit ht: hpr.hitList) ht.setBin(nBin); + hpr.flag = Arg.MAJOR; + hpr.bin = nBin++; + majorMap.put(hpr.bin, hpr); + + if (TRC) hpr.note += "" best""; + } + + // Loop Major: Good Enough + for (HitPair hpr : g2HprList) { + if (hpr.flag!=Arg.UNK) continue; // Not Arg.FILTER or Arg.MAJOR + + int minorBin = setMinor(1, hpr, majorMap); // if can be minor, assign on next loop when all majors are done + + if (minorBin==0 && Arg.bG2passCov(1, hpr)) { // 1 is more stringent (already passed 0) + hpr.flag = Arg.MAJOR; + hpr.bin = nBin++; + for (Hit ht: hpr.hitList) ht.setBin(hpr.bin); + majorMap.put(hpr.bin, hpr); + + if (TRC) hpr.note += "" good+""; + } + } + + // Loop Minor or Ignore + for (HitPair hpr : g2HprList) { + if (hpr.flag!=Arg.UNK) continue; + + int minorBin = setMinor(2, hpr, majorMap); // sufficient shared hits + if (minorBin>0) { + hpr.flag = Arg.MINOR; + hpr.bin = minorBin; + } + else {numFilter++; hpr.flag = Arg.IGN; } + } + majorMap.clear(); + + // Loop Remove exact coords; do last since may flip major to minor + HitPair last=null; + HitPair.sortByXstart(T, g2HprList); + for (HitPair hpr : g2HprList) { + if (hpr.flag!=Arg.MAJOR) continue; + if (last!=null) { + if (Arg.bHprOlap(last, hpr)) { + ArrayList dups = new ArrayList (2); + dups.add(last); + dups.add(hpr); + sortForAssignGx(TQ, TQ, dups); + + HitPair dhp = dups.get(1); + dhp.flag = Arg.MINOR; + dhp.bin = dups.get(0).bin; + dhp.note = ""Dup-""+dups.get(0).bin; + } + } + last = hpr; + } + } + catch (Exception e) {ErrorReport.print(e,""g2 set major""); bSuccess=false;} + } + /********************************************************* + * hpr: is minor? Called from setBinAllG2 + * majorMap: + * step: 1 check if there is a definite minor; 2 assign minor if possible + * The benefit of Minor is to give every gene a 'hit' if possible, as then it shows in Query Every* + * Return: 0 not minor, >0 bin to set for minor + */ + private int setMinor(int step, HitPair hpr, HashMap majorMap) { + try { + if (!hpr.tGene.isOlapGene && !hpr.qGene.isOlapGene) return 0; + String tGeneTag = hpr.tGene.geneTag, qGeneTag=hpr.qGene.geneTag; + + HashMap binMap = new HashMap (); // bin, cntShared + int cntBin0=0; + + // Count how may hits this hpr has in each hit bin + for (Hit ht: hpr.hitList) { + if (ht.bin==0) cntBin0++; + else { + if (!binMap.containsKey(ht.bin)) binMap.put(ht.bin, 1); + else binMap.put(ht.bin, binMap.get(ht.bin)+1); + + if (ht.bin2>0) { // hit can be in multiple HitPairs + if (!binMap.containsKey(ht.bin2)) binMap.put(ht.bin2, 1); + else binMap.put(ht.bin2, binMap.get(ht.bin2)+1); + } + } + } + if (cntBin0==hpr.nHits) return 0; // all unique + + // Find the best and check contained + int bestBin=0, bestCnt=0; + + for (int bin : binMap.keySet()) { + int cnt = binMap.get(bin); + if (cnt>bestCnt) { + HitPair majHpr = majorMap.get(bin); + if (majHpr.tGene.geneTag.equals(tGeneTag) || majHpr.qGene.geneTag.equals(qGeneTag)) { + bestBin = bin; + bestCnt = cnt; + } + } + } + if (bestCnt==hpr.nHits) return bestBin; // Contained - does not matter if both already major + + // Not contained, then if already major do not make minor + int cntMajT=0, cntMajQ=0; + for (HitPair thp : hpr.tGene.gHprList) if (thp.flag==Arg.MAJOR) cntMajT++; + for (HitPair qhp : hpr.qGene.gHprList) if (qhp.flag==Arg.MAJOR) cntMajQ++; + if (cntMajT>0 && cntMajQ>0) return 0; + + // for all major, check if bestBin or any other qualify as minor + // 1. bestCnt will not include hits shared with overlapping majors, + // 2. or there may be HPRs with tied binMap counts, but different nHits + int shareBin=0, shareCnt=0; + for (int i=0; i<2; i++) { + for (int bin : binMap.keySet()) { + if (i==0 && bin!=bestBin) continue; // give bestBin 1st chance + if (i==1 && bin==bestBin) continue; + + HitPair majHpr = majorMap.get(bin); + int cnt=0; + for (Hit ht1: majHpr.hitList) { + for (Hit ht2 : hpr.hitList) { + if (ht1==ht2) { + cnt++; + break; + } + } + } + if (cnt==hpr.nHits) return bin; // could still happen... + + double p1 = ((double) cnt/(double)hpr.nHits); + double p2 = ((double) cnt/(double)majHpr.nHits); + if (p1>=pCutoff5 && p2>=pCutoff8) { + if (step==2 || hpr.lenRatioshareCnt) { + shareCnt = cnt; + shareBin = bin; + } + } + } + if (step==1) return 0; + + // one more try for step2 + HitPair majHpr = majorMap.get(shareBin); + double p1 = ((double) shareCnt/(double)hpr.nHits); + double p2 = ((double) shareCnt/(double)majHpr.nHits); + if (p1>=pCutoff5 || p2>=pCutoff8) return shareBin; + if (p1>=pCutoff5-0.1 && p2>=pCutoff8-0.1) return shareBin; + return 0; + } + catch (Exception e) {ErrorReport.print(e,""g2 getMinor""); bSuccess=false; return 0;} + } + + /******************************************************************** + * if -wsp, output wrong strand; + */ + private void processWS() { // all needed info is in wsPairList + if (!Arg.WRONG_STRAND_PRT) { + grpPairObj.mainObj.cntWS += numWS; + return; + } + Globals.rclear(); + if (wsPairList.size()==0) return; + + final String dot = Globals.DOT; + final int cutoff=2; + TreeMap tGeneMap = new TreeMap (); + TreeMap qGeneMap = new TreeMap (); + + HitPair.sortByXstart(Q, wsPairList); + + // Count genes at each end of cutoff (must have 'cutoff' effected genes) + for (HitPair hpr : wsPairList) { + if (!hpr.htype.equals(""EE"")) continue; + + String tTag = hpr.tGene.geneTag, qTag = hpr.tGene.geneTag; + if (!tTag.endsWith(dot) && !qTag.endsWith(dot)) continue; // probably share hits with isRst overlapped genes + + if (tGeneMap.containsKey(tTag)) tGeneMap.put(tTag, tGeneMap.get(tTag)+hpr.nHits); + else tGeneMap.put(tTag, hpr.nHits); + + if (qGeneMap.containsKey(qTag)) qGeneMap.put(qTag, qGeneMap.get(qTag)+hpr.nHits); + else qGeneMap.put(qTag, hpr.nHits); + } + // check if there will be any output + int cnt=0; + for (int n : tGeneMap.values()) if (n>cutoff) cnt++; + for (int n : qGeneMap.values()) if (n>cutoff) cnt++; + if (cnt==0) return; + + // Output + + Globals.prt(String.format(""#Subs Gene Hit %-10s %-10s [Exon Gene Length] [Exon Gene Length] %s "", + grpPairObj.mainObj.proj1Name, grpPairObj.mainObj.proj2Name, chrPair)); + + for (HitPair hpr : wsPairList) { + if (!hpr.htype.equals(""EE"")) continue; + + String tTag = hpr.tGene.geneTag, qTag = hpr.tGene.geneTag; + if (!tTag.endsWith(dot) && !qTag.endsWith(dot)) continue; + + if (tGeneMap.get(tTag)>cutoff || qGeneMap.get(qTag)>cutoff) { // don't want a lot of little hits + Globals.prt(hpr.toWSResults()); + } + } + grpPairObj.mainObj.cntWS += cnt; + } + /************************************************************** + * Counts content of notes from this file, booleans, and single/mult + */ + private void prtTrace(boolean isStEQ) { + if (!TRC) return; + + if (grpPairObj.mainObj.fhOutHPR[2]!=null) { + grpPairObj.mainObj.fhOutHPR[2].println(""## "" + chrPair + "" "" + Arg.isEQstr(isStEQ) + "" HPRs: "" + g2HprList.size()); + for (HitPair ph : g2HprList) + grpPairObj.mainObj.fhOutHPR[2].println(ph.toResults(chrPair, true)+""\n""); + } + } + + } // End G2 class + /***************************************************************** + // G1 create opposite side pseudogenes and match with T/Q genes + * Uses genes to gather hits without mate + * All hits with a bin>0 are in a G2; G1 hits get a temporary tbin + ******************************************************************/ + private class G1Pairs { + private ArrayList g1HprList = new ArrayList (); // Final list, to be added to gxPairList + + private G1Pairs() { + if (TRC) Utils.prtIndentMsgFile(plog, 0, "">>G1: Intron 2x "" + intronLen2xG1 + + "" Sm "" + intronLenRm + "" hits "" + grpHitList.size()); + + if (qGeneMap.size()!=0) { // Make T pseudo-genes and use Q genes; put results in global gxPairList + runG1(Q, T, qGeneMap, true); if (!bSuccess) return; // isStEQ + runG1(Q, T, qGeneMap, false); if (!bSuccess) return; // !isStEQ + } + if (tGeneMap.size()!=0) { // Make Q pseudo-genes and use T genes + runG1(T, Q, tGeneMap, true); if (!bSuccess) return; + runG1(T, Q, tGeneMap, false); if (!bSuccess) return; + } + for (Hit ht : grpHitList) ht.bin2=0; + } + private void runG1(int X, int Y, TreeMap xGeneMap, boolean isStEQ) { + try { + // Process + stepMkPairs(X, Y, xGeneMap, isStEQ); + + // Bins - no minor assigned + sortForAssignGx(X, Y, g1HprList); + + for (HitPair hpr : g1HprList) { + if (hpr.flag==Arg.UNK) { // could be FILTER + hpr.flag = Arg.MAJOR; + hpr.bin = nBin++; + for (Hit ht: hpr.hitList) if (ht.bin==0) ht.bin = hpr.bin; + } + } + + // Finish + for (HitPair hpr : g1HprList) gxFinalList.add(hpr); + + prtTrace(X, isStEQ); + + g1HprList.clear(); + } + catch (Exception e ) {ErrorReport.print(e, ""runG1""); + } + } + private void stepMkPairs(int X, int Y, TreeMap xGeneMap, boolean isStEQ) { + try { + double lenRatioCut = Arg.dLenRatio +0.2; + int cntG1Mf=0, cntG1Sf=0; + + int type = (X==Q) ? Arg.type1q : Arg.type1t; + int tBin2 = 1; // temporary bin to show its in a multiMap or been used + + /* g1 loop by gene */ + for (Gene xgene : xGeneMap.values()) { + ArrayList gnHitList = xgene.getHitsForXgene(X, Y, isStEQ); // bin=0, no Y gene for xgene + if (gnHitList==null || gnHitList.size()==0) continue; + + Hit.sortBySignByX(Y, gnHitList); // sort by intergenic + Gene tGene = (X==T) ? xgene : null; + Gene qGene = (X==Q) ? xgene : null; + + HashMap hprMultiMap = new HashMap (); // bin, object + int nHits = gnHitList.size(); + + // For gene loop by hit: create multi-hpr; a gene can have multiple hprs + for (int r1=0; r10 && !hprMultiMap.containsKey(ht1.bin2)) continue; // already taken for this Q,isStEq + + for (int r2=r1+1; r20) continue; + + int yDiff = Math.abs(ht2.hStart[Y]-ht1.hEnd[Y]); + if (yDiff> intronLen2xG1) continue; + + HitPair hpr=null; + if (ht1.bin2==0) { // make a hitPair if at least two hits within distance + hpr = new HitPair(type, tGene, qGene, isStEQ); + ht1.bin2 = tBin2++; // set bin so it will not be made a single hpr + hpr.addHit(ht1); + + hprMultiMap.put(ht1.bin2, hpr); + } + else hpr = hprMultiMap.get(ht1.bin2); + + ht2.bin2 = ht1.bin2; + hpr.addHit(ht2); + } + } + // For multi in gene's hprMultiMap + for (HitPair hpr : hprMultiMap.values()) { + + // prune ends from gene side, then non-gene + hpr.setScoresMini(); + while (rmEndHitsG1(X, hpr, true)); + while (hpr.lenRatio1 && Arg.bG1passCov(X, hpr)) { + g1HprList.add(hpr); + } + else { // break back into singles + cntG1Mf++; + for (Hit ht : hpr.hitList) ht.bin2 = 0; // identify singles in gnHitList + + if (TRC) { + hpr.flag = Arg.FILTER; + g1HprList.add(hpr); + } + else hpr.clear(); + } + } + hprMultiMap.clear(); + + // For singles in gene's gnHitList + for (Hit ht : gnHitList) { + if (ht.bin2>0) continue; + + HitPair hpr = new HitPair(type, tGene, qGene, isStEQ); + hpr.addHit(ht); + + hpr.setScores(); + + if (Arg.bG1passCov(X, hpr)) { + g1HprList.add(hpr); + ht.bin2 = tBin2++; + } + else { + cntG1Sf++; + if (TRC) { + hpr.flag = Arg.FILTER; + g1HprList.add(hpr); + } + else hpr.clear(); + } + } + gnHitList.clear(); + } // finish g1 Loop by gene + + grpPairObj.mainObj.cntG1Fil+= (cntG1Sf+cntG1Mf); + } + catch (Exception e) {ErrorReport.print(e,""Compute G1 clusters""); bSuccess=false;} + } + /******************************************************** + * Remove end hits if gap is intronLen + * Without the other gene constraint, the gene side have the big gap at beginning or end + * Return True: run again, False: do not run again + */ + private boolean rmEndHitsG1(int X, HitPair hpr, boolean isGene) { + try { + if (hpr.nHits<=1) return false; + + Hit.sortXbyStart(X, hpr.hitList); + + Gene xygene; + if (X==Q) if (isGene) xygene = hpr.qGene; else xygene=hpr.tGene; + else if (isGene) xygene = hpr.tGene; else xygene=hpr.qGene; + + boolean bDidRm=false, bTest; + Hit ht0, ht1; + double olap; + int iRm; + + for (int i=0; i<2; i++) { // i=0 remove 1st, i=1 remove end + if (i==0) { + ht0 = hpr.hitList.get(0); + ht1 = hpr.hitList.get(1); + iRm=0; + } + else { + ht0 = hpr.hitList.get(hpr.nHits-1); + ht1 = hpr.hitList.get(hpr.nHits-2); + iRm = hpr.nHits-1; + } + olap = Arg.pGap_nOlap(ht0.hStart[X], ht0.hEnd[X], ht1.hStart[X], ht1.hEnd[X]); + + bTest = isGene && ((olap > intronLen2xG1) || (olap>intronLenRm && ht0.getExonCov(X, xygene)==0)); + if (!bTest) bTest = !isGene && (olap > intronLenRm); // it may cover an exon on gene side, but would need to check amount olap on that side + + if (bTest) { + hpr.rmHit(X, xygene, null, iRm); // setScoreMini after change + ht0.bin2 = 0; // Hit is in gene list, can try for single + bDidRm = true; + if (TRC) { + String x = (i==0) ? ""0"" : ""n""; + hpr.note += "" rm"" + Arg.toTF(isGene) + x + Arg.side[X] + ""#"" + ht0.hitNum; + } + } + if (hpr.nHits<=1) return false; + } + return bDidRm; + } + catch (Exception e) {ErrorReport.print(e,""g1 rm end hits ""); bSuccess=false; return false;} + } + + /************************************************* + * Write summary and to file + */ + private void prtTrace(int X, boolean isStEQ) { + try { + if (!TRC) return; + + // To file + if (grpPairObj.mainObj.fhOutHPR[1]!=null) { + grpPairObj.mainObj.fhOutHPR[1].println(""##"" + Arg.side[X] + "" "" + Arg.isEQstr(isStEQ) + "" HPRs: "" + g1HprList.size()); + for (HitPair ph : g1HprList) + grpPairObj.mainObj.fhOutHPR[1].println(ph.toResults("""", true)+""\n""); + } + } + catch (Exception e) {ErrorReport.print(e,""g1 prt trace""); bSuccess=false;} + } + } // End G1 + /*************************************************************** + * G0: Create pairs for G0, where both sides are bound by intron length + */ + private class G0Pairs { + int cntG0Mf=0, cntG0Sf=0; + + private G0Pairs() { + if (TRC) Globals.tprt("">>G0 use Intron "" + intronLenG0); + + for (int eq=0; eq<2; eq++) { + runG0(eq==0); if (!bSuccess) return; + } + grpPairObj.mainObj.cntG0Fil+=(cntG0Mf+cntG0Sf); + } + /* create by finding runs of hits with intron length */ + private void runG0(boolean isStEQ) { + try { + ArrayList g0HitList = new ArrayList (); // Find isStEQ hits with no genes + for (Hit ht : grpHitList) { + if (ht.isStEQ==isStEQ && ht.bNoGene()) g0HitList.add(ht); + } + Hit.sortXbyStart(Q, g0HitList); + + // Multi: Loop thru g0 hits to create multi hprs + int tBin=1, nG0Hits=g0HitList.size(); + HashMap multiHprMap = new HashMap (); + + for (int r0=0; r00) continue; + + int qDiff = ht2.hStart[Q]-ht1.hEnd[Q]; + if (qDiff>intronLenG0) break; + + int tDiff = (isStEQ) ? Math.abs(ht2.hStart[T] - ht1.hEnd[T]) + : Math.abs(ht1.hStart[T] - ht2.hEnd[T]); + if (tDiff>intronLenG0) continue; + + HitPair hpr; + if (ht1.bin2==0) { + hpr = new HitPair(Arg.type0, null, null, isStEQ); + multiHprMap.put(tBin, hpr); + + hpr.addHit(ht1); + ht1.bin2 = tBin++; + } + else hpr = multiHprMap.get(ht1.bin2); + + ht2.bin2 = ht1.bin2; + hpr.addHit(ht2); + } + } + + // Multi: Loop multiHpr and score + ArrayList hprList = new ArrayList (); + for (HitPair hpr : multiHprMap.values()) { + + hpr.setScoresMini(); + if (hpr.lenRatio<0.1) continue; + + int cntRm=0; + while (cntRm<5 && rmEndHitsG0(hpr)) {cntRm++;} // setScoreMini, bin2=0 if removed + if (hpr.nHits<=1) { + if (TRC) {hpr.flag = Arg.FILTER; hprList.add(hpr);} + else hpr.clear(); + continue; + } + hpr.setScores(); + if (Arg.bG0passCov(hpr)) { + hprList.add(hpr); + hpr.flag = Arg.MAJOR; + } + else { + cntG0Mf++; + for (Hit ht : hpr.hitList) ht.bin2=0; // for singles + + if (TRC) {hpr.flag = Arg.FILTER; hprList.add(hpr);} + else hpr.clear(); + } + } + multiHprMap.clear(); + + // Singles: Loop thru g0 hits to create and filter single hprs + for (Hit ht : g0HitList) { + if (ht.bin2>0) {ht.bin2=0; continue;} + + HitPair hpr = new HitPair(Arg.type0, null, null, isStEQ); + hpr.addHit(ht); + hpr.setScores(); + + if (Arg.bG0passCov(hpr)) { + hprList.add(hpr); + } + else { + cntG0Sf++; + + if (Globals.TRACE) {hpr.flag = Arg.FILTER; hprList.add(hpr);} + else hpr.clear(); + } + } + g0HitList.clear(); + + sortForAssignG0(hprList); // Add sorted g0PairList to main list + for (HitPair hpr : hprList) { + hpr.bin = nBin++; + if (hpr.flag!=Arg.FILTER) hpr.flag = Arg.MAJOR; + gxFinalList.add(hpr); + } + + prtTrace(isStEQ, hprList); + hprList.clear(); + } + catch (Exception e) {ErrorReport.print(e,""Compute G0 clusters""); bSuccess=false;} + } + private boolean rmEndHitsG0(HitPair hpr) { + try { + if (hpr.nHits<=1) return false; + + boolean bDidRm=false; + Hit ht0, ht1; + double olap; + int iRm; + + for (int X=0; X<2; X++) { // X=0 remove 1st, X=1 remove end + Hit.sortXbyStart(X, hpr.hitList); + + if (X==0) { + ht0 = hpr.hitList.get(0); + ht1 = hpr.hitList.get(1); + iRm=0; + } + else { + ht0 = hpr.hitList.get(hpr.nHits-1); + ht1 = hpr.hitList.get(hpr.nHits-2); + iRm = hpr.nHits-1; + } + olap = Arg.pGap_nOlap(ht0.hStart[X], ht0.hEnd[X], ht1.hStart[X], ht1.hEnd[X]); + + if (olap > intronLenRm) { + hpr.rmHit(X, null, null, iRm); // setScoreMini after change + ht0.bin2 = 0; // Hit is in gene list, can try for single + bDidRm = true; + if (TRC) { + String x = (X==0) ? ""0"" : ""N""; + hpr.note += "" rm"" + x + Arg.toTF(hpr.isStEQ) + Arg.side[X] + ""#"" + ht0.hitNum; + } + } + if (hpr.nHits<=1) return false; + } + return bDidRm; + } + catch (Exception e) {ErrorReport.print(e,""g1 rm end hits ""); bSuccess=false; return false;} + } + /************************************************* + * Write summary and to file + */ + private void prtTrace(boolean isStEQ, ArrayList hprList) { + try { + if (!TRC) return; + + // To file + if (grpPairObj.mainObj.fhOutHPR[0]!=null) { + grpPairObj.mainObj.fhOutHPR[0].println(""##"" + Arg.isEQstr(isStEQ) + "" HPRs: "" + hprList.size()); + for (HitPair ph : hprList) + grpPairObj.mainObj.fhOutHPR[0].println(ph.toResults("""", true)+""\n""); + } + } + catch (Exception e) {ErrorReport.print(e,""g1 prt trace""); bSuccess=false;} + } + } // End class G0 + + /////////////////////////////////////////////////////////////////////////////////////// + // added this because had a violates + protected void sortForAssignGx(int X, int Y, ArrayList gpList) {// G2, G1 + try { + sortForAssignTry1(X, Y, gpList); + return; + } + catch (Exception e) {} + Globals.dtprt(""First sort did not work - try easier one...""); + + try { + sortForAssignTry2(X, gpList); + return; + } + catch (Exception e) {} + + Globals.dtprt(""Second sort did not work - try an easier...""); + try { + sortForAssignTry3(X, gpList); + return; + } + catch (Exception e) {} + + Globals.eprt(""Algo2 will not work for this dataset - use Algo1""); + bSuccess=false; + } + // This can get a comparison Comparison method violates its general contract! + + // This can get a comparison Comparison method violates its general contract! + protected void sortForAssignTry1(int X, int Y, ArrayList gpList) { // GrpPairGx g2TQ + Collections.sort(gpList, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + if (h1.isRst && !h2.isRst) return -1; + if (!h1.isRst && h2.isRst) return 1; + + if (h1.flag==Arg.UNK && h2.flag!=Arg.UNK) return -1; // could be filter, dup + if (h1.flag!=Arg.UNK && h2.flag==Arg.UNK) return 1; + + if (h1.htype.equals(Arg.sEE) && !h2.htype.equals(Arg.sEE)) return -1; + if (!h1.htype.equals(Arg.sEE) && h2.htype.equals(Arg.sEE)) return 1; + + if (h1.pExonHitCov[X]>h2.pExonHitCov[X]) return -1; + if (h1.pExonHitCov[X]h2.pGeneHitOlap[X]) return -1; + if (h1.pGeneHitOlap[X]h2.pHitGapCov[X]) return -1; + if (h1.pHitGapCov[X]h2.pExonHitCov[Y]) return -1; + if (h1.pExonHitCov[Y]h2.pGeneHitOlap[Y]) return -1; + if (h1.pGeneHitOlap[Y]h2.pHitGapCov[Y]) return -1; + if (h1.pHitGapCov[Y]h2.lenRatio) return -1; + if (h1.lenRatioh2.nHits) return -1; + if (h1.nHitsh2.nHpr) return -1; // deterministic sort on identical hits; may have caused the violate + if (h1.nHpr gpList) { // GrpPairGx g1T, g1Q, g2TQ + Collections.sort(gpList, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + if (h1.isRst && !h2.isRst) return -1; + if (!h1.isRst && h2.isRst) return 1; + + if (h1.flag==Arg.UNK && h2.flag!=Arg.UNK) return -1; // could be filter + if (h1.flag!=Arg.UNK && h2.flag==Arg.UNK) return 1; + + if (h1.pExonHitCov[X]>h2.pExonHitCov[X]) return -1; + if (h1.pExonHitCov[X]h2.nHits) return -1; + if (h1.nHitsh2.nHpr) return -1; + if (h1.nHpr gpList) { // GrpPairGx g1T, g1Q, g2TQ + Collections.sort(gpList, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + if (h1.flag==Arg.UNK && h2.flag!=Arg.UNK) return -1; // could be filter + if (h1.flag!=Arg.UNK && h2.flag==Arg.UNK) return 1; + + if (h1.htype.equals(Arg.sEE) && !h2.htype.equals(Arg.sEE)) return -1; + if (!h1.htype.equals(Arg.sEE) && h2.htype.equals(Arg.sEE)) return 1; + + if (h1.nHpr>h2.nHpr) return -1; + if (h1.nHpr gpList) { // GrpPairGx g0 + Collections.sort(gpList, + new Comparator() { + public int compare(HitPair h1, HitPair h2) { + int X = TQ; + if (h1.flag==Arg.MAJOR && h2.flag!=Arg.MAJOR) return -1; // could be filter + if (h1.flag!=Arg.MAJOR && h2.flag==Arg.MAJOR) return 1; + + if (h1.pHitGapCov[X]>h2.pHitGapCov[X]) return -1; + if (h1.pHitGapCov[X]h2.xMaxCov) return -1; + if (h1.xMaxCovh2.nHits) return -1; + if (h1.nHits inorder = new Vector (); + + tree.tree2array(tree.root, inorder); + + return inorder.toArray(new Gene[0]); + } + + protected TreeSet findOlapSet(int hstart, int hend, boolean bAll) { + return tree.findOverlapSet(hstart, hend, bAll); // if false, only return longest gene with start + } + protected void finish() { + tree.iAssignMaxEnd(tree.root); + } + protected void clear() { + tree.clear(tree.root); + tree.root = null; + cntDupStart=cntGenes=0; + } + + protected String toResults() { + return String.format(""Tree: %-20s Genes: %,6d DupStart %,4d"", title, cntGenes, cntDupStart);} + public String toString() {return toResults();} + + /***********************************************************/ + protected class Node implements Comparable { + private Gene itvObj; // interval that encompasses startSet intervals + private int start, end; // same as itvObj.start, itvObj.end + private TreeSet startSet=null; // intervals with same start, contained in itvObj + + private int maxEnd=0, height=1; + private Node left, right; + + private Node (Gene itv) { + this.start = itv.gStart; + this.end = itv.gEnd; + itvObj = itv; + maxEnd = end; + } + private void add(Gene gn) { + if (startSet==null) startSet = new TreeSet (); + + if (gn.gEnd > end) { + startSet.add(itvObj); + itvObj = gn; + maxEnd = end = gn.gEnd; + } + else startSet.add(gn); + } + public int compareTo(Node n) { + if (this.start < n.start) return -1; + else if (this.start == n.start) return this.end > n.end ? -1 : 1; + else return 1; + } + public String toString() { + String msg = (startSet!=null) ? ""Set "" + startSet.size() : ""0""; + return ""["" + start + "","" + end + ""] Max("" + maxEnd + "") "" + msg; + } + protected void clear() { // node + if (startSet!=null) { + startSet.clear(); + startSet=null; + } + itvObj=null; + left=right=null; + start=end=0; + } + } + /************************************************************/ + private class Tree { + protected Node root=null; + + protected Node insertNode(Node node, Gene gn) { + if (node == null) return new Node(gn); + + int hStart = gn.gStart; + if (hStart < node.start) node.left = insertNode (node.left, gn); + else if (hStart > node.start) node.right = insertNode (node.right, gn); + else die(""Duplicate start "" + gn.gStart); + + node.height = 1 + Math.max(iHeight(node.left), iHeight(node.right)); + + int balance = iBalance(node); + if (balance >= -1 && balance <= 1) return node; + + if (balance > 1 && hStart < node.left.start) { + return iRightRotate(node); + } + if (balance < -1 && hStart > node.right.start) { + return iLeftRotate(node); + } + if (balance > 1 && hStart > node.left.start) { + node.left = iLeftRotate (node.left); // here + return iRightRotate(node); + } + if (balance < -1 && hStart < node.right.start) { + node.right = iRightRotate(node.right); + return iLeftRotate(node); + } + return node; + } + private Node iRightRotate(Node y) { + try { + Node x = y.left; + Node T2 = x.right; + x.right = y; + y.left = T2; + + y.height = Math.max(iHeight (y.left), iHeight (y.right)) + 1; + x.height = Math.max(iHeight (x.left), iHeight (x.right)) + 1; + return x; + } + catch (Exception e) { ErrorReport.print(e, ""GeneTree right rotate""); return null;} + } + private Node iLeftRotate(Node x) { + try { + Node y = x.right; + Node T2 = y.left; // here + y.left = x; + x.right = T2; + + x.height = Math.max(iHeight(x.left), iHeight(x.right)) + 1; + y.height = Math.max(iHeight(y.left), iHeight(y.right)) + 1; + return y; + } + catch (Exception e) { ErrorReport.print(e, ""GeneTree left rotate""); return null;} + } + private int iHeight (Node N) { + if (N == null) return 0; + return N.height; + } + private int iBalance(Node N) { + if (N == null) return 0; + return iHeight(N.left) - iHeight(N.right); + } + // Find node with start; allows adding AnnoData to node.startSet + protected Node findStartNode(Node node, int start) { + if (node==null) return null; + + if (start < node.start) return findStartNode(node.left, start); + else if (start>node.start) return findStartNode(node.right, start); + else return node; + } + + // this can only be done when the tree is complete as it expects init maxEnd=end + protected int iAssignMaxEnd(Node tmpNode) { + int maxL = (tmpNode.left!=null) ? iAssignMaxEnd(tmpNode.left) : 0; + int maxR = (tmpNode.right!=null) ? iAssignMaxEnd(tmpNode.right) : 0; + if (tmpNode.maxEnd < maxL) tmpNode.maxEnd = maxL; + if (tmpNode.maxEnd < maxR) tmpNode.maxEnd = maxR; + return tmpNode.maxEnd; + } + protected void clear(Node tmpNode) { + if (tmpNode == null) return; + clear(tmpNode.left); + clear(tmpNode.right); + tmpNode.clear(); + } + + /** Access tree methods *******************************************************/ + + // Search for overlap or contained; uses maxEnd + protected TreeSet findOverlapSet(int start, int end, boolean checkAll) { + TreeSet set = new TreeSet (); + findOverlap(root, start, end, set, checkAll); + return set; + } + private void findOverlap(Node tmpNode, int hstart, int hend, TreeSet annoSet, boolean checkAll) { + if (tmpNode == null) return; + + if ( !(tmpNode.start > hend || tmpNode.end < hstart) ) { + annoSet.add(tmpNode.itvObj); + if (checkAll && tmpNode.startSet!=null) + for (Gene ad : tmpNode.startSet) { + if ( !(ad.gStart > hend || ad.gEnd < hstart) ) + annoSet.add(ad); + } + } + + if (tmpNode.left != null && tmpNode.left.maxEnd >= hstart) + this.findOverlap(tmpNode.left, hstart, hend, annoSet, checkAll); + + this.findOverlap(tmpNode.right, hstart, hend, annoSet, checkAll); + } + + protected void tree2array(Node tmpNode, Vector inorder){ + if (tmpNode == null) return; + + tree2array(tmpNode.left, inorder); + + inorder.add(tmpNode.itvObj); + if (tmpNode.startSet!=null) { + for (Gene gn : tmpNode.startSet) { + inorder.add(gn); + } + } + + tree2array(tmpNode.right, inorder); + } + + // Print + private boolean bPrtTree=false; + private int cntNode=0, cntLevel=0; + protected void printTree() { + prt(""PrintTree ""); + printTree(root, 0, ""C""); + prt(""#Node "" + cntNode + "" level "" + cntLevel); + } + private void printTree(Node root, int level, String d ){ + if (root == null) return; + + if (level>cntLevel) cntLevel=level; + cntNode++; + + printTree(root.left, level+1, ""L""); + if (bPrtTree) { + String sp="" ""; + for (int i=0; i { + private static final int T=Arg.T, Q=Arg.Q; + + // Gene input; set at start + protected int ix=0; + protected int gStart, gEnd, gLen; + protected int geneIdx=0; + protected String chr=""""; + protected String strand="""", geneTag=""""; // geneTag, e.g. 136. or 136.b + protected ArrayList exonList = new ArrayList (); + protected int exonSumLen=0; + + protected boolean isOlapGene=false; + + // read mummer finds overlaps and assign to gene for chr-chr; Pair-specific - clone only + protected ArrayList gHitList = new ArrayList (); // some will be filtered, or used in two diff clHits + protected ArrayList gHprList = new ArrayList (); + + private int hitsStart=Integer.MAX_VALUE, hitsEnd=0; // trace + + protected Gene(int ix, int geneIdx, String chr, int gstart, int gend, String strand, String geneTag) { + this.ix=ix; // 0 is target, 1 is query + this.geneIdx = geneIdx; // eventually saved with HitPair + this.chr = chr; // trace + this.gStart = gstart; // for calculations + this.gEnd = gend; // for calculations + this.strand = strand; // used to insure strands are consistent with hit + this.geneTag = geneTag.trim(); // trace; up to '(' + isOlapGene = !this.geneTag.endsWith("".""); + + gLen = (gend-gstart)+1; + } + protected void addExon(int estart, int eend) { + Exon ex = new Exon(estart, eend); + exonList.add(ex); + exonSumLen += (eend-estart)+1; + } + + // All genes objects used from GrpPair.addGene are copies so they are chrT-chrQ specific + private Gene() {} + public Object copy() { + Gene gn = new Gene(); + gn.ix = ix; + gn.geneIdx = geneIdx; + gn.chr = chr; + gn.gStart = gStart; + gn.gEnd = gEnd; + gn.strand = strand; + gn.geneTag = geneTag.trim(); + gn.gLen = gLen; + + for (Exon ex : exonList) gn.exonList.add(ex); + gn.exonSumLen = exonSumLen; + + gn.isOlapGene = isOlapGene; + + return gn; + } + + ////////////////////////////////////////////////// + protected int addHit(Hit ht) throws Exception { // AnchorMain2.runReadMummer + try { + hitsStart = Math.min(ht.hStart[ix], hitsStart); + hitsEnd = Math.max(ht.hEnd[ix], hitsEnd); + gHitList.add(ht); + + int allOlap=0; + for (int i=0; i mergeSet) throws Exception { + double [] scores = {-1,-1, -1, -1}; + try { + int nExons = exonList.size(); + int exonCov=0; + double exonFrac=0; + + for (int i=0; i0 && nExons>0) ? (exonFrac*100.0/(double)nExons) : 0.0; + scores[1] = (exonCov>0 && exonSumLen>0) ? (((double) exonCov/ (double) exonSumLen) * 100.0) : 0.0; + scores[2] = (geneCov>0 && gLen>0) ? ((double) geneCov/ (double) gLen) * 100.0 : 0.0; + scores[3] = exonCov; + return scores; + } + catch (Exception e) {ErrorReport.print(e, ""Score exons""); throw e;} + } + + // No paired Y gene and bin=0; will be sorted by Y in calling routine + protected ArrayList getHitsForXgene(int X, int Y, boolean isEQ) throws Exception { // GrpPairGx.runG1 + try { + if (X!=ix) symap.Globals.dtprt(""anchor2.Gene Wrong T/Q ""); + if (gHitList.size()==0) return null; + + ArrayList binList = new ArrayList (); + for (Hit ht : gHitList) { + if (ht.bin==0 && ht.isStEQ==isEQ && !ht.bBothGene()) { + if (X==Q && ht.bHasQgene(this)) binList.add(ht); + else if (X==T && ht.bHasTgene(this)) binList.add(ht); + else symap.Globals.dtprt(geneTag + "" has hit that does not have supposed genes""); + } + } + return binList; + } + catch (Exception e) {ErrorReport.print(e, ""Find remaining hits""); return null;} + } + + ///////////////////////////////////////////////// + public int compareTo(Gene gn) { + if (this.gStartgn.gStart) return 1; + else if (this.gEnd>gn.gEnd) return -1; + else if (this.gEnd() { + public int compare(Exon g1, Exon g2) { + if (g1.estart < g2.estart) return -1; + else if (g1.estart > g2.estart) return 1; + else if (g1.eend > g2.eend) return -1; + else if (g1.eend < g2.eend) return 1; // for violates its general contract! + else return 0; + } + } + ); + } + + /******* prtToFile on -tt ***************/ + protected String toResults() { + if (gHitList.size()==0) return """"; + + int iy = (ix==Arg.T) ? Arg.Q : Arg.T; + Hit.sortBySignByX(iy, gHitList); + + String hits=""""; + Hit last=null; + for (Hit ht : gHitList) { + int be = ht.getExonCov(ix, this); + String e = (be>0) ? "" E "" : "" I ""; + hits += e + ht.toDiff(last) + ""\n""; + last = ht; + } + hits = ""\n"" + hits; + + String hprList= "" HPR:"" + gHprList.size(); // may be clear from prtToFile (unless not crossRefClear run) + for (HitPair hpr : gHprList) hprList += ""\n"" + hpr.toResultsGene() + "" "" + hpr.note; + + return toBrief() + hprList + hits + ""\n""; + } + protected String toBrief() { + String gCoords = String.format(""Gene [%s%,d-%,d %5s] #Ex%d "",strand, gStart, gEnd, Arg.int2Str(gEnd-gStart+1), exonList.size()); + String hCoords = (gHitList.size()>0) ? + String.format(""Hits [%,d-%,d %5s] #Ht%d "", hitsStart,hitsEnd, Arg.int2Str(hitsEnd-hitsStart+1), gHitList.size()) + : "" No hits ""; + return toName() + gCoords + hCoords; + } + protected String toName() {return Arg.side[ix]+ ""#"" + geneTag + "" ("" + geneIdx + "") "" + chr + "" "";} + public String toString() {return toResults();} + + public void clear() { + gHitList.clear(); + exonList.clear(); + gHprList.clear(); + + hitsStart=Integer.MAX_VALUE; + hitsEnd=0; + } + ////////////////////////////////////////////////////////////////// + protected class Exon { + protected Exon(int h1, int h2) {this.estart=h1; this.eend=h2;} + protected int estart, eend; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor2/AnchorMain2.java",".java","18980","509","package backend.anchor2; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.PrintWriter; +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.TreeSet; + +import backend.AnchorMain; +import backend.Constants; +import backend.Utils; +import database.DBconn2; +import symap.manager.Mpair; +import symap.manager.Mproject; +import symap.Globals; +import util.Cancelled; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; + +/******************************************************* + * -Reads and process one MUMmer file at a time, so it is important that no chromosome gets split over multiple files!!! + * -For each chr-chr pair, creates a GrpPair object which performs on processing and DB saves + * each GrpPair has genes and hits for the pair; a gene can be in multiple GrpPairs, but a hit will only be in one + * + * -tt outputs files of results and extended results to terminal + * I tried to add self-synteny, but it almost always did worse and was entering some hits twice... + */ +public class AnchorMain2 { + private static final int T=Arg.T, Q=Arg.Q; + protected static boolean bTrace = Globals.TRACE; + + private AnchorMain mainObj=null; + + // accessed from GrpPair + protected DBconn2 tdbc2; + protected ProgressDialog plog; + protected Mpair mPair; + protected Mproject mProj1, mProj2; + protected int topN=0; + + protected long cntRawHits=0; // for logged output + protected int cntG2=0, cntG1=0, cntG0=0, cntClusters=0; // GrpPair.saveClusterHits + protected int cntG2Fil=0, cntG1Fil=0, cntG0Fil=0, cntPileFil=0; // GrpPair.createClusters + protected int cntWS=0, cntRmEnd=0, cntRmLow=0; // GrpPair.GrpPairGx + + protected PrintWriter fhOutHit=null, fhOutCl=null, fhOutGene=null, fhOutPile=null; + protected PrintWriter [] fhOutHPR = {null,null,null}; + protected String fileName="""", argParams=""""; + + // Main data structures; all genes; the ChrT-ChrQ genes with hits are transferred to GrpPair. + private TreeMap qGrpGeneMap = new TreeMap (); // key grpIdxQ; Mproj1 + private TreeMap tGrpGeneMap = new TreeMap (); // key grpIdxT; Mproj2 + private TreeSet donePair = new TreeSet (); // key grpIdx2+""-""+grpIdx1; ensure that chr-pair not in mult files + + protected String proj1Name, proj2Name; + private boolean bSuccess=true; + private int [] avgGeneLen = {0,0}, avgIntronLen = {0,0}, avgExonLen = {0,0}; // T,Q: + private double [] percentCov = {0,0}; + + // created and processed per file + private TreeMap grpPairMap = new TreeMap (); // key chrT-chrQ + + /*********************************/ + public AnchorMain2(AnchorMain mainObj) { + Arg.setVB(); + + this.mainObj = mainObj; + this.plog = mainObj.plog; + this.mPair = mainObj.mp; + + Arg.topN = mPair.getTopN(Mpair.FILE); + + double exon = mPair.getExonScale(Mpair.FILE); + double gene = mPair.getGeneScale(Mpair.FILE); + double g0 = mPair.getG0Scale(Mpair.FILE); + double len = mPair.getLenScale(Mpair.FILE); + argParams += Arg.setFromParams(exon, gene, g0, len); + + Arg.pEE = mPair.isEEpile(Mpair.FILE); + Arg.pEI = mPair.isEIpile(Mpair.FILE); + Arg.pEn = mPair.isEnpile(Mpair.FILE); + Arg.pII = mPair.isIIpile(Mpair.FILE); + Arg.pIn = mPair.isInpile(Mpair.FILE); + + tdbc2 = new DBconn2(""Anchors-""+DBconn2.getNumConn(), mainObj.dbc2); + } + /*********************************/ + public boolean run(Mproject pj1, Mproject pj2, File dh) throws Exception { + try { + this.mProj1=pj1; this.mProj2=pj2; // query, target + proj1Name=mProj1.getDisplayName(); + proj2Name=mProj2.getDisplayName(); + long totTime = Utils.getTime(); + + // read anno: create master copies for genes in a TreeMap per chr + if (Arg.VB) Utils.prtIndentMsgFile(plog, 1, ""Load genes for Algo2""); else Globals.rprt(""Load genes for Algo2""); + loadAnno(T, mProj2, tGrpGeneMap); if (!bSuccess) return false; + loadAnno(Q, mProj1, qGrpGeneMap); if (!bSuccess) return false; + argParams += Arg.setLenFromGenes(avgIntronLen, avgGeneLen, percentCov); + + prtFileOpen(); + + // for each file: read file, build clusters, save results to db + int nfile = processFiles(dh); if (!bSuccess) return false; + + // finish + prtFileClose(); + clearTree(); + + Globals.rclear(); + Utils.prtIndentMsgFile(plog, 1, String.format(""Final totals Raw hits %,d Files %,d"", cntRawHits, nfile)); + + String msg1 = String.format(""Clusters Both genes %,9d One gene %,9d No gene %,9d"", cntG2, cntG1, cntG0); + Utils.prtNumMsgFile(plog, cntClusters, msg1); + + int total = cntG2Fil+cntG1Fil+cntG0Fil; + String msg2 = String.format(""Filtered Both genes %,9d One gene %,9d No gene %,9d Pile hits %,d"", + cntG2Fil, cntG1Fil, cntG0Fil, cntPileFil); + Utils.prtNumMsgFile(plog, total, msg2); + if (Arg.WRONG_STRAND_PRT) Utils.prtNumMsgFile(plog, cntWS, ""Wrong strand""); + + if (bTrace) Globals.prt(String.format(""Wrong strand %,d Rm End %,d Rm Low %,d"", cntWS, cntRmEnd, cntRmLow)); + if (Arg.TRACE) Utils.prtTimeMemUsage(plog, "" Finish "", totTime); // also writes in AnchorMain after a few more comps + + return bSuccess; + } + catch (Exception e) {ErrorReport.print(e, ""create clustered hits""); return false;} + } + + /************************************************************************** + // Step1: All anno read at once, but loaded in separate GeneTrees per group (chr) + * Average and median stats computed for Arg settings + ************************************************************************/ + private void loadAnno(int X, Mproject mProj, TreeMap grpGeneMap) { + if (!mProj.hasGenes()) return; + + try { + // Genes + HashMap geneMap = new HashMap (); + + // get all groups for project + TreeMap grpIdxNameMap = mProj.getGrpIdxMap(); + String gx = null; + for (int idx : grpIdxNameMap.keySet()) { + if (gx==null) gx = idx+""""; + else gx += "","" + idx; + } + // query for the all groups genes + ResultSet rs = tdbc2.executeQuery( + ""SELECT idx, grp_idx, start, end, strand, tag FROM pseudo_annot "" + + "" where type='gene' and grp_idx in ("" + gx + "") order by idx"" ); + + while (rs.next()){ + int geneIdx = rs.getInt(1); + int grpIdx = rs.getInt(2); + int s = rs.getInt(3); + int e = rs.getInt(4); + String strand = rs.getString(5); + String tag = rs.getString(6); + tag = tag.substring(0, tag.indexOf(""("")); + + Gene geneObj = new Gene(X, geneIdx, grpIdxNameMap.get(grpIdx), s, e, strand, tag); + geneMap.put(geneIdx, geneObj); + + // Create new geneMap for this chromosome if needed + if (!grpGeneMap.containsKey(grpIdx)) { + if (!grpIdxNameMap.containsKey(grpIdx)) die(""No groupIdx "" + grpIdx); + + String title = Arg.side[X] + "" "" + grpIdxNameMap.get(grpIdx) + "" ("" + grpIdx + "")""; + grpGeneMap.put(grpIdx, new GeneTree(title)); + } + // add to tree for this chromosome + GeneTree treeObj = grpGeneMap.get(grpIdx); + treeObj.addGene(s, geneObj); + } + rs.close(); + + if (geneMap.size()==0) { + plog.msg(mProj.getDisplayName() + "" - no genes""); + return; + } + if (failCheck()) return; + + // for avg values + int nGene = geneMap.size(), nExon=0, nIntron=0; + int minGene=Integer.MAX_VALUE, minExon=Integer.MAX_VALUE, minIntron=Integer.MAX_VALUE; + int maxGene=0, maxExon=0, maxIntron=0; + long sumGene=0, sumExon=0, sumIntron=0; + int lastGeneIdx=0, lastExonEnd=0; + + // Exons - query for all exons + rs = tdbc2.executeQuery(""SELECT gene_idx, start, end FROM pseudo_annot "" + + "" where type='exon' and grp_idx in ("" + gx + "") order by grp_idx, gene_idx, start""); + + while (rs.next()){ + int geneIdx = rs.getInt(1); + if (geneIdx==0) continue; // happened in Mus13 + if (!geneMap.containsKey(geneIdx)) die(""No geneMap for "" + geneIdx + "" grpIdx "" + gx); + + int start = rs.getInt(2); + int end = rs.getInt(3); + + Gene geneObj = geneMap.get(geneIdx); + geneObj.addExon(start, end); + + // exon and intron stats + int len = end-start+1; + sumExon += len; + if (len>maxExon) maxExon = len; + if (len0) { + sumIntron += len; + if (len>maxIntron) maxIntron = len; + if (lenmaxGene) maxGene = gn.gLen; + } + } + avgGeneLen[X] = (int) Math.round((double)sumGene/(double)nGene); + avgExonLen[X] = (int) Math.round((double)sumExon/(double)nExon); + avgIntronLen[X] = (int) Math.round((double)sumIntron/(double)nIntron); + percentCov[X] = ((double)sumExon/(double)(sumGene))*100.0; + + if (Arg.VB) { + String msg = String.format(""%-10s [Avg Min Max] [Gene %5s %3s %5s] [Intron %5s %3s %5s] [Exon %5s %3s %5s] Cov %4.1f%s"", + mProj.getDisplayName(), + Utilities.kText(avgGeneLen[X]), Utilities.kText(minGene), Utilities.kText(maxGene), + Utilities.kText(avgIntronLen[X]), Utilities.kText(minIntron), Utilities.kText(maxIntron), + Utilities.kText(avgExonLen[X]), Utilities.kText(minExon), Utilities.kText(maxExon), percentCov[X], ""%""); + Utils.prtIndentMsgFile(plog, 2, msg); + } + else { + String msg = String.format(""%-10s [Avg Gene %5s Intron %5s Exon %5s] Cov %4.1f%s"", + mProj.getDisplayName(), Utilities.kText(avgGeneLen[X]), + Utilities.kText(avgIntronLen[X]), Utilities.kText(avgExonLen[X]), percentCov[X], ""%""); + Globals.rprt(msg); + } + } + catch (Exception e) {ErrorReport.print(e, ""load anno "" + Arg.side[X]); bSuccess=false;} + } + + /****************************************************** + * Step 2: Each file is read and immediately processed and save + */ + private int processFiles(File dh) { + try { + int nfile=0; + File[] fs = dh.listFiles(); + Arrays.sort(fs); + for (File f : fs) { + if (!f.isFile() || f.isHidden()) continue; // macOS add ._ files in tar; CAS576 add isHidden + fileName = f.getName(); + if (!fileName.endsWith(Constants.mumSuffix))continue; + nfile++; + long time = Utils.getTime(); + + // load hits into grpPairs + readMummer(f); + + // process all group pairs from file + for (GrpPair gp : grpPairMap.values()) { + bSuccess = gp.buildClusters(); if (!bSuccess) return nfile; + } + + if (failCheck()) return nfile; + + clearFileSpecific(); + + if (Arg.TRACE) Utils.prtTimeMemUsage(plog, "" Finish "", time); + } + return nfile; + } + catch (Exception e) {ErrorReport.print(e, ""analyze and save""); bSuccess=false; return 0;} + } + /********************************************************************* + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 + // [tS1] [tE1] [qS2] [qE2] [tLEN] [qLEN] [% IDY] [% SIM] [% STP] [tChrLEN] [qChrLEN] [FRM] [TAGS] + // 15491 15814 20452060 20451737 324 324 61.11 78.70 1.39 73840631 37257345 2 -3 chr1 chr3 + ************************************************************************/ + private void readMummer(File fObj) { + try { + int hitNum=0, hitEQ=0, hitNE=0, cntLongHit=0; + int [] cntHitGene = {0,0}; + String line; + GrpPair pairObj; + int cntErr=0, cntHits=0, cntNoChr=0; + TreeSet noChrSetQ = new TreeSet (); + TreeSet noChrSetT = new TreeSet (); + + BufferedReader reader = new BufferedReader ( new FileReader ( fObj ) ); + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.equals("""") || !Character.isDigit(line.charAt(0))) continue; + + cntHits++; + String[] tok = line.split(""\\s+""); + if (tok.length<13) { + plog.msg(""*** Missing values, only "" + tok.length + "" must be >=13 ""); + plog.msg("" Line: "" + line); + plog.msg("" Line "" + cntHits + "" of file "" + fObj.getAbsolutePath()); + cntErr++; + if (cntErr>5) Globals.die(""Too many errors in "" + fObj.getAbsolutePath()); + continue; + } + int poffset = (tok.length > 13 ? 2 : 0); // nucmer vs. promer + + int [] start = {Integer.parseInt(tok[0]), Integer.parseInt(tok[2])}; + int [] end = {Integer.parseInt(tok[1]), Integer.parseInt(tok[3])}; + int [] len = {Integer.parseInt(tok[4]), Integer.parseInt(tok[5])}; + int id = (int) Math.round(Double.parseDouble(tok[6])); + int sim = (poffset==0) ? 0 : (int) Math.round(Double.parseDouble(tok[7])); + + int [] f = {0, 0}; // frame; in Hit but not used + if (poffset==2) { + f[T] = Integer.parseInt(tok[11]); + f[Q] = Integer.parseInt(tok[12]); + } + String [] chr = {"""",""""}; + chr[T] = tok[11+poffset]; + chr[Q] = tok[12+poffset]; + + // Get grpIdx using name + int [] grpIdx = {0,0}; + grpIdx[Q] = mProj1.getGrpIdxFromFullName(chr[Q]); // proj1 is Q, 2nd set of coords (Q==1, T==0) + if (grpIdx[Q]==-1) { + if (!noChrSetQ.contains(chr[Q])) noChrSetQ.add(chr[Q]); + cntNoChr++; continue; + } + grpIdx[T] = mProj2.getGrpIdxFromFullName(chr[T]); + if (grpIdx[T]==-1) { + if (!noChrSetT.contains(chr[T])) noChrSetQ.add(chr[T]); + cntNoChr++; continue; + } + + String strand = (start[Q] <= end[Q] ? ""+"" : ""-"") + ""/"" + (start[T] <= end[T] ? ""+"" : ""-""); // copied from anchor1 + if (Arg.isEqual(strand)) hitEQ++; else hitNE++; + + if (start[T]>end[T]) {int t=start[T]; start[T]=end[T]; end[T]=t;} + if (start[Q]>end[Q]) {int t=start[Q]; start[Q]=end[Q]; end[Q]=t;} + + // Add hit to pairObj + String grp2grpkey=grpIdx[Q]+""-""+grpIdx[T]; + + if (!grpPairMap.containsKey(grp2grpkey)) { + if (donePair.contains(grp2grpkey)) die(chr[Q] + "" and "" + chr[T] + "" occurs in multiple files""); + donePair.add(grp2grpkey); + + pairObj = new GrpPair(this, grpIdx[T], proj2Name, chr[T], grpIdx[Q], proj1Name, chr[Q], plog); + grpPairMap.put(grp2grpkey, pairObj); + } + else pairObj = grpPairMap.get(grp2grpkey); + + // Create hit + hitNum++; + Hit ht = new Hit(hitNum, id, sim, start, end, len, grpIdx, strand, f); + pairObj.addHit(ht); + + // add hit to gene and vice versa; + if (qGrpGeneMap.size()>0 && qGrpGeneMap.containsKey(grpIdx[Q])) { // grp may have no genes + GeneTree qGrpGeneObj = qGrpGeneMap.get(grpIdx[Q]); + TreeSet qSet = qGrpGeneObj.findOlapSet(start[Q], end[Q], true); + + for (Gene gn : qSet) { + cntHitGene[Q]++; + pairObj.addGeneHit(Q, gn, ht); + } + } + if (tGrpGeneMap.size()>0 && tGrpGeneMap.containsKey(grpIdx[T])) { + GeneTree tGrpGeneObj = tGrpGeneMap.get(grpIdx[T]); + TreeSet tSet = tGrpGeneObj.findOlapSet(start[T], end[T], true); + + for (Gene gn : tSet) { + cntHitGene[T]++; + pairObj.addGeneHit(T, gn, ht); + } + } + if (len[T]>Arg.mamGeneLen || len[Q]>Arg.mamGeneLen) cntLongHit++; + } // finish reading file + reader.close(); + + /* ---------- Finish ----------- */ + Globals.rclear(); + String x = (cntLongHit>0) ? String.format(""Long Hits %,d"", cntLongHit) : """"; + String msg = String.format(""Load %s Hits %,d (EQ %,d NE %,d) %s"", fileName, hitNum, hitEQ, hitNE, x); + if (Arg.VB) Utils.prtIndentMsgFile(plog, 1, msg); else Globals.rprt(msg); + + cntRawHits += hitNum; + + if (cntNoChr>0) { + if (noChrSetQ.size()>0) { + msg = proj1Name + "" ("" + noChrSetQ.size() + ""): ""; + for (String c : noChrSetQ) msg += c + "" ""; + Utils.prtNumMsgFile(plog, cntNoChr, ""lines without loaded sequence: "" + msg); + } + if (noChrSetT.size()>0) { + msg = proj2Name + "" ("" + noChrSetT.size() + ""): ""; + for (String c : noChrSetT) msg += c + "" ""; + Utils.prtNumMsgFile(plog, cntNoChr, ""lines without loaded sequence: "" + msg); + } + } + + if (Arg.TRACE || bTrace) { + msg = String.format(""SubHit->genes %s %,d %s %,d"", proj2Name, cntHitGene[Arg.T], proj1Name, cntHitGene[Arg.Q]); + Utils.prtIndentMsgFile(plog, 2, msg); + } + } + catch (Exception e) {ErrorReport.print(e, ""read file""); bSuccess=false;} + } + + //////////////////////////////////////////////////////////////////////// + private void clearFileSpecific() { + for (GrpPair p : grpPairMap.values()) { + p.clear(); + p=null; + } + grpPairMap.clear(); + System.gc(); + } + private void clearTree() { + for (GeneTree gt : tGrpGeneMap.values()) gt.clear(); + for (GeneTree gt : qGrpGeneMap.values()) gt.clear(); + tGrpGeneMap.clear(); + qGrpGeneMap.clear(); + } + protected boolean failCheck() { + if (Cancelled.isCancelled() || mainObj.bInterrupt || !bSuccess) { + Globals.prt(""Cancelling operation""); + bSuccess=false; + return true; + } + return false; + } + ///////////////////////////////////////////////////////////////////////// + // the 1st 4 are written from GrpPair when done, the last set is written from GrpPairGx before Pile. + private void prtFileOpen() { + try { + if (Globals.INFO || Globals.TRACE) Utils.prtIndentMsgFile(plog, 0, argParams + ""\n""); + if (!Globals.TRACE) return; + + boolean doHit=true, doGenePair=true, doCluster=true, doGene=true, doPile=true; + + if (doPile) + fhOutPile = new PrintWriter(new FileOutputStream(""logs/zPiles.log"", false)); + if (doHit) + fhOutHit = new PrintWriter(new FileOutputStream(""logs/zHits.log"", false)); + if (doCluster) + fhOutCl = new PrintWriter(new FileOutputStream(""logs/zCluster.log"", false)); + if (doGene) + fhOutGene = new PrintWriter(new FileOutputStream(""logs/zGene.log"", false)); + if (doGenePair) { // before final clusters, written in GrpPairGx + fhOutHPR[2] = new PrintWriter(new FileOutputStream(""logs/zHprG2.log"", false)); + fhOutHPR[1] = new PrintWriter(new FileOutputStream(""logs/zHprG1.log"", false)); + fhOutHPR[0] = new PrintWriter(new FileOutputStream(""logs/zHprG0.log"", false)); + fhOutHPR[2].print(argParams); + fhOutHPR[1].print(argParams); + fhOutHPR[0].print(argParams); + } + } + catch (Exception e) {ErrorReport.print(e, ""save to file""); bSuccess=false;} + } + private void prtFileClose() { + try { + if (fhOutHit!=null) fhOutHit.close(); + if (fhOutCl!=null) fhOutCl.close(); + if (fhOutGene!=null) fhOutGene.close(); + if (fhOutPile!=null) fhOutPile.close(); + for (int i=0; i<2; i++) + if (fhOutHPR[i]!=null) fhOutHPR[i].close(); + } + catch (Exception e) {ErrorReport.print(e, ""file close""); bSuccess=false;} + } + public String toResults() { + String msg = """"; + for (GrpPair gp : grpPairMap.values()) msg += ""\n"" + gp.toResults(); + return ""!!!AnchorMain "" + msg + ""\n""; + } + public String toString() {return toResults();} + + private void die(String msg) {symap.Globals.die(""Load Hits: "" + msg);} +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/Merge.java",".java","5346","174","package backend.synteny; + +import java.util.TreeSet; +import java.util.Vector; +import java.util.HashSet; +import java.util.TreeMap; +import java.util.Stack; + +import util.ErrorReport; + +/****************************************************** + * Used for merge blocks + **********************************************************/ + +public class Merge { + protected final static int CONTAINED=1, OLAP=2, COSET=3; + private int action = 1; + private boolean bOrient; // User set variable; + protected int cntCoset=0, cntSkip=0; + + private Vector blockVec; // input all blocks, return merge blocks + + private int gap1, gap2, mindots, fullGap2; + + private Graph graph; + + protected Merge( int action, Vector blockVec, boolean bOrient, int mindots, int fullGap2) { + this.action = action; + this.blockVec = blockVec; + this.bOrient = bOrient; + this.mindots = mindots; + this.fullGap2 = fullGap2; + + for (SyBlock blk : blockVec) blk.hasChg=false; + } + /*************************************************** + * Merge blocks; Contained - gap isn't used; Overlap - gap is 0; Close - gap is >0 + */ + protected Vector mergeBlocks(int gap1, int gap2) { + this.gap1 = gap1; this.gap2 = gap2; + + int loop=0; + int prevSz = blockVec.size() + 1; + while (prevSz > blockVec.size()){ + prevSz = blockVec.size(); + blockVec = mergeBlocksSingleFixed(loop++); + } + return blockVec; + } + + private Vector mergeBlocksSingleFixed(int loop) { + try { + if (blockVec.size() <= 1) return blockVec; + graph = new Graph(blockVec.size()); + + for (int i = 0; i < blockVec.size(); i++) { + SyBlock bA = blockVec.get(i); + + for (int j = i + 1; j < blockVec.size(); j++){ + SyBlock bZ = blockVec.get(j); + + if (bOrient && !bA.orient.equals(bZ.orient)) continue; + + if (action!=COSET && (bA.nHits < mindots && bZ.nHits < mindots)) continue; // Strict merges cosets + + if (action==CONTAINED) { // only merge if contained on both sides + if (isContained(bA.mS1,bA.mE1,bZ.mS1,bZ.mE1) && + isContained(bA.mS2,bA.mE2,bZ.mS2,bZ.mE2)) + { + boolean isGood = true; + if (bA.nHitsmindots + isGood = (bA.nHits=OLAP) { // gap=0 for overlap only, or >0 for close or overlap + if (action!=COSET && (bA.nHits0) + private boolean isOverlap(int s1,int e1, int s2, int e2, int max_gap) { + int gap = Math.max(s1,s2) - Math.min(e1,e2); + return (gap <= max_gap); + } + // always run + private boolean isContained(int s1,int e1, int s2, int e2){ + return ((s1 >= s2 && e1 <= e2) || (s2 >= s1 && e2 <= e1)); + } + /*************************************************************** + // Implements a directed graph and transitive closure algorithm + // This does not look at blk.n, and can merge a big n into a very small n + **************************************************************/ + private Vector mergeGraph() { + HashSet> blockSets = graph.transitiveClosure(); + Vector mergedBlocks = new Vector(); + + for (TreeSet s : blockSets) { + SyBlock bnew = null; + for (Integer i : s) { + if (bnew == null) + bnew = blockVec.get(i); + else { + bnew.mergeWith(blockVec.get(i)); + } + } + mergedBlocks.add(bnew); + } + return mergedBlocks; + } + /**************************************************************************/ + private class Graph { + private int mN; + private TreeMap> mNodes; + + private Graph(int nnodes) { + mN = nnodes; + mNodes = new TreeMap>(); + for (int i = 0; i < mN; i++) { + mNodes.put(i, new TreeSet()); + } + } + protected void addNode(int i, int j){ + mNodes.get(i).add(j); + mNodes.get(j).add(i); + } + + // Simple transitive closure using stack and marked nodes. + protected HashSet> transitiveClosure(){ + HashSet> retSets = new HashSet>(); + + TreeSet usedNodes = new TreeSet(); + Stack curNodes = new Stack(); + TreeSet curSet = new TreeSet(); + + for (Integer i : mNodes.keySet()) { + if (usedNodes.contains(i)) continue; + + assert(curNodes.empty()); + curNodes.push(i); + + while(!curNodes.empty()) { + int j = curNodes.pop(); + + for (int k : mNodes.get(j)) { + if (usedNodes.contains(k)) continue; + usedNodes.add(k); + curNodes.push(k); + } + curSet.add(j); + } + retSets.add(curSet); + curSet = new TreeSet(); + } + return retSets; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/RWdb.java",".java","7200","193","package backend.synteny; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Vector; + +import database.DBconn2; +import symap.Globals; +import util.ErrorReport; + +/********************************************************* + * This contains the major read/write DB methods + */ +public class RWdb { + private final String orientSame = SyntenyMain.orientSame; + private final String orientDiff = SyntenyMain.orientDiff; + + private DBconn2 tdbc2; + private int mPairIdx, mProj1Idx, mProj2Idx; + + protected RWdb (int mPairIdx, int mProj1Idx, int mProj2Idx, DBconn2 tdbc2) { + this.mPairIdx = mPairIdx; + this.mProj1Idx = mProj1Idx; + this.mProj2Idx = mProj2Idx; + this.tdbc2 = tdbc2; + } + /***************************************************** + * Load hits for chromosome pair + * ***************************************************/ + protected Vector loadHitsForGrpPair(int grpIdx1, int grpIdx2, String orient) { + try { + Vector hits = new Vector(); + + String st = ""SELECT h.idx, h.hitnum, h.start1, h.end1, h.start2, h.end2, h.pctid, h.runnum, h.gene_overlap"" + + "" FROM pseudo_hits as h "" + + "" WHERE h.proj1_idx="" + mProj1Idx + "" AND h.proj2_idx="" + mProj2Idx + + "" AND h.grp1_idx="" + grpIdx1 + "" AND h.grp2_idx="" + grpIdx2 ; + + if (orient.equals(orientSame)) st += "" AND (h.strand = '+/+' or h.strand = '-/-')""; + else if (orient.equals(orientDiff)) st += "" AND (h.strand = '+/-' or h.strand = '-/+')""; + + if (grpIdx1==grpIdx2) st += "" AND h.start1 > h.start2 ""; // DIR_SELF (old <) these have refIdx=0; refIdx>0 is used to mirror blocks + + ResultSet rs = tdbc2.executeQuery(st); + while (rs.next()) { + int i=1; + int id = rs.getInt(i++); + int hitnum = rs.getInt(i++); + int start1 = rs.getInt(i++); + int end1 = rs.getInt(i++); + + int start2 = rs.getInt(i++); + int end2 = rs.getInt(i++); + int pctid = rs.getInt(i++); + int runnum = rs.getInt(i++); + int genes = rs.getInt(i++); + + hits.add(new SyHit(start1, end1, start2, end2,id, pctid, runnum, hitnum, genes)); + } + rs.close(); + + return hits; + } + catch (Exception e) {ErrorReport.print(e, ""Write results to DB""); return null;} + } + + /************************************************************* + * Save blocks to DB + * if bSwap is true, enter the synmetric block fo self-synteny + *************************************************************/ + protected void saveBlocksToDB(Vector blocks, boolean bMirror) { + try { + if (blocks.size()==0) return; + + if (!tdbc2.tableColumnExists(""blocks"", ""avgGap1"")) {// this is not a Version update; it is only for report; + Globals.prt(""Updating the database schema for the block table""); + tdbc2.tableCheckAddColumn(""blocks"", ""avgGap1"", ""integer default 0"", null); + tdbc2.tableCheckAddColumn(""blocks"", ""avgGap2"", ""integer default 0"", null); + } + + // Create blocks + String sql= ""insert into blocks (pair_idx, blocknum,""; + if (!bMirror) sql += ""proj1_idx, grp1_idx, start1, end1, proj2_idx, grp2_idx, start2, end2, avgGap1, avgGap2, ""; + else sql += ""proj2_idx, grp2_idx, start2, end2, proj1_idx, grp1_idx, start1, end1, avgGap2, avgGap1, ""; + + sql += ""score, corr, comment, ngene1, ngene2, genef1, genef2) "" + + ""values (?,?, ?,?,?,?, ?,?,?,?, ?,?, ?,?,?, 0, 0, 0.0, 0.0)""; + + PreparedStatement ps = tdbc2.prepareStatement(sql); + + for (SyBlock b : blocks) { + int i=1; + ps.setInt(i++, mPairIdx); + ps.setInt(i++, b.mBlkNum); + + ps.setInt(i++, mProj1Idx); + ps.setInt(i++, b.mGrpIdx1); + ps.setInt(i++, b.mS1); + ps.setInt(i++, b.mE1); + + ps.setInt(i++, mProj2Idx); + ps.setInt(i++, b.mGrpIdx2); + ps.setInt(i++, b.mS2); + ps.setInt(i++, b.mE2); + + if (bMirror) {ps.setInt(i++, 0);ps.setInt(i++, 0);} // avgGap=0 indicates mirrored; used in Report + else { + ps.setInt(i++, (int) b.avgGap1); + ps.setInt(i++, (int) b.avgGap2); + } + + ps.setInt(i++, b.nHits); + ps.setFloat(i++, b.mCorr1); + ps.setString(i++, (""Avg %ID:"" + b.avgPctID())); // tinytext (256char) + + ps.executeUpdate(); + } + ps.close(); + + // Create pseudo_block_hits; first, get block idx (if bSwap, swapped above so can use start1...) + for (SyBlock b : blocks) { + String st = ""SELECT idx FROM blocks WHERE pair_idx="" + mPairIdx + + "" AND blocknum="" + b.mBlkNum + + "" AND proj1_idx="" + mProj1Idx + "" AND grp1_idx="" + b.mGrpIdx1 + + "" AND proj2_idx="" + mProj2Idx + "" AND grp2_idx="" + b.mGrpIdx2 + + "" AND start1="" + b.mS1 + "" AND end1="" + b.mE1 + + "" AND start2="" + b.mS2 + "" AND end2="" + b.mE2; + b.mIdx = tdbc2.executeInteger(st); + if (b.mIdx==-1) ErrorReport.die(""SyMAP error, cannot get block idx \n"" + st); + } + + if (bMirror) { // blocks were created with hits with refidx=0, update reverse hits with refidx>0 + for (SyBlock b : blocks) { + for (SyHit ht : b.hitVec) { // find + if (ht.mIdx>0) { + int s = ht.mIdx; + ht.mIdx = tdbc2.executeInteger(""select idx from pseudo_hits where refidx="" + ht.mIdx); + if (ht.mIdx<=0 && SyntenyMain.bTrace) + Globals.prt(String.format(""%6d no refidx: %s "", s, ht)); + } + } + } + } + PreparedStatement ps2 = tdbc2.prepareStatement( + ""insert into pseudo_block_hits (hit_idx, block_idx) values (?,?)""); + for (SyBlock bk : blocks) { + for (SyHit ht : bk.hitVec) { + if (ht.mIdx>0) { + ps2.setInt(1, ht.mIdx); + ps2.setInt(2, bk.mIdx); + ps2.executeUpdate(); + } + } + } + ps2.close(); + + /** compute final block fields **/ + if (bMirror) return; // do not need for mirrored + + // count genes1 with start1 and end2 of block + tdbc2.executeUpdate(""update blocks set "" + + ""ngene1 = (select count(*) from pseudo_annot as pa "" + + ""where pa.grp_idx=grp1_idx and greatest(pa.start,start1) < least(pa.end,end1) "" + + "" and pa.type='gene') where pair_idx="" + mPairIdx); + + tdbc2.executeUpdate(""update blocks set "" + + ""ngene2 = (select count(*) from pseudo_annot as pa "" + + "" where pa.grp_idx=grp2_idx and greatest(pa.start,start2) < least(pa.end,end2) "" + + "" and pa.type='gene') where pair_idx="" + mPairIdx); + + // compute gene1 in grp1 that have hit, and divide by ngene1 + tdbc2.executeUpdate(""update blocks set "" + + ""genef1=(select count(distinct annot_idx) from "" + + "" pseudo_hits_annot as pha "" + + "" join pseudo_block_hits as pbh on pbh.hit_idx=pha.hit_idx "" + + "" join pseudo_annot as pa on pa.idx=pha.annot_idx "" + + "" where pbh.block_idx=blocks.idx and pa.grp_idx=blocks.grp1_idx)/ngene1 "" + + "" where ngene1 > 0 and pair_idx="" + mPairIdx); + + tdbc2.executeUpdate(""update blocks set "" + + ""genef2=(select count(distinct annot_idx) from "" + + "" pseudo_hits_annot as pha "" + + "" join pseudo_block_hits as pbh on pbh.hit_idx=pha.hit_idx "" + + "" join pseudo_annot as pa on pa.idx=pha.annot_idx "" + + "" where pbh.block_idx=blocks.idx and pa.grp_idx=blocks.grp2_idx)/ngene2 "" + + "" where ngene2 > 0 and pair_idx="" + mPairIdx); + + } catch (Exception e) {ErrorReport.die(e, ""Writing blocks to DB""); } + } + + /** CAS575 replace with above: symmetrizeBlocks() {} Self-synteny Add the mirror reflected blocks for self alignments **/ +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/SyntenyMain.java",".java","28742","774","package backend.synteny; + +import java.io.File; +import java.util.Vector; +import java.util.HashMap; +import java.util.Collections; + +import backend.Constants; +import backend.Utils; +import database.DBconn2; +import symap.Globals; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ErrorReport; +import util.ProgressDialog; +import util.Utilities; + +/************************************************** + * Computes synteny + * Strict: uses original algorithm but: + * uses stricter gaps and larger PCC (see setCutoffs) + * creates blocks with bOrient first, then remove hit-wires that cross may others + * makes blocks out of CoSets that are not in blocks (cosetBlocks), and tries to merge + * Merge has some special logic for Strict since CoSets can be merged + * Self: + */ +public class SyntenyMain { + public static boolean bTrace = false; // -bt trace; set at command line + protected static boolean bTraceBlks = bTrace; // local set + + private boolean bVerbose = Constants.VERBOSE; + + protected static final String orientSame = ""==""; // must be ++ or --; + protected static final String orientDiff = ""!=""; // must be +- or -+ + protected static final String orientMix = """"; // can be mixed + + private ProgressDialog mLog; + private DBconn2 dbc2, tdbc2; + private int mPairIdx; + + // Interface parameters saved + protected int pMindots=7; // the only user integer parameters + private boolean bStrict = false; + private boolean bOrient = false; // to conform to standard definition, must be same orientation + private String pMerge = ""0""; // 0 - always do contain; 1 - overlap; 2 - close (which is also overlap) + + private boolean bOrSt = false; // Orient || Strict + private boolean isSelf = false, bOrderAgainst=false; + + private Mproject mProj1, mProj2; + private Mpair mp; + private String resultDir; + + // Main data structure for a chr-chr pair + private Vector blockVec; // blocks chr-chr pair; recreated on each new chr-chr; + + // Cutoffs + final private int fMindots_keepbest = 3; // to be merged into one >= pMinDots + final private int fMingap = 1000; // minimum gap param considered in binary search + + private int mMindotsA, mMindotsB, mMindotsC, mMindotsD; // Set using pMinHits; used with isGoodCorr + private float mCorr1A=0.8f; // reduced for strict + private final float mCorr1B=0.98f, mCorr1C=0.96f, mCorr1D=0.94f; // For chain + private final float mCorr2A=0.7f, mCorr2B=0.9f, mCorr2C=0.8f, mCorr2D=0.7f; // For all hits in surrounding box + + private int mMaxgap1, mMaxgap2; // mProj1.getLength()/(Math.sqrt(nHits))); + private float mAvg1A, mAvg2A; // mMapgap/15 + private int ngaps; // Depends on genome length && number hits + private Vector gap1list = new Vector(); // Set the decreasing gap search points + private Vector gap2list = new Vector(); + + private final double fDiag = 0.4, fGeneDiag=0.8; // isSelf, aligns to close to diagonal; CAS576 + + // final stats + private boolean bSuccess = true; + private long startTime; + private int totalBlocks=0, cntMerge=0, cntSame=0, cntDiff=0; + private int cntGrpMerge=0, cntGrpSame=0, cntGrpDiff=0, cntSetNB=0, cntSetNBhits=0; // Verbose + private int cntTrIn=0, cntTrOlap=0, cntTrCoset=0, cntTrSkip=0, cntTrCsChg=0, cntTrRmDiag=0; // bTrace + + public SyntenyMain(DBconn2 dbc2, ProgressDialog log, Mpair mp) { + this.dbc2 = dbc2; + this.mLog = log; + this.mp = mp; + mPairIdx = mp.getPairIdx(); + mProj1 = mp.mProj1; + mProj2 = mp.mProj2; + + bStrict = mp.isStrict(Mpair.FILE); + bOrient = mp.isOrient(Mpair.FILE); + pMerge = mp.getMergeIndex(Mpair.FILE); + bOrSt = bOrient || bStrict; // Strict does orient but then mix merges, whereas bOrient does not mix merge + + bOrderAgainst = (mp.isOrder1(Mpair.FILE) || mp.isOrder2(Mpair.FILE)); + + isSelf = (mProj1.getIdx() == mProj2.getIdx()); + } + /******************************************************************/ + public boolean run(Mproject pj1, Mproject pj2) { + try { + /** Setup ***************************************/ + String proj1Name = mProj1.getDBName(), proj2Name = mProj2.getDBName(); + int mProj1Idx = mProj1.getIdx(), mProj2Idx = mProj2.getIdx(); + + startTime = Utils.getTime(); + if (proj1Name.equals(proj2Name)) mLog.msg(""Finding self-synteny for "" + proj1Name); + else mLog.msg(""Finding synteny for "" + proj1Name + "" and "" + proj2Name); + + resultDir = Constants.getNameResultsDir(proj1Name, proj2Name); + if (!(new File(resultDir)).exists()) { + mLog.msg(""Cannot find result directory "" + resultDir); + ErrorCount.inc(); + return false; + } + + tdbc2 = new DBconn2(""Synteny-"" + DBconn2.getNumConn(), dbc2); + tdbc2.executeUpdate(""DELETE FROM blocks WHERE pair_idx="" + mPairIdx); + RWdb rwObj = new RWdb(mPairIdx, mProj1Idx, mProj2Idx, tdbc2); + BuildBlock buildObj = new BuildBlock(rwObj); + FinishBlock finishObj = new FinishBlock(rwObj); + + setCutoffs(); // Set cutoffs for all grp-grp pairs + if (Cancelled.isCancelled() || !bSuccess) {tdbc2.close(); return false;} + + /** Main loop through chromosome pairs ***************************************/ + int nGrpGrp = mProj1.getGrpSize() * mProj2.getGrpSize(); + int maxGrp = nGrpGrp; + + if (bVerbose) Utils.prtNumMsg(mLog, nGrpGrp, ""group-x-group pairs to analyze""); + else Globals.rprt(""group-x-group pairs to analyze""); + String grpMsg = nGrpGrp + "" of "" + maxGrp; + + for (int grpIdx1 : mProj1.getGrpIdxMap().keySet()) { + for (int grpIdx2 : mProj2.getGrpIdxMap().keySet()) { + nGrpGrp--; + if (isSelf && grpIdx1) must match direction of loadHitsForGrpPair; mirror later + + SyBlock.cntBlk = 1; + cntGrpMerge=cntGrpSame=cntGrpDiff=cntTrRmDiag=0; + blockVec = new Vector(); // create for both orients so can be number sequentially + + if (!bOrSt) buildObj.doChrChrSynteny(grpIdx1,grpIdx2, orientMix, grpMsg); + else { // restrict to same orientation; + buildObj.doChrChrSynteny(grpIdx1,grpIdx2, orientSame, grpMsg); + buildObj.doChrChrSynteny(grpIdx1,grpIdx2, orientDiff, grpMsg); + } + if (Cancelled.isCancelled() || !bSuccess) {tdbc2.close();return false;} + + finishObj.doChrChrBlkFinish(grpIdx1,grpIdx2); // save to DB; need to be combined bOrient; + + cntSame += cntGrpSame; cntDiff += cntGrpDiff; cntMerge += cntGrpMerge; + if ((bTrace || bVerbose) && blockVec.size()>0) { + Globals.rclear(); + String msg = String.format(""Blocks %-12s"", mProj1.getGrpFullNameFromIdx(grpIdx1) + ""-"" + mProj2.getGrpFullNameFromIdx(grpIdx2)); + if (bOrSt) msg += String.format("" Orient: Same %3d Diff %3d "",cntGrpSame, cntGrpDiff); + if (!pMerge.equals(""0"") || bTrace) msg += String.format("" Merged %3d "", cntGrpMerge); + if (isSelf && cntTrRmDiag>0 && bTrace) msg += String.format("" Remove close to diagonal %3d "", cntTrRmDiag); + Utils.prtIndentNumMsgFile(mLog, 1, blockVec.size(), msg); + } + String t = Utilities.getDurationString(Utils.getTime()-startTime); + + grpMsg = "" ("" + nGrpGrp + "" of "" + maxGrp + "" pairs "" + t + "")""; + Globals.rprt(nGrpGrp + "" of "" + maxGrp + "" pairs remaining ("" + t + "")""); + blockVec.clear(); + } + } + Globals.rclear(); + + if (Cancelled.isCancelled() || !bSuccess) {tdbc2.close();return false;} + + // Final number for output to terminal and log + String msg = ""Blocks""; + if (!pMerge.equals(""0"")) msg += String.format("" %,d Merged "", cntMerge); + if (bOrient) msg += String.format("" Orient: %,d Same %,d Diff"", cntSame, cntDiff); + Utils.prtNumMsg(mLog, totalBlocks, msg); + + if (bVerbose) { + msg = String.format(""Collinear Sets not in blocks (%,d total hits)"", cntSetNBhits); + Utils.prtIndentNumMsgFile(mLog, 1, cntSetNB, msg); + } + if (bTrace) { + Utils.prtIndentMsgFile(mLog, 3, String.format(""Merge: In %,d Olap %,d"", cntTrIn, cntTrOlap)); + Utils.prtIndentMsgFile(mLog, 3, String.format(""Coset Blk %,d Skip %,d Add hits to existing blk %,d"", cntTrCoset, cntTrSkip, cntTrCsChg)); + } + Utils.prtMsgTimeDone(mLog, ""Finish Synteny"", startTime); + + /** Order *******************************************************/ + if (mp.isOrder1(Mpair.FILE)) { + OrderAgainst obj = new OrderAgainst(mp, mLog, tdbc2); + obj.orderGroupsV2(false); + } + else if (mp.isOrder2(Mpair.FILE)) { + OrderAgainst obj = new OrderAgainst(mp, mLog, tdbc2); + obj.orderGroupsV2(true); + } + if (Cancelled.isCancelled() || !bSuccess) {tdbc2.close(); return false;} + + /** Finish **********************************************************/ + tdbc2.close(); + return bSuccess; // Full time printed in calling routine + } + catch (Exception e) {ErrorReport.print(e, ""Computing Synteny""); return false; } + } + +// Pearson correlation coefficient (PCC) of midpoints; used for BuildBlock and for saving final to DB + private float hitCorrelation(Vector hits) { + if (hits.size() <= 2) return 0; + + double N = (float)hits.size(); + double xav = 0, xxav = 0, yav = 0, yyav = 0, xyav = 0; + + for (SyHit h : hits) { + double x = (double)h.midG1; + double y = (double)h.midG2; + xav += x; yav += y; + xxav += x*x; yyav += y*y; xyav += x*y; + } + xav /= N; yav /= N; + xxav /= N; yyav /= N; xyav /= N; + + double sdx = Math.sqrt(Math.abs(xxav - xav*xav)); + double sdy = Math.sqrt(Math.abs(yyav - yav*yav)); + double sdprod = sdx*sdy; + + double corr = (sdprod > 0) ? corr = ((xyav - xav*yav)/sdprod) : 0; + if (Math.abs(corr) > 1) corr = (corr > 0) ? 1.0 : -1.0; // cannot be <1 or >1 + + return (float)corr; + } + + /*************************************************************** + * All values are final + ****************************************************/ + private void setCutoffs() { + try { + pMindots = mp.getMinDots(Mpair.FILE); // default 7 + + mMindotsA = mMindotsB = pMindots; // default 7 + mMindotsC = 3*pMindots/2; // default 10 if pMindots=7 + mMindotsD = 2*pMindots; // default 14 if pMindots=7 + + int nHits = tdbc2.executeCount(""select count(*) as nhits from pseudo_hits "" + + "" where proj1_idx='"" + mProj1.getIdx() + ""' and proj2_idx='"" + mProj2.getIdx() + ""'"");; + if (bVerbose) Utils.prtNumMsg(mLog, nHits, ""Total hits""); + else Globals.rprt(String.format(""%,10d Total Hits"", nHits)); + + mMaxgap1 = (int)( ((double)mProj1.getLength())/(Math.sqrt(nHits))); // can be >3M, e.g. humans, don't limit + mMaxgap2 = (int)( ((double)mProj2.getLength())/(Math.sqrt(nHits))); + + mAvg1A = ((float)mMaxgap1)/15; + mAvg2A = ((float)mMaxgap2)/15; + + gap1list.add(mMaxgap1/2); + gap2list.add(mMaxgap2/2); + + int minGap=2*fMingap; // fMingap=1000 + ngaps = 1; + while (gap1list.get(ngaps-1) >= minGap && gap2list.get(ngaps-1) >= minGap){ + gap1list.add(gap1list.get(ngaps-1)/2); + gap2list.add(gap2list.get(ngaps-1)/2); + ngaps++; + } + if (bStrict) { + if (ngaps>2) { + gap1list.remove(0); + gap2list.remove(0); + ngaps--; + } + mCorr1A = 0.9f; + } + if (bTrace) { + Globals.prt(String.format(""A Hits %4d corr1 %6.3f corr2 %6.3f avg1 %,d avg2 %,d"", + mMindotsA, mCorr1A, mCorr2A, (int)mAvg1A, (int)mAvg2A)); + Globals.prt(String.format(""B Hits %4d corr1 %6.3f corr2 %6.3f"", mMindotsB, mCorr1B, mCorr2B)); + Globals.prt(String.format(""C Hits %4d corr1 %6.3f corr2 %6.3f"", mMindotsC, mCorr1C, mCorr2C)); + Globals.prt(String.format(""D Hits %4d corr1 %6.3f corr2 %6.3f"", mMindotsD, mCorr1D, mCorr2D)); + + double sr = Math.sqrt(nHits); + Globals.prt(String.format(""MaxGap1 %,d (%,d/%.1f) MaxGap2 %,d (%,d/%.1f) "", + mMaxgap1, mProj1.getLength(), sr, mMaxgap2, mProj2.getLength(), sr)); + String m=""Gap1: ""; for (int g : gap1list) m += String.format(""%,d "",g); Globals.prt(m); + m=""Gap2: ""; for (int g : gap2list) m += String.format(""%,d "",g); Globals.prt(m); Globals.prt(""""); + } + } + catch (Exception e) {ErrorReport.print(e, ""Set properties for synteny""); bSuccess=false;} + } + + /************************************************************************* + * Synteny algorithm + * All methods that use hitVec are in this class + * The hitVec contains the hits from grp1 to grp2 for orient ==,!= or both + *************************************************************************/ + private class BuildBlock { + private String orient; + private RWdb rwObj; // all read/write db methods + private Vector hitVec; // chr-chr hits; populated in RWdb for each new chr-chr; + private int grpIdx1, grpIdx2; + private String title, grpMsg; + + private BuildBlock(RWdb rwObj) { + this.rwObj = rwObj; + } + /************************************************************************ + * Main synteny method; orient may be ""=="", ""!="" or """" + *******************************************************************/ + private void doChrChrSynteny(int grpIdx1, int grpIdx2, String o, String grpMsg) { + try { + this.grpIdx1 = grpIdx1; + this.grpIdx2 = grpIdx2; + orient = o; // """", ==, != + this.grpMsg = grpMsg; + title = mProj1.getGrpFullNameFromIdx(grpIdx1)+ ""-"" + mProj2.getGrpFullNameFromIdx(grpIdx2); + + /* Read hits */ + hitVec = rwObj.loadHitsForGrpPair(grpIdx1, grpIdx2, orient); + if (hitVec==null) {bSuccess=false; return;} + + if (hitVec.size() < pMindots) return; // not error + + Collections.sort(hitVec); // Sort by G2 hit midpoints + for (int i = 0; i < hitVec.size(); i++) hitVec.get(i).mI2 = i; // index of the hit in the sorted list + + /** Create blocks **/ + createBlockVec(); + + hitVec.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Synteny main""); bSuccess = false;} + } + + /** This performs a ""binary search"" of the gap parameter space **/ + private void createBlockVec() { + for (int i = 0; i < ngaps; i++) { + int low1 = gap1list.get(i); // gaps are from large to small + int low2 = gap2list.get(i); + int high1 = (i > 0 ? gap1list.get(i-1) : low1); + int high2 = (i > 0 ? gap2list.get(i-1) : low2); + + while (hasGoodChain(low1, low2)) // if there is at least one good chain + binarySearch(low1, high1, low2, high2); // search them all + } + cosetBlocks(); // Use HitVec, if bStrict, make cosets not in blocks into blocks; otherwise, just count for output + } + + /************************************************************/ + private void binarySearch(int low1, int high1, int low2, int high2){ + int gap1 = (high1 + low1)/2; + int gap2 = (high2 + low2)/2; + + while ( high1-low1 > fMingap && high2-low2 > fMingap){ // 1000 + if (hasGoodChain(gap1,gap2)){ + low1 = gap1; + low2 = gap2; + gap1 = (gap1 + high1)/2; + gap2 = (gap2 + high2)/2; + } + else { + high1 = gap1; + high2 = gap2; + gap1 = (low1 + gap1)/2; + gap2 = (low2 + gap2)/2; + } + } + // Final blocks + SyBlock blk = new SyBlock(orient, grpIdx1, grpIdx2); + while (longestChain(2, low1, low2, blk)){ + if (isGoodCorr(blk)){ + blockVec.add(blk); // final: add new block to blockVec + finalBlock1(blk); + + blk = new SyBlock(orient, grpIdx1, grpIdx2); + Globals.rclear(); + Globals.rprt(blockVec.size() + "" blocks for "" + title + grpMsg); + } + else blk.clear(); + } + resetDPUsed(); + } + /************************************************************/ + private boolean hasGoodChain(int gap1, int gap2){ // createBlockVec, binarySearch + SyBlock blk = new SyBlock(orient, grpIdx1, grpIdx2); + while (longestChain(1, gap1, gap2, blk)){ + if (isGoodCorr(blk)) { + resetDPUsed(); + return true; + } + blk.clear(); + } + resetDPUsed(); + return false; + } + + private void resetDPUsed(){ + for (SyHit h : hitVec) h.mDPUsed = h.mDPUsedFinal; + } + /************************************************************ + * Uses !ht.mDPUsed from hitVec to find longest chain + ***********************************************************/ + private boolean longestChain(int who, int gap1, int gap2, SyBlock rtBlk) {// hasGoodChain, binarySearch + for (SyHit hit : hitVec) { + hit.mNDots = 1; + hit.mScore = 1; + hit.mPrevI = -1; + } + + SyHit savHt1 = null; // first of final chain + Vector links = new Vector(); // hits within range of ht1 + + for (int i = 0; i < hitVec.size(); i++) { + SyHit ht1 = hitVec.get(i); // try this dot for possible first + if (ht1.mDPUsed) continue; + + links.clear(); // get all dots within gaps range of ht1 to be used as possible bestPrev + for (int j = i-1; j >= 0; j--) { // links are from current position searching previous + SyHit ht2 = hitVec.get(j); + + if (ht2.mDPUsed) continue; + + if (ht1.midG2 - ht2.midG2 > mMaxgap2) break; // crucial optimization from sorting on midG2 + + if (Math.abs(ht1.midG1 - ht2.midG1) > mMaxgap1) continue; + + links.add(ht2); + } + if (links.size() == 0) continue; + + int maxscore = 0; + SyHit bestPrev = null; + + for (SyHit htbN : links) { // Find bestNext for ht1 by minimal gap on both sides + double d1 = Math.abs((double)htbN.midG1 - (double)ht1.midG1)/(double)gap1; + double d2 = Math.abs((double)htbN.midG2 - (double)ht1.midG2)/(double)gap2; + int gap_penalty = (int)(d1 + d2); + + int score = 1 + htbN.mScore - gap_penalty; + + if (score > maxscore) { // score can be <0 + maxscore = score; + bestPrev = htbN; + } + } + if (maxscore > 0) { + ht1.mScore = maxscore; + ht1.mPrevI = bestPrev.mI2; + ht1.mNDots += bestPrev.mNDots; + + if (savHt1 == null) savHt1 = ht1; + else if (ht1.mScore > savHt1.mScore) savHt1 = ht1; + else if (ht1.mScore >= savHt1.mScore && ht1.mNDots > savHt1.mNDots) savHt1 = ht1; + } + else { + ht1.mNDots = 1; + ht1.mScore = 1; + ht1.mPrevI = -1; + } + } // end hit loop + + if (savHt1==null || savHt1.mNDots < fMindots_keepbest) return false; // fMindots_keepBest=3 + + /* Need to build block for isGoodBlock even if it is then discarded */ + SyHit ht = savHt1; // build chain from first dot + + while (true) { + ht.mDPUsed = true; + + rtBlk.addHit(ht); // add to block hits (rtBlk is parameter); + + if (ht.mPrevI >= 0) ht = hitVec.get(ht.mPrevI); + else break; + } + return true; + } + /****************************************************/ + private boolean isGoodCorr(SyBlock blk){ // hasGoodChain, binary search; evaluate block + int nDots = blk.nHits; //blk.mHits.size(); + + if (nDots < mMindotsA) return false; + + blockCorrelations(blk); + + if (!bOrderAgainst && bOrSt) { // does not work well for small draft + if (orient.equals(orientSame) && blk.mCorr1<0) return false; + if (orient.equals(orientDiff) && blk.mCorr1>0) return false; + } + + float avg1 = (blk.mE1 - blk.mS1)/nDots; + float avg2 = (blk.mE2 - blk.mS2)/nDots; + float c1 = Math.abs(blk.mCorr1), c2 = Math.abs(blk.mCorr2); + + // mCase='R' is reject; mCase also used in Merge.removeBlocks + if (nDots >= mMindotsA && avg1 <= mAvg1A && avg2 <= mAvg2A && c1 >= mCorr1A && c2 >= mCorr2A) blk.mCase = ""A""; + else if (nDots >= mMindotsB && c1 >= mCorr1B && c2 >= mCorr2B) blk.mCase = ""B""; + else if (nDots >= mMindotsC && c1 >= mCorr1C && c2 >= mCorr2C) blk.mCase = ""C""; + else if (nDots >= mMindotsD && c1 >= mCorr1D && c2 >= mCorr2D) blk.mCase = ""D""; + + return (!blk.mCase.equals(""R"")); + } + + /*************************************************** + * from 2006 publication + * mCorr1 is the approximate linearity of the anchors in the chain as measured by the PCC; + * mCorr2 is the correlation of all the anchors in the chain’s bounding rectangle + */ + private void blockCorrelations(SyBlock blk) { + blk.mCorr1 = hitCorrelation(blk.hitVec); // chain hits + + Vector hits2 = new Vector(); + for (SyHit ht : hitVec) { + if (blk.isContained(ht.midG1, ht.midG2)) hits2.add(ht); + } + blk.mCorr2 = hitCorrelation(hits2); // all hits in surrounding block + } + private void finalBlock1(SyBlock blk) { + for (SyHit h : blk.hitVec) { + h.mDPUsedFinal = true; + h.nBlk = blk.tBlk; // use for cosetBlocks + } + } + /***************************************************************************** + * Find cosets that are not in blocks and create them. They may then get merged. + * Run on chr-chr-orient, hence, hitsVec can be used. + * Strict: make blocks from cosets; Original: count cosets not in blocks + * + * If coset is same strand, then will already be part of block if any good. + * So this only merges opposite strand cosets that 'fit' well. + *****************************************************************************/ + private void cosetBlocks() { + try { + if (!bStrict && !bVerbose) return; + if (bStrict && bOrient && !bVerbose) return; + + // gather Coset hits; loop through hits + HashMap cosetMap = new HashMap (); + for (SyHit ht : hitVec) { + if (ht.coset==0) continue; + CoSet cs; + if (cosetMap.containsKey(ht.coset)) cs = cosetMap.get(ht.coset); + else { + cs = new CoSet(ht.coset); + cosetMap.put(ht.coset, cs); + } + cs.add(ht); + } + + // loop through cosets + Vector cblkVec = new Vector (); + for (CoSet cset : cosetMap.values()) { + int nBlk=0, cntNoBlk=0; // loop through coset hits; determine if in block or not; + for (SyHit ht : cset.setVec) { + if (ht.nBlk!=0) { + if (nBlk==0) nBlk = ht.nBlk; // hits go in 1st block found for coset + else if (nBlk!=ht.nBlk && bTrace) // coset in two different blocks + Globals.prt(""Warning: collinear set "" + ht.coset + "" in block "" + nBlk + "" and "" + ht.nBlk); + } + else cntNoBlk++; + } // end hit loop + + if (!bStrict) { + if (nBlk==0) {cntSetNB++; cntSetNBhits += cset.setVec.size(); } + continue; + } + + if (nBlk==0) { // new block + SyBlock cblk = new SyBlock(orient, grpIdx1, grpIdx2); // assigned nBlk on creation + for (SyHit ht : cset.setVec) + if (ht.nBlk==0) cblk.addHit(ht); + + cblk.mCase = ""N""; + cblk.setActualCoords(); // better for possible merge + cblkVec.add(cblk); + continue; + } + + if (cntNoBlk>0) { // at least one hit in block, add rest to the existing block; rare case + for (SyBlock cblk : blockVec) { + if (cblk.tBlk == nBlk) { + for (SyHit ht : cset.setVec) { + if (ht.nBlk==0) { + cblk.addHit(ht); + cntTrCsChg++; + } + } + break; + } + } + } + // else nBlk>0 and all are in a block + } // end coset loop + + // If Cosets merge, they have a better change of merging into a bigger block + if (cblkVec.size()>0) { + Merge mergeObj = new Merge(Merge.COSET, cblkVec, bOrient, pMindots, gap2list.get(0)); + cblkVec = mergeObj.mergeBlocks(gap1list.get(0), gap2list.get(0)); + + for (SyBlock blk : cblkVec) blockVec.add(blk); + } + } + catch (Exception e) {ErrorReport.print(e, ""trim block""); } + } + /**************************************************/ + private class CoSet { + private Vector setVec = new Vector (); + + private void add(SyHit ht) {setVec.add(ht);} + + private CoSet(int num) {} + } + } + /************************************************************* + * All blocks for grp-grp, both orient + */ + private class FinishBlock { + private RWdb rwObj; + + private FinishBlock(RWdb rwObj) { + this.rwObj = rwObj; + } + private void doChrChrBlkFinish(int grpIdx1, int grpIdx2) { + try { + for (SyBlock blk : blockVec) finalBlock2(blk); + + if (grpIdx1 == grpIdx2) rmDiagBlocks(); + + mergeBlocks(); // always merge contained; conditionally merge olap/close + + if (bStrict) strictRemoveBlocks(); + + // Finalize for DB save + Collections.sort(blockVec); // Sort on start1 for final block# (sorted before Merge, but may have changed) + + String msg= String.format(""%-6s %-6s:"", mProj1.getGrpFullNameFromIdx(grpIdx1), mProj2.getGrpFullNameFromIdx(grpIdx2)); + int blkNum=1; // final block numbering + for (SyBlock b : blockVec) { + b.mGrpIdx1 = grpIdx1; + b.mGrpIdx2 = grpIdx2; + b.mBlkNum = blkNum++; + + if ((bOrient || bStrict) && b.orient.equals(orientSame)) cntGrpSame++; else cntGrpDiff++; // for bVerbose + if (bTraceBlks) msg += b.tBlk + ""->"" + b.mBlkNum + ""; ""; // for trace + } + if (bTraceBlks && blockVec.size()>0) Globals.prt(msg); + + rwObj.saveBlocksToDB(blockVec, false); + if (isSelf) rwObj.saveBlocksToDB(blockVec, true); + + totalBlocks += blockVec.size(); + } + catch (Exception e) {ErrorReport.print(e, ""Synteny main finish""); bSuccess = false;} + } + + /*********************************************************** + * This is called on all final blocks from BuildBlock, and any changed blocks from Merge + *********************************************************/ + private void finalBlock2(SyBlock blk) { + for (SyHit h : blk.hitVec) h.mDPUsedFinal = h.mDPUsed = false; + + blk.setActualCoords(); // Change from midpoint to actual coords + blk.avgGap(); // saved to DB; sorted by hitVec + + blk.mCorr1 = hitCorrelation(blk.hitVec); + blk.hasChg = false; + } + + /***************************************************** + * Merge final blocks + * Run on chr-chr pair (both orients) before strict (HitsVec cannot be used because maybe only one orient) + */ + private void mergeBlocks() { + cntGrpMerge = 0; + Collections.sort(blockVec); // Sort blocks on start coord + + // Always do for contained + Merge mergeObj = new Merge(Merge.CONTAINED, blockVec, bOrient, pMindots, gap2list.get(0)); + blockVec = mergeObj.mergeBlocks(0, 0); // returned merged contained blocks + + for (SyBlock blk : blockVec) { + if (blk.hasChg) { + finalBlock2(blk); + cntTrIn++; + } + } + cntTrCoset += mergeObj.cntCoset; cntTrSkip += mergeObj.cntSkip; + if (pMerge.equals(""0"")) return; // Contain only + + // 0 Contain, 1 Overlap + int nb = blockVec.size(); + + mergeObj = new Merge(Merge.OLAP, blockVec, bOrient, pMindots, gap2list.get(0)); // T=overlap or close; send blocks; perform overlap + + if (pMerge.equals(""1"")) + blockVec = mergeObj.mergeBlocks(0, 0); // combine small overlapping + else + blockVec = mergeObj.mergeBlocks(gap1list.get(0), gap2list.get(0)); // return merged close blocks + + for (SyBlock blk : blockVec) { + if (blk.hasChg) { + finalBlock2(blk); + cntTrOlap++; + } + } + cntGrpMerge += nb-blockVec.size(); + } + + /****************************************** + * Run on final chr-chr pair (both orients) after merge + * Coset blocks are not on final Merge sets unless they are merged with blocks>pMindots + * So just need to recalculate #Cosets not in blocks + *****************************************/ + private void strictRemoveBlocks() { + try { + int cntRm=0; + for (SyBlock blk : blockVec) { + if (blk.nHits0) { // rebuild blockVec + Vector xVec = new Vector (); + for (SyBlock blk : blockVec) { + if (!blk.mCase.equals(""X"")) xVec.add(blk); + else blk.clear(); + } + blockVec = xVec; + } + } + catch (Exception e) {ErrorReport.print(e, ""trim block""); } + } + + /************************************************** + * Remove blocks that run along the diagonal with few genes; Hsa has many, Arab none + * Note: even if a block is retained, it may be removed in strictRemove + */ + private void rmDiagBlocks(){ + Vector out = new Vector(); + for (SyBlock b : blockVec){ + int gap = Math.max(b.mS1,b.mS2) - Math.min(b.mE1,b.mE2); + if (gap>0) { + out.add(b); + continue; + } + gap = -gap; + int len = b.mE2-b.mS2+1; + double ratio = (double)gap/(double)len; + if (bTrace) Globals.prt(String.format(""Rm %s %,10d %,10d %.6f "", Globals.toTF(ratio>=fDiag), gap, len, ratio) + b.toString()); + + if (ratio cntNG*2) { // 2x genes vs non-gene + out.add(b); + continue; + } + } + cntTrRmDiag++; + } + blockVec = out; + } + } +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/OrderAgainst.java",".java","11646","334","package backend.synteny; + +import java.io.File; +import java.io.FileWriter; +import java.sql.ResultSet; +import java.util.Collections; +import java.util.TreeMap; +import java.util.Vector; + +import database.DBconn2; +import backend.Constants; +import backend.Utils; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.ErrorReport; +import util.ProgressDialog; +import util.FileDir; + +/**************************************************************** + * Called from SyntenyMain after blocks are created + */ +public class OrderAgainst { + private ProgressDialog mLog; + private DBconn2 dbc2; + private Mpair mp; + private Mproject mProj1, mProj2; + + protected OrderAgainst(Mpair mp, ProgressDialog mLog, DBconn2 dbc2) { + this.mp = mp; + this.mProj1 = mp.getProj1(); + this.mProj2 = mp.getProj2(); + this.mLog = mLog; + this.dbc2 = dbc2; + } + + /************************************************************** + // mProj1 is proj_idx1 and mProj2 is proj_idx2 in database. + // if !switch, mProj1 is draft to be ordered against mProj2 the target + // if switch, mProj2 is draft to be ordered against mProj1 the target + ****************************************************************/ + protected void orderGroupsV2(boolean bSwitch) { + try { + if (!bSwitch) {pDraft = mProj1; pTarget = mProj2; } + else {pDraft = mProj2; pTarget = mProj1; } + + String ordPfx = pDraft.getGrpPrefix(); + String targPfx = pTarget.getGrpPrefix(); + String chr0 = targPfx + ""UNK""; + int chr0Idx = 99999; + + long startTime = Utils.getTime(); + mLog.msg(""Ordering "" + pDraft.getDBName() + "" contigs against "" + pTarget.getDBName()); + + if (!s1LoadDataDB(bSwitch, chr0, chr0Idx)) return; + + if (!s2OrderFlipGrpDB(targPfx, ordPfx, chr0, chr0Idx)) return; + + s3WriteNewProj(); + + Utils.prtMsgTimeDone(mLog, ""Complete ordering"", startTime); + } + catch (Exception e) {ErrorReport.print(e, ""Ordering sequence""); } + } + /*********************************************************** + * Load groups from both projects + */ + private boolean s1LoadDataDB(boolean bSwitch, String chr0, int chr0Idx) { + try { + /** Get Draft and Target groups **/ + ResultSet rs = dbc2.executeQuery(""select idx, fullname, p.length "" + + "" from xgroups as g "" + + "" join pseudos as p on p.grp_idx=g.idx "" + + "" where proj_idx="" + pDraft.getIdx()); + while (rs.next()) { + Draft o = new Draft(); + o.gidx = rs.getInt(1); + o.ctgName = rs.getString(2); + o.ctgLen = rs.getInt(3); + idxDraftMap.put(o.gidx, o); + } + + rs = dbc2.executeQuery(""select idx, fullname from xgroups "" + + "" where proj_idx="" + pTarget.getIdx()); + while (rs.next()) { + Target o = new Target(); + o.gidx = rs.getInt(1); + o.chrName = rs.getString(2); + idxTargetMap.put(o.gidx, o); + } + Target o = new Target(); + o.gidx = chr0Idx; + o.chrName = chr0; + idxTargetMap.put(chr0Idx, o); + + rs = dbc2.executeQuery(""select grp1_idx, grp2_idx, start1, start2, score, corr from blocks "" + + "" where proj1_idx="" + mProj1.getIdx() + "" and proj2_idx="" + mProj2.getIdx() + + "" order by score desc, grp1_idx, grp2_idx, blocknum"" ); + + while (rs.next()) { + int tgidx1 = rs.getInt(1); + int tgidx2 = rs.getInt(2); + int tStart1 = rs.getInt(3); + int tStart2 = rs.getInt(4); + int score = rs.getInt(5); + + int gidx1, gidx2, pos; + if (!bSwitch) { + gidx1 = tgidx1; + gidx2 = tgidx2; + pos = tStart2; + } + else { + gidx1 = tgidx2; + gidx2 = tgidx1; + pos = tStart1; + } + Draft d = idxDraftMap.get(gidx1); + + if (d.score > score) continue; // a group (chr) can be split across multiple blocks; use first with biggest score + + d.pos = pos; + d.score = rs.getInt(5); + d.bDoFlip = (rs.getDouble(6)<0); // Block containing contig is flipped + + Target t = idxTargetMap.get(gidx2); + d.chrName = t.chrName; + d.tidx = t.gidx; + } + rs.close(); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Load Data""); return false; } + } + /** + * Assign chr0 to unassigned, create ordered ctgs, write ordered file, update DB order + ***/ + private boolean s2OrderFlipGrpDB(String targPfx, String ordPfx, String chr0, int chr0Idx) { + try { + + for (Draft d : idxDraftMap.values()) { + if (d.tidx==0) { + d.chrName = targPfx + chr0Idx; // sort last; renamed after sort + d.tidx = chr0Idx; + } + orderedDraft.add(d); + } + Collections.sort(orderedDraft); + + /** Write Ordered file and update DB order **/ + String fileName = Constants.seqDataDir + pDraft.getDBName() + getOrderFile(mp); + File ordFile = new File(fileName); + if (ordFile.exists()) ordFile.delete(); + FileWriter ordFileW = new FileWriter(ordFile); + + ordFileW.write(pDraft.getDBName() + ""-"" + ordPfx + "","" + pTarget.getDBName() + ""-"" + targPfx + "",pos,F/R,#anchors,"" + pDraft.getDBName() + ""-length\n""); + + int nOrd=1; // new order of contigs in database; only place database changes for V2 + for (Draft d : orderedDraft) { + int f = (d.bDoFlip) ? 1 : 0; // the flipped is not used anywhere + dbc2.executeUpdate(""update xgroups set sort_order="" + nOrd + "",flipped="" + f + + "" where idx="" + d.gidx); + nOrd++; + + String rc = (d.bDoFlip) ? ""R"" : ""F""; + if (d.tidx==chr0Idx) d.chrName = chr0; + ordFileW.write(d.ctgName + "","" + d.chrName + "","" + d.pos + "","" + rc + "","" + d.score + "","" + d.ctgLen + ""\n""); + } + ordFileW.close(); + mLog.msg("" Wrote order to "" + fileName); + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Order Draft""); return false; } + } + + /** + * Write new project sequence/x.fa, annotation/gap.gff and params + ***/ + private void s3WriteNewProj() { + try { + String ordProjName = Constants.getOrderDir(mp); + String ordDirName = Constants.seqDataDir + ordProjName; + + mLog.msg("" Creating new project "" + ordDirName); + + File ordDir = new File(ordDirName); + if (ordDir.exists()) { + mLog.msg("" Delete previous "" + ordDirName); + FileDir.clearAllDir(ordDir); + ordDir.delete(); + } + FileDir.checkCreateDir(ordDirName, false); + + File ordSeqDir = FileDir.checkCreateDir(ordDir + Constants.seqSeqDataDir, false); + File ordFasta = FileDir.checkCreateFile(ordSeqDir, ordProjName + Constants.faFile, ""SM fasta file""); + FileWriter ordFastaFH = new FileWriter(ordFasta); + + File ordAnnoDir = FileDir.checkCreateDir(ordDir + Constants.seqAnnoDataDir, false); + File ordGFF = FileDir.checkCreateFile(ordAnnoDir, ordProjName + "".gff"", ""SM gff""); + FileWriter ordGffFH = new FileWriter(ordGFF); + + int sepLen=100; + String separator=""""; + for (int i=0; i<10; i++) separator += ""NNNNNNNNNN""; + + Target curTar=null; + String lastCtgName = """"; + int cntFlip=0; + + for (Draft d : orderedDraft) { + if (curTar==null || curTar.gidx != d.tidx) { + curTar = idxTargetMap.get(d.tidx); + ordFastaFH.write("">"" + curTar.chrName + ""\n""); + } + else { // N's between subsequent contigs aligned to chrN + ordFastaFH.write(separator + ""\n""); + + ordGffFH.write(curTar.chrName + ""\tconsensus\tgap\t"" + + curTar.tLen + ""\t"" + (curTar.tLen+sepLen) + + ""\t.\t+\t.\tName \""GAP:"" + lastCtgName + ""-"" + d.ctgName + ""\""\n""); + curTar.nLen += sepLen; + curTar.tLen += sepLen; + } + ResultSet rs = dbc2.executeQuery(""select ps.seq from pseudo_seq2 as ps "" + + "" where ps.grp_idx ="" + d.gidx + "" order by ps.chunk asc""); + String seq=""""; + while (rs.next()) + seq += rs.getString(1); + rs.close(); + + if (d.bDoFlip) { // v2 flips on output instead of in database for draft + seq = reverseComplement(seq); + cntFlip++; + } + + for (int i = 0; i < seq.length(); i += 50) + { + int end = Math.min(i+50, seq.length()-1); + String line = seq.substring(i, end); + ordFastaFH.write(line + ""\n""); + } + curTar.tLen += seq.length(); + curTar.bLen += seq.length(); + lastCtgName = d.ctgName; + } + mLog.msg("" Flipped contigs "" + cntFlip); + + long blen=0,nlen=0,tlen=0; + mLog.msg("" Ordered chromosome lengths:""); + mLog.msg(String.format("" %-10s %12s %12s %12s"", ""ChrName"", ""nBases"", ""Added Ns"", ""Total"")); + for (Target t : idxTargetMap.values()) { + mLog.msg(String.format("" %-10s %,12d %,12d %,12d"", + t.chrName, t.bLen, t.nLen, t.tLen)); + blen += t.bLen; + nlen += t.nLen; + tlen += t.tLen; + } + mLog.msg(String.format("" %-10s %,12d %,12d %,12d"", ""Total"", blen, nlen, tlen)); + + mLog.msg("" Wrote sequence to "" + ordFasta); + mLog.msg("" Wrote gaps to "" + ordGFF); + ordFastaFH.close(); + ordGffFH.close(); + + File ordParam = Utils.getParamsFile(ordDir.getAbsolutePath(), Constants.paramsFile); + ordParam = FileDir.checkCreateFile(ordDir, Constants.paramsFile, ""SM params""); // deletes if exists + FileWriter ordParamsFH = new FileWriter(ordParam); + ordParamsFH.write(""category = "" + pDraft.getdbCat() + ""\n""); + ordParamsFH.write(""abbrev_name = Draf\n""); + ordParamsFH.write(""display_name="" + getOrderDisplay(mp) + ""\n""); + ordParamsFH.write(""description="" + getOrderDesc(mp) + ""\n""); + ordParamsFH.write(""grp_prefix="" + pTarget.getGrpPrefix() + ""\n""); + ordParamsFH.close(); + } + catch (Exception e) {ErrorReport.print(e, ""write chromosomes""); } + } + private String reverseComplement(String in){ + in = (new StringBuffer(in)).reverse().toString().toUpperCase(); + in = in.replace('A', 't'); + in = in.replace('G', 'c'); + in = in.replace('C', 'g'); + in = in.replace('T', 'a'); + return in.toLowerCase(); + } + /***************************************************************************/ + private String getOrderFile(Mpair mp) { + if (mp.isOrder1(Mpair.FILE)) return ""/"" + mp.mProj2.getDBName() + Constants.orderSuffix; + if (mp.isOrder2(Mpair.FILE)) return ""/"" + mp.mProj1.getDBName() + Constants.orderSuffix; + return null; + } + + private String getOrderDisplay(Mpair mp) { + if (mp.isOrder1(Mpair.FILE)) return mp.mProj1.getDisplayName() + ""."" + mp.mProj2.getDisplayName(); + if (mp.isOrder2(Mpair.FILE)) return mp.mProj2.getDisplayName() + ""."" + mp.mProj1.getDisplayName(); + return null; + } + private String getOrderDesc(Mpair mp) { + if (mp.isOrder1(Mpair.FILE)) return mp.mProj1.getDisplayName() + "" ordered against "" + mp.mProj2.getDisplayName(); + if (mp.isOrder2(Mpair.FILE)) return mp.mProj2.getDisplayName() + "" ordered against "" + mp.mProj1.getDisplayName(); + return null; + } + /***************************************************************************/ + private class Draft implements Comparable { + int gidx; // group.idx + String ctgName=""""; // group.fullname + int ctgLen; // pseudo.length + + int score=0; // block.score + boolean bDoFlip=false; // (block.corr<0) + int pos=0; // block.start to chromosome + int tidx = 0; // block.grpX_idx; target chromosome; if 0, not aligned to the target + String chrName=""""; // From idxTargetMap.get(tidx).chrName + + public int compareTo(Draft d) { + if (chrName.equals(d.chrName)) { + if (posd.pos) return 1; + if (scored.score) return 1; + return 0; + } + return chrName.compareTo(d.chrName); + } + } + private class Target { + int gidx; // group.idx, group.proj_idx + String chrName; // group.fullname + int bLen=0, nLen=0, tLen=0; + } + private Mproject pDraft, pTarget; + private TreeMap idxTargetMap = new TreeMap (); + private TreeMap idxDraftMap = new TreeMap (); + private Vector orderedDraft = new Vector (); +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/SyBlock.java",".java","6481","205","package backend.synteny; + +import java.util.Vector; +import java.util.Collections; +import java.util.Comparator; +import java.util.TreeSet; + +import symap.Globals; +import util.ErrorReport; + +/************************************** + * Block class used for the synteny computations + */ +public class SyBlock implements Comparable { + static protected int cntBlk=1; + + protected int tBlk=0; // temporary unique + + protected String orient=""""; // """", ""=="", ""!="", needed so not merged; + protected int mS1, mE1, mS2, mE2; // mid-point, until ready to save - than exact + protected float mCorr1, mCorr2; // chain hits, all hits in block + protected String mCase = ""R""; // R=fail, A,B,C,D in isGoodCorr, N in coset, X is delete, M merged + + protected int mGrpIdx1, mGrpIdx2, mBlkNum=0; // Finalize + protected int mIdx; // get from database to enter pseudo_blocks_hits + protected double avgGap1=0, avgGap2=0; + + protected Vector hitVec; // Block hits + protected int nHits=0; // number hits + + private TreeSet mHitIdxSet; // quick search for hitVec in Merge + protected boolean hasChg=false; // MergeWith or Strict + + protected SyBlock(String orient, int grpIdx1, int grpIdx2) { + hitVec = new Vector(); + mHitIdxSet = new TreeSet(); + this.orient = orient; + tBlk = cntBlk++; + + mGrpIdx1 = grpIdx1; + mGrpIdx2 = grpIdx2; + + mS1 = mS2 = Integer.MAX_VALUE; mE1 = mE2 = 0; + } + protected void clear() { // gets reused + hitVec.clear(); + mHitIdxSet.clear(); + mCorr1 = mCorr2 = 0; + mS1 = mS2 = Integer.MAX_VALUE; mE1 = mE2 = 0; + } + protected void addHit(SyHit ht) { + hitVec.add(ht); + nHits = hitVec.size(); + + mS1 = Math.min(mS1, ht.midG1); + mE1 = Math.max(mE1, ht.midG1); + mS2 = Math.min(mS2, ht.midG2); + mE2 = Math.max(mE2, ht.midG2); + } + protected void setActualCoords() { // finalize, used actual start/end + for (SyHit h : hitVec) { + if (h.s1mE1) mE1=h.e1; + if (h.s2mE2) mE2=h.e2; + } + } + + // Merge this block + // Orient not recalculated, but it is the mCorr1 that is save in database for orient + protected void mergeWith(SyBlock b) { + hasChg = true; + + mS1 = Math.min(mS1, b.mS1); + mS2 = Math.min(mS2, b.mS2); + mE1 = Math.max(mE1, b.mE1); + mE2 = Math.max(mE2, b.mE2); + + for (SyHit ht : b.hitVec) { + if (!mHitIdxSet.contains(ht.mIdx)) { + mHitIdxSet.add(ht.mIdx); + addHit(ht); + } + else if (SyntenyMain.bTrace) Globals.prt(""Merge dup hit#"" + ht.mI2 + "" "" + tBlk + "" -> "" + b.tBlk); + } + nHits = hitVec.size(); + mCase = ""M""; + } + + /******************************************* + * Checks to see whether the collinear block fit well in this block; called from Merge + */ + protected boolean fitStrict(SyBlock coblk, int fullGap2, boolean bPrt) {// hits sorted on side1; + try { + int cutoff = (int) (Math.round((double)coblk.nHits/2.0) * (double)fullGap2); + cutoff = Math.max(cutoff, 300000); // plants have small gaps + cutoff = Math.min(cutoff, 4000000); // mammals have large gaps, e.g. human 3,389,849 + + SyHit cHtTop = coblk.hitVec.get(0); + SyHit cHtBot = coblk.hitVec.get(coblk.nHits-1); + SyHit htTop=null, htBot=null; + + for (int i=1; i cHtTop.hitNum) htTop = hitVec.get(i-1); + + if (htA.hitNum > cHtBot.hitNum) htBot = htA; + + if (htTop!=null && htBot!=null) break; + } + boolean isGood1 = true, isGood2 = true; + int diff1 = 0, diff2 = 0; + if (htTop!=null) { + diff1 = Math.abs(cHtTop.midG2 - htTop.midG2); + isGood1 = diff1 < cutoff; + } + if (htBot!=null) { + diff2 = Math.abs(cHtBot.midG2 - htBot.midG2); + isGood2 = diff2 < cutoff; + } + + if (bPrt && SyntenyMain.bTraceBlks) { + cHtTop.tprt(String.format(""C %-4d 1"", cHtTop.coset)); + if (htTop!=null) htTop.tprt(String.format(""B %-4d 1"", tBlk)); else Globals.prt(""At TOP""); + Globals.prt(String.format(""%s%s D %,10d %,10d [BK %-3d #%-4d Top M2 %,10d] [bk %-3d #%-4d top M2 %,10d] Gap %,d\n"", + Globals.toTF(isGood1),Globals.toTF(isGood2), diff1, diff2, coblk.tBlk, coblk.nHits, cHtTop.midG2, tBlk, nHits, htTop.midG2, cutoff)); + } + + return isGood1 || isGood2; + } + catch (Exception e) {ErrorReport.print(e,""strictTrim""); return false;} + } + /******************************************************************/ + // Block finalize: Compute avgGap + // + protected void avgGap() { + int nGap = nHits-1; + avgGap1 = avgGap2 = 0; + + // side2 avgGap + Collections.sort(hitVec,new Comparator() { + public int compare(SyHit a, SyHit b) { + if (a.s2 != b.s2) return a.s2 - b.s2; + else return a.e2 - b.e2; + }}); + + for (int i=0; i() { + public int compare(SyHit a, SyHit b) { + if (a.s1 != b.s1) return a.s1 - b.s1; + else return a.e1 - b.e1; + }}); + + for (int i=0; i= mS1 && pos1 <= mE1 && + pos2 >= mS2 && pos2 <= mE2); + } + + protected double avgPctID() { // to save in DB + if (hitVec.size()==0) return -1.0; // for self-synteny - see RWdb + + double avg = 0; + for (SyHit h : hitVec) avg += h.mPctID; + avg /= hitVec.size(); + avg = (Math.round(10*avg)); + return avg/10; + } + protected void tprt(String msg) { + int m = (mBlkNum==0) ? tBlk : mBlkNum; + String x = String.format(""%-6s [Blk #%-3d %2s %s #Hits %-4d %6.3f %6.3f]"", + msg, m, orient, mCase, nHits, mCorr1, mCorr2); + + String y = String.format("" [AG %,7d %,7d S1 %,10d %,10d Len %,10d %,10d]"", + (int)avgGap1, (int)avgGap2, mS1, mS2, (mE1-mS1), (mE2-mS2)); + + String z = String.format("" [1st Hit# %4d C# %d]"",hitVec.get(0).hitNum, hitVec.get(0).coset); + Globals.prt(x + y + z); + } + public String toString() { + return String.format(""Block# %3d Grps %3d,%3d Hits %4d S-E %,10d %,10d %,10d %,10d "", + mBlkNum, mGrpIdx1, mGrpIdx2, hitVec.size(), mS1, mE1, mS2, mE2); + } + public int compareTo (SyBlock b2) { + if (mS1 != b2.mS1) return mS1 - b2.mS1; + else return mE1 - b2.mE1; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/synteny/SyHit.java",".java","2806","74","package backend.synteny; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Vector; + +import symap.Globals; + +/***************************************************** + * Hit class used for the synteny computations + */ +public class SyHit implements Comparable { + protected int s1, e1, s2, e2; // input coords; used for final block coords and finding midpoint + protected int mIdx; // index of the hit in the database table; + protected int mPctID; // MUMmer %id; create average of chain to save in DB; never used + protected int coset; // collinear set; for bStrict to include cosets + protected int hitNum; // hitnum computed down G1 side after clustering + protected int nGenes; // gene_overlap for isSelf + + protected int midG1; // (h.start1+h.end1)/2 used for synteny computations + protected int midG2; // (h.start2+h.end2)/2 + + protected int mI2; // index of the hit in the sorted list sorted on midG2 - set before for binarySearch + + // parameters used in finding long chain + protected int mScore; // score of longest chain terminating at this hit + protected int mPrevI; // predecessor in longest chain; finalBlock used for previous hitNum + protected int mNDots; // number of hits in longest chain + + // indicates if the hit has been returned in a chain in the current iteration + protected boolean mDPUsed = false; + + // indicates if the hit has been put into a block and should not be used in any future iterations + protected boolean mDPUsedFinal = false; + protected int nBlk = 0; // Used in SyntenyMain.cosetBlock + + protected SyHit(int s1, int e1, int s2, int e2, int idx, int pctid, int coset, int hitnum, int gene_overlap){ + this.s1 = s1; + this.e1 = e1; + this.s2 = s2; + this.e2 = e2; + this.mIdx = idx; + this.mPctID = pctid; + this.coset = coset; + this.hitNum = hitnum; + this.nGenes = gene_overlap; // for isSelf + + midG1 = (s1+e1)/2; + midG2 = (s2+e2)/2; + } + protected void tprt(String msg) { + Globals.prt(String.format("" %s Hit# %,6d S/E: %,10d %,10d %,10d %,10d CS %d"", + msg, hitNum, s1, e1, s2, e2, coset)); + } + public String toString() { + return String.format("" Hit# %,6d Sort %,5d Prev %,5d NDots %5d S-E: %,10d %,10d %,10d %,10d "", + hitNum, mI2, mPrevI, mNDots, s1, e1, s2, e2); + } + ///////////////////////////////////////////////////////////////////// + public int compareTo(SyHit h2) { // For binarySearch + if (midG2 != h2.midG2) return midG2 - h2.midG2; + else return midG1 - h2.midG1; + } + + //SyHit.sortListSide1(hitVec); + protected static void sortListSide1(Vector mHits) {// sorted on side1 in ascending order + Collections.sort(mHits,new Comparator() { + public int compare(SyHit a, SyHit b) { + if (a.s1 != b.s1) return a.s1 - b.s1; + else return a.e1 - b.e1; + }}); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/AnchorMain1.java",".java","31399","856","package backend.anchor1; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.TreeSet; +import java.util.Vector; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Arrays; +import java.util.Collections; +import java.io.FileReader; +import java.io.BufferedReader; +import java.io.File; +import java.lang.Math; + +import backend.Constants; +import backend.Utils; +import backend.AnchorMain; +import database.DBconn2; +import symap.Globals; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.Cancelled; +import util.ErrorCount; +import util.ErrorReport; +import util.ProgressDialog; + +/****************************************************** + * Read align files and create anchors + * CAS575 made self-synteny not dependent on order of schema, removed binstats; self-chr diagonal not saved + * New algo: Only lower diagonal hits are analyzed, then mirrored. e.g. Rice_f8.Rice_f11.mum swap coords, Rice_f9.Rice_f1.mum no swap. + * Old algo: Mix of lower and upper as input, then all are mirrored. + */ +enum HitStatus {In, Out, Undecided }; +enum QueryType {Query, Target, Either }; +enum HitType {GeneGene, GeneNonGene, NonGene} +enum GeneType {Gene, NonGene, NA} + +public class AnchorMain1 { + private boolean VB = Constants.VERBOSE; + private static final int HIT_VEC_INC = 1000; + private static final int nLOOP = 10000; + + public static int nAnnot=0; // number of input projects that are annotated; different filter rules based on if 0,1,2 + + private AnchorMain mainObj; + private DBconn2 dbc2, tdbc2; + private ProgressDialog plog; + private int pairIdx = -1; + private Mpair mp; + + private boolean bSuccess=true; + private String proj1Name, proj2Name; + private Proj syProj1, syProj2; + + private int mTotalHits=0, mTotalLargeHits=0, mTotalBrokenHits=0, mTotalWS=0; + private boolean isSelf = false, isNucmer=false; + + private HashSet filtHitSet = new HashSet (); + private Vector diagHits = new Vector (); // for self-synteny; seems to process more than diagonal... + + public AnchorMain1(AnchorMain mainObj) { + this.mainObj = mainObj; + this.dbc2 = mainObj.dbc2; + this.plog = mainObj.plog; + this.mp = mainObj.mp; + this.pairIdx = mp.getPairIdx(); + } + + /**************************************************************************/ + public boolean run(Mproject pj1, Mproject pj2, File dh) throws Exception { + try { + tdbc2 = new DBconn2(""Anchors-""+DBconn2.getNumConn(), dbc2); + proj1Name = pj1.getDBName(); proj2Name = pj2.getDBName(); + isSelf = pj1.getIdx()==pj2.getIdx(); + + /** execute **/ + loadAnnoBins(pj1, pj2); if (!bSuccess) return false; // create initial hitbins from genes + + scanAlignFiles(dh); if (!bSuccess) return false; // create new hitbins from non-gene hits + + filterFinalHits(); if (!bSuccess) return false; + + saveAllResults(); if (!bSuccess) return false; + + /** finish **/ + filtHitSet.clear(); + tdbc2.close(); + } + catch (OutOfMemoryError e) { + filtHitSet.clear(); + tdbc2.shutdown(); + ErrorReport.prtMem(); + System.out.println(""\n\nOut of memory! Edit the symap script and increase the memory limit (mem=).\n\n""); + System.exit(0); + } + return true; + } + + /*********************************************************************** + * Load annotations and create initial HitBins + */ + private void loadAnnoBins(Mproject pj1, Mproject pj2) { + try { + long memTime = Utils.getTimeMem(); + + int topN = mp.getTopN(Mpair.FILE); + syProj1 = new Proj(dbc2, plog, pj1, proj1Name, topN, Constants.QUERY); // loads group + syProj2 = new Proj(dbc2, plog, pj2, proj2Name, topN, Constants.TARGET); // make new object even if self or filtering gets confused + + nAnnot=0; // static, make sure its 0 + if (syProj1.hasAnnot()) nAnnot++; + if (syProj2.hasAnnot()) nAnnot++; + if (nAnnot==0) { + plog.msg(""Neither project is annotated""); + return; + } + + if (VB) plog.msg("" Loading annotations""); else Globals.rprt("" Loading annotation""); + Vector group1Vec = syProj1.getGroups(); + Vector group2Vec = syProj2.getGroups(); + + if (syProj1.hasAnnot()) { + int tot1=0; + for (Group grp : group1Vec) tot1 += grp.createAnnoFromGenes(tdbc2); + if (VB) Utils.prtNumMsgFile(plog, tot1, proj1Name + "" genes ""); + else Globals.rprt(String.format(""%,d %s genes"", tot1, proj1Name)); + } + if (syProj2.hasAnnot()) { + int tot2=0; + for (Group grp : group2Vec) tot2 += grp.createAnnoFromGenes(tdbc2); + if (!isSelf) { + if (VB) Utils.prtNumMsgFile(plog, tot2, proj2Name + "" genes ""); + else Globals.rprt(String.format(""%,d %s genes"", tot2, proj2Name)); + } + } + + failCheck(); + if (Globals.TRACE) Utils.prtTimeMemUsage(""Load Annot bins"", memTime); + } + catch (Exception e) {ErrorReport.print(e, ""load annotation""); bSuccess=false;} + } + + /******************************************************************* + */ + private boolean scanAlignFiles(File dh) throws Exception { + try { + /** first scan: process all aligned files in directory */ + plog.msg("" Scan files to create candidate genes from hits""); + long memTime = Utils.getTimeMem(); + + int nHitsScanned = 0, nFile=0; + TreeSet skipList = new TreeSet(); + File[] fs = dh.listFiles(); + Arrays.sort(fs); // not necessary, but nice for VB output; CAS575 this changes the hits found slightly! + int nLoop = (isSelf) ? 2 : 1; // process grp1!=grp2 first to get similar results as v4.2 + + for (int i=0; i1 || !VB) Utils.prtNumMsgFile(plog, nHitsScanned, ""Total scanned hits from "" + nFile + "" files""); + if (nHitsScanned!=mTotalHits) Utils.prtNumMsgFile(plog, mTotalHits, ""Total accepted hits""); + if (mTotalLargeHits > 0 && VB) Utils.prtNumMsgFile(plog, mTotalLargeHits, ""Large hits (> "" + Group.FSplitLen + "") "" + + mTotalBrokenHits + "" Split ""); + if (Globals.TRACE) Utils.prtTimeMemUsage(plog, ""Complete scan candidate genes"", memTime); + + /** Second scan - to cluster and filter **/ + plog.msg("" Scan files to cluster and filter hits""); + memTime = Utils.getTimeMem(); + + nHitsScanned = nFile = 0; + + for (int i=0; i1 || !VB) Utils.prtNumMsg(plog, nHitsScanned, ""Total cluster hits ""); + + if (Globals.TRACE) { + Utils.prtNumMsgFile(plog, mTotalWS, ""Cluster hits with >3 subhits have wrong strand compared to hit genes""); + Utils.prtTimeMemUsage(plog, ""Complete scan cluster"", memTime); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Reading seq anchors""); bSuccess=false; return false;} + } + + /************************************************************* + * first time through, create the predicted genes from non-gene hits + */ + private int scanFile1AnnoBins(File mFile, Proj p1, Proj p2) throws Exception { + Vector rawHits = new Vector(HIT_VEC_INC,HIT_VEC_INC); + try { + if (!VB) Globals.rprt(String.format(""Scan %s"", Utils.fileFromPath(mFile.toString()))); + + String line, fileType=""PROMER""; + int numErrors = 0, hitNum = 0; + int cntSkip=0, cntSwap=0; + + /** Read file and build rawHits **/ + BufferedReader fh = new BufferedReader(new FileReader(mFile)); + + while (fh.ready()) { + line = fh.readLine().trim(); + if (line.length() == 0) continue; + if (!Character.isDigit(line.charAt(0))) { + if (line.startsWith(""NUCMER"")) { + isNucmer = true; + fileType = ""NUCMER""; + } + continue; + } + hitNum++; + Hit hit = new Hit(); + hit.origHits = 1; + + boolean success = scanNextMummerHit(line,hit); + if (!success) { + if (numErrors < 5){ + plog.msg("" Error on line "" + hitNum + "" in "" + mFile.getName()); // Will go to symap.log and terminal + numErrors++; + continue; + } + else {fh.close(); Globals.die(""Too many errors in file "" + mFile.getName());} + } + hit.queryHits.grpIdx = p1.grpIdxFromQuery(hit.queryHits.name); + if (hit.queryHits.grpIdx == -1) { + plog.msg(proj2Name + "": Query not found: "" + hit.queryHits.name + "" --skipping file""); + fh.close(); + return 0; + } + hit.targetHits.grpIdx = p2.grpIdxFromQuery(hit.targetHits.name); + if (hit.targetHits.grpIdx == -1) { + plog.msg(proj1Name + "": Target not found for: "" + hit.targetHits.name + "" --skipping file""); + fh.close(); + return 0; + } + if (isSelf) {// DIR_SELF + if (hit.queryHits.grpIdx < hit.targetHits.grpIdx) {hit.swapCoords(); cntSwap++;} // lower diagonal + + if (hit.queryHits.grpIdx == hit.targetHits.grpIdx && hit.queryHits.start < hit.targetHits.start) { + cntSkip++; continue; // mirror later; self hits are in file twice, once with start1 Group.FSplitLen) { + Globals.tprt("" split hit of size "" + hit.maxLength()); + Vector brokenHits = Hit.splitMUMmerHit(hit); + mTotalLargeHits++; + mTotalBrokenHits += brokenHits.size(); + rawHits.addAll(brokenHits); + } + else { + rawHits.add(hit); + } + if (failCheck()) {fh.close(); return 0;} + } + fh.close(); + + if (Globals.TRACE && isSelf) { + if (cntSkip>0) Utils.prtNumMsg(cntSkip, String.format("" skipped coords from %,8d "", hitNum) + Utils.fileFromPath(mFile.toString())); + else Utils.prtNumMsg(cntSwap, String.format("" swapped coords from %,8d "", hitNum) + Utils.fileFromPath(mFile.toString())); + } + String msg= String.format(""%,10d scanned %s %s"", hitNum, fileType, Utils.fileFromPath(mFile.toString())); + if (VB) Utils.prtMsgFile(plog, msg); else Globals.rprt(msg); + + if (hitNum==0 || mTotalHits==0) return 0; + + /** Scan1 processing: all hits get added to each grp; create non-genes (predicted); hit has start rawHits = new Vector(HIT_VEC_INC,HIT_VEC_INC); + try { + if (!VB) Globals.rprt(String.format(""Cluster %s"", Utils.fileFromPath(mFile.toString()))); + + BufferedReader fh = new BufferedReader(new FileReader(mFile)); + String line; + int errCnt=0; + + /** Read file and build rawHits **/ + while (fh.ready()) { + line = fh.readLine().trim(); + + if (line.length() == 0) continue; + if (!Character.isDigit(line.charAt(0))) continue; + + Hit hit = new Hit(); + hit.origHits = 1; + + boolean success = scanNextMummerHit(line,hit); + if (!success) { // should have already been caught in ScanFile1 + plog.msg("" Error in file "" + Utils.fileFromPath(mFile.toString())); + errCnt++; + if (errCnt>=5) Utils.die(""Too many errors""); + continue; + } + + hit.queryHits.grpIdx = p1.grpIdxFromQuery(hit.queryHits.name); + hit.targetHits.grpIdx = p2.grpIdxFromQuery(hit.targetHits.name); + + if (isSelf) {// DIR_SELF + if (hit.queryHits.grpIdx < hit.targetHits.grpIdx) hit.swapCoords(); + + if (hit.queryHits.grpIdx == hit.targetHits.grpIdx && hit.queryHits.start < hit.targetHits.start) continue; + } + + // The only section different from scanFile1, which makes a big difference for self-synteny + if (hit.isDiagHit()) { // Diagonal hits are handle separately + hit.status = HitStatus.In; + diagHits.add(hit); + continue; + } + + if (hit.maxLength() > Group.FSplitLen){ + Vector brokenHits = Hit.splitMUMmerHit(hit); // catches and prints error + if (brokenHits==null) {bSuccess=false; fh.close(); return 0;} + rawHits.addAll(brokenHits); + } + else { + rawHits.add(hit); + } + if (failCheck()) {fh.close(); return 0;} + } + fh.close(); + if (rawHits.size()==0) return 0; + + /** Scan2 processing ***/ + Vector clustHits = clusterHits2( rawHits ); if (!bSuccess) return 0; + rawHits.clear(); + Collections.sort(clustHits); + + filterClusterHits2(clustHits, p1, p2); if (!bSuccess) return 0; + + String msg= String.format(""%,10d clustered %s"", clustHits.size(), Utils.fileFromPath(mFile.toString())); + if (VB) Utils.prtMsgFile(plog, msg); else Globals.rprt(msg); + return clustHits.size(); + } + catch (Exception e) { + rawHits.clear(); + ErrorReport.print(e, ""scanFile2: Reading file for hits ""); + bSuccess=false; + return 0;} + } + + /********************************************************************* + * Cluster the mummer hits into larger hits using the annotations, including the ""non-genes"". [clusterGeneHits] + * So our possible hit set will now be a subset of annotations x annotations, and the + * actual length of the hits will be the sum of the subhits that went into them. + */ + private Vector clusterHits2(Vector inHits) throws Exception { + Vector outHits = new Vector(HIT_VEC_INC, HIT_VEC_INC); + + // all use key = qAnno.mID + ""_"" + tAnno.mID; + HashMap> pairMap = new HashMap>(); // all hits to the q-t pair + HashMap key2qAnno = new HashMap(); + HashMap key2tAnno = new HashMap(); + HashMap pairTypes = new HashMap(); + + try { + // Find all hits for each qAnno x tAnno; every hit has a gene or non-gene AnnotElem for q&t + for (Hit hit : inHits) { + Group grp1 = syProj1.getGrpByIdx(hit.queryHits.grpIdx); + Group grp2 = syProj2.getGrpByIdx(hit.targetHits.grpIdx); + + AnnotElem qAnno = grp1.getBestOlapAnno(hit.queryHits.start, hit.queryHits.end); // priority to gene annotElem + AnnotElem tAnno = grp2.getBestOlapAnno(hit.targetHits.start, hit.targetHits.end); + + // Self-synteny humans failed on this, especially Y chr + if (qAnno == null) {Globals.tprt(""missing query annot! grp:"" + grp1.idStr() + "" start:"" + hit.queryHits.start + "" end:"" + hit.queryHits.end); continue;} + if (tAnno == null) {Globals.tprt(""missing target annot! grp:"" + grp2.idStr() + "" start:"" + hit.targetHits.start + "" end:"" + hit.targetHits.end); continue;} + + String key = qAnno.mID + ""_"" + tAnno.mID; + + if (!pairMap.containsKey(key)) { + pairMap.put(key, new Vector()); + key2qAnno.put(key, qAnno); + key2tAnno.put(key, tAnno); + + if (!qAnno.isGene() && !tAnno.isGene()) { + pairTypes.put(key, HitType.NonGene); + } + else if (qAnno.isGene() && tAnno.isGene()) { + pairTypes.put(key, HitType.GeneGene); + } + else { + pairTypes.put(key, HitType.GeneNonGene); + } + } + pairMap.get(key).add(hit); + } + + // Merge the pair hits into a clustered hit + Hit.totalWS=0; + for (String key : pairMap.keySet()) { + Vector pairHits = pairMap.get(key); + AnnotElem qAnno = key2qAnno.get(key); + AnnotElem tAnno = key2tAnno.get(key); + + outHits.addAll(Hit.clusterHits2( pairHits, pairTypes.get(key), qAnno, tAnno)); + } + mTotalWS += Hit.totalWS; + return outHits; + } + catch (Exception e) { + outHits.clear(); pairMap.clear(); key2qAnno.clear();key2tAnno.clear(); pairTypes.clear(); + ErrorReport.print(e, ""cluster gene hits""); + bSuccess=false; + return null;} + } + /******************************************************** + * Add hits to their topN bins, applying the topN criterion immediately when possible to reduce memory + * Called from scanFile2; hits get transfered to respective project [preFilterHit2] + */ + private void filterClusterHits2(Vector clustHits, Proj p1, Proj p2) throws Exception { + try { + // Bin the annotated/candidate genes [syProj1.collectPGInfo]; + Vector grp1Vec = syProj1.getGroups(); + for (Group grp : grp1Vec) grp.createHitBinFromAnno2(syProj1.getName()); + + Vector grp2Vec = syProj2.getGroups(); + for (Group grp : grp2Vec) grp.createHitBinFromAnno2(syProj2.getName()); + + Vector theseDiag = new Vector(); + + for (Hit hit : clustHits) { + if (hit.isDiagHit()) { // not used in isSelf, could possibly happen in !isSelf + hit.status = HitStatus.In; + theseDiag.add(hit); + continue; + } + + // Add hit to group HitBin if passes filter + Group grp1 = p1.getGrpByIdx(hit.queryHits.grpIdx); + grp1.filterAddToHitBin2(hit, hit.queryHits.start, hit.queryHits.end); + + Group grp2 = p2.getGrpByIdx(hit.targetHits.grpIdx); + grp2.filterAddToHitBin2(hit, hit.targetHits.start, hit.targetHits.end); + } + if (theseDiag.size() > 0) { + Hit.mergeOlapDiagHits(theseDiag); + diagHits.addAll(theseDiag); + } + } + catch (Exception e) {ErrorReport.print(e, ""prefilter hits""); bSuccess=false;} + } + /*****************************************************************/ + private void filterFinalHits() { + try { + if (VB) plog.msg(""Filter hits""); else Globals.rprt(""Filter hits""); + + // final TopN filtering, and collect all the hits that pass on at least one side into the set ""hits"" + Vector group1Vec = syProj1.getGroups(); + for (Group grp1 : group1Vec) grp1.filterFinalAddHits(filtHitSet); // adds to filtHitSet vector + + Vector group2Vec = syProj2.getGroups(); + for (Group grp2 : group2Vec) grp2.filterFinalAddHits(filtHitSet); + + int nQueryIn = 0, nTargetIn = 0, nBothIn=0; + for (Hit h : filtHitSet) { + if (h.targetHits.status == HitStatus.In) nTargetIn++; + if (h.queryHits.status == HitStatus.In) nQueryIn++; + + if (h.queryHits.status == HitStatus.In && h.targetHits.status == HitStatus.In) { + h.status = HitStatus.In; + nBothIn++; + } + } + if (VB) { + Utils.prtNumMsg(plog, nQueryIn, ""for "" + proj1Name ); + Utils.prtNumMsg(plog, nTargetIn, ""for "" + proj2Name ); + } + Utils.prtNumMsg(plog, nBothIn, ""Filtered hits to save""); + + if (diagHits.size()>0) { + filtHitSet.addAll(diagHits); + if (Globals.TRACE) Utils.prtNumMsg(plog, diagHits.size(), "" diagonal hits ""); + } + } + catch (Exception e) {ErrorReport.print(e, ""filter hits""); bSuccess=false;} + } + /********************************************* + * 0 1 2 3 4 5 6 7 + * [S1] [E1] [S2] [E2] [LEN 1] [LEN 2] [% IDY] [% SIM] [% STP] [LEN R] [LEN Q] [FRM] [TAGS] + *15491 15814 20452060 20451737 324 324 61.11 78.70 1.39 73840631 37257345 2 -3 chr1 chr3 + * NUCMER does not have %SIM or %STP + * The file is pair.proj1idx_to_pair.proj2idx, where proj1idx.name=13 ""); + plog.msg("" Line: "" + line); + return false; + } + int poffset = (fs.length > 13 ? 2 : 0); // nucmer vs. promer + + int tstart = Integer.parseInt(fs[0]); + int tend = Integer.parseInt(fs[1]); + int qstart = Integer.parseInt(fs[2]); + int qend = Integer.parseInt(fs[3]); + int match = Math.max(Integer.parseInt(fs[4]), Integer.parseInt(fs[5])); + int pctid = Math.round(Float.parseFloat(fs[6])); + int pctsim = (isNucmer) ? 0 : Math.round(Float.parseFloat(fs[7])); + if (pctsim>110) pctsim=0; // in case mummer file does not have Nucmer header; + String targetChr = fs[11 + poffset]; + String queryChr = fs[12 + poffset]; + + String strand = (qstart <= qend ? ""+"" : ""-"") + ""/"" + (tstart <= tend ? ""+"" : ""-""); + + hit.setHit(queryChr, targetChr, qstart, qend, tstart, tend, match, pctid, pctsim, strand); + + return true; + } + /******************************************************************* + * XXX + */ + private void saveAllResults() throws Exception { + try { + if (Constants.VERBOSE) plog.msg(""Save results""); else Globals.rprt(""Save results""); + long memTime = Utils.getTimeMem(); + + Vector onlyFiltHits = new Vector (filtHitSet.size()); + for (Hit h : filtHitSet) + if (h.status == HitStatus.In) onlyFiltHits.add(h); // CAS575 add IN as WAS ignored later anyway + + Hit.sortByTarget(onlyFiltHits); + + saveFilterHits(onlyFiltHits, false); if (!bSuccess) return; + + if (isSelf) saveFilterHits(onlyFiltHits, true); if (!bSuccess) return; + + saveAnnoHits(); if (!bSuccess) return; + + if (Globals.TRACE) Utils.prtMsgTimeFile(plog, ""Complete save"", memTime); + } + catch (Exception e) {ErrorReport.print(e, ""save results""); throw e;} + } + /************************************************ + * Save hits + * if bMirror, self-synteny, mirror hits; add refidx and swap all 1-2 columns and query/target + */ + private void saveFilterHits(Vector filtHits, boolean bMirror) throws Exception { + try { + String msg = (bMirror) ? "" Save mirrored filtered hits "" : "" Save filtered hits ""; + msg += String.format(""%,d"", filtHits.size()); + if (VB) plog.msg(msg); else Globals.rprt(msg); + int numLoaded=0, countBatch=0; + + addIsSelfRefIdx(filtHits, bMirror); + + String sql = ""insert into pseudo_hits (pair_idx,""; + + if (!bMirror) sql += ""proj1_idx, proj2_idx, grp1_idx, grp2_idx,""; + else sql += ""proj2_idx, proj1_idx, grp2_idx, grp1_idx,""; + + sql += ""pctid, cvgpct, countpct, score, htype, gene_overlap, strand,""; + + if (!bMirror) sql += ""annot1_idx, annot2_idx, start1, end1, start2, end2, query_seq, target_seq, refidx)""; + else sql += ""annot2_idx, annot1_idx, start2, end2, start1, end1, target_seq, query_seq, refidx)""; + + PreparedStatement ps = tdbc2.prepareStatement(sql + + ""VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ""); + + for (Hit hit : filtHits) { + if (hit.htype==-1) continue; // isSelf self-chr diagonal; dotplot creates the diagonal + + String htype = ""g0""; // show on Query + int geneOlap = 0; + if (hit.mHT == HitType.GeneGene) {geneOlap = 2; htype=""g2"";} + else if (hit.mHT == HitType.GeneNonGene) {geneOlap = 1; htype=""g1"";} + + int i=1; + ps.setInt(i++, pairIdx); + ps.setInt(i++, syProj1.getIdx()); + ps.setInt(i++, syProj2.getIdx()); + ps.setInt(i++, hit.queryHits.grpIdx); + ps.setInt(i++, hit.targetHits.grpIdx); + + ps.setInt(i++, hit.pctid); // pctid Avg%Id + ps.setInt(i++, hit.pctsim); // cvgpct; unsigned tiny int; now Avg%Sim + ps.setInt(i++, (hit.queryHits.subHits.length/2)); // countpct; unsigned tiny int; now #SubHits + ps.setInt(i++, hit.matchLen); // score + ps.setString(i++, htype) ; // + ps.setInt(i++, geneOlap); // 0,1,2 + ps.setString(i++, hit.strand); + + ps.setInt(i++, hit.annotIdx1); + ps.setInt(i++, hit.annotIdx2); + ps.setInt(i++, hit.queryHits.start); + ps.setInt(i++, hit.queryHits.end); + ps.setInt(i++, hit.targetHits.start); + ps.setInt(i++, hit.targetHits.end); + + ps.setString(i++, intArrayToBlockStr(hit.queryHits.subHits)); + ps.setString(i++, intArrayToBlockStr(hit.targetHits.subHits)); + + ps.setInt(i++, hit.idx); // refidx + + ps.addBatch(); + countBatch++; numLoaded++; + if (countBatch==nLOOP) { + if (failCheck()) return; + countBatch=0; + ps.executeBatch(); + Globals.rprt(numLoaded + "" loaded""); + } + } + if (countBatch>0) ps.executeBatch(); + ps.close(); + } + catch (Exception e) {ErrorReport.print(e, ""save annot hits""); bSuccess=false;} + } + /************************************************ + * Since hit.idx is not entered, that class variable is used for refidx for the above save + * 1. refidx = 0 : for first time the hit is entered + * 2. refidx = idx of mirror hit: second time the hit is entered + */ + private void addIsSelfRefIdx(Vector filtHits, boolean bMirror) { // CAS575 new method for isSelf + for (Hit hit : filtHits) { + if (hit.queryHits.grpIdx==hit.targetHits.grpIdx + && hit.queryHits.start == hit.targetHits.start + && hit.queryHits.end == hit.targetHits.end) hit.htype = -1; + } + if (!bMirror) { + for (Hit hit : filtHits) hit.idx = 0; + return; + } + // swapped load + Vector loadHits = loadHitsFromDB(false); // get the idx of the hit entered before mirror; will be refidx in mirror + + HashMap idxMap = new HashMap (); + + for (Hit lht : loadHits) { // make idx map with loaded hits + String key = lht.queryHits.grpIdx + "":"" + lht.queryHits.start + "":"" + lht.queryHits.end + + lht.targetHits.grpIdx + "":"" + lht.targetHits.start + "":"" + lht.targetHits.end; + idxMap.put(key, lht.idx); + } + for (Hit fht: filtHits) { // transfer idx to filtered hits + if (fht.htype==-1) continue; // diagonal + + String key = fht.queryHits.grpIdx + "":"" + fht.queryHits.start + "":"" + fht.queryHits.end + + fht.targetHits.grpIdx + "":"" + fht.targetHits.start + "":"" + fht.targetHits.end; + if (!idxMap.containsKey(key)) ErrorReport.print(""Cannot get hit idx "" + key); + fht.idx = idxMap.get(key); + } + loadHits.clear(); + } + private String intArrayToBlockStr(int[] ia) { + String out = """"; + if (ia != null) { + for (int i = 0; i < ia.length; i+=2) { + out += ia[i] + "":"" + ia[i+1]; + if (i + 1 < ia.length - 1) + out += "",""; + } + } + return out; + } + // private void addMirroredHits() CAS575 changed to use saveFilterHits, which does not crash if schema is changed + + /*****************************************************/ + private void saveAnnoHits() { + String key=""""; + try { + if (VB) plog.msg("" Save hit to gene ""); else Globals.rprt("" Save hit to gene ""); + + /* Load hits from database, getting their new idx; */ + Vector vecHits = loadHitsFromDB(true); + if (failCheck()) return; + + /* save the query annotation hits, which correspond to syProj1 */ /* on self-synteny, get dups; */ + PreparedStatement ps = tdbc2.prepareStatement(""insert ignore into pseudo_hits_annot "" + + ""(hit_idx, annot_idx, olap, exlap, annot2_idx) values (?,?,?,?,?)""); + + int count=0, cntHit=0, cntBatch=0; + int [][] vals; + + for (Hit ht : vecHits) {// FIRST LOOP for Q + Group grp = syProj1.getGrpByIdx(ht.queryHits.grpIdx); + vals = grp.getAnnoHitOlapForSave(ht, ht.queryHits.start, ht.queryHits.end); + if (vals.length>0) cntHit++; + + for (int i=0; i 0) ps.executeBatch(); + if (cntHit>0) { + String m = String.format("" (%,d) for %s"", count, proj1Name); + if (VB) Utils.prtNumMsg(plog, cntHit, m+"" ""); else Globals.rprt(cntHit + m); + } + if (failCheck()) return; + + /* save the target annotation hits */ + cntHit=cntBatch=0; + for (Hit ht : vecHits) { // SECOND LOOP for T + Group grp = syProj2.getGrpByIdx(ht.targetHits.grpIdx); + + vals = grp.getAnnoHitOlapForSave(ht, ht.targetHits.start, ht.targetHits.end); + if (vals.length>0) cntHit++; + + for (int i=0; i0) ps.executeBatch(); + ps.close(); + if (!isSelf && cntHit>0) { + String m = String.format("" (%,d) for %s"", count,proj2Name); + if (VB) Utils.prtNumMsg(plog, cntHit, m+"" ""); else Globals.rprt(cntHit + m); + } + if (failCheck()) return; + } + catch (Exception e) {ErrorReport.print(e, ""save annot hits "" + key); bSuccess=false;} + } + + // Used by saveAnnoHits (gene only) and self-synteny addRefIdx (all) + private Vector loadHitsFromDB(boolean bGene) { + try { + Vector vecHits = new Vector (filtHitSet.size()); + String st = ""SELECT idx, start1, end1, start2, end2, strand, grp1_idx, grp2_idx, annot1_idx, annot2_idx"" + + "" FROM pseudo_hits WHERE pair_idx="" + pairIdx; + if (bGene) st+= "" and gene_overlap>0""; + + ResultSet rs = tdbc2.executeQuery(st); + while (rs.next()) { + Hit h = new Hit(); + h.idx = rs.getInt(1); + h.queryHits.start = rs.getInt(2); + h.queryHits.end = rs.getInt(3); + h.targetHits.start = rs.getInt(4); + h.targetHits.end = rs.getInt(5); + h.strand = rs.getString(6); + h.queryHits.grpIdx = rs.getInt(7); + h.targetHits.grpIdx = rs.getInt(8); + h.annotIdx1 = rs.getInt(9); + h.annotIdx2 = rs.getInt(10); + h.isRev = (h.strand.contains(""-"") && h.strand.contains(""+"")); + vecHits.add(h); + } + rs.close(); + return vecHits; + } + catch (Exception e) {ErrorReport.print(e, ""get Hits""); bSuccess=false; return null;} + } + /********************************************/ + private boolean failCheck() { + if (Cancelled.isCancelled() || mainObj.bInterrupt) { + if (mainObj.bInterrupt) plog.msg(""Process was interrupted""); + else plog.msg(""Process was cancelled""); + bSuccess=false; + return true; + } + return false; + } + private boolean rtError(String msg) { + plog.msg(msg); + ErrorCount.inc(); + bSuccess=false; + return false; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/Hit.java",".java","16581","489","package backend.anchor1; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Vector; + +import backend.Utils; +import symap.Globals; +import util.ErrorReport; + +/***************************************************** + * Used for AnchorsMain: a hit may be a MUMmer hit or a clustered hit SubHit>0. + */ +public class Hit implements Comparable { + protected static final boolean FcheckRev = true; // Only cluster hits of the same orientation (--,++) and (+-,+-) + protected static final int FhaveNSubs=2, FhaveLen1=300, FhaveLen2=100; // >= heuristics; used in Hit/HitBin for filtering + + protected int hitLen=0; + protected int matchLen, pctid, pctsim, idx; // bestLen(T,Q), pctid=%ID, pctsim=%sim from MUMmer per subhit + protected String strand; + protected int annotIdx1 = 0, annotIdx2 = 0; + protected int nSubHits=0; + + protected SubHit queryHits, targetHits; + protected HitType mHT = null; // AnchorsMain1 {GeneGene, GeneNonGene, NonGene} + protected int htype=0; + + protected HitStatus status = HitStatus.Undecided; // AnchorsMain1 {In, Out, Undecided }; + + protected int origHits = 0; + protected int binsize1=0, binsize2=0; // store topN bin sizes for stats + + protected boolean isRev=false; + + // Called in AnchorMain + protected Hit() { + this(0); // single hit, i.e. not clustered + } + + // Called in AnchorMain1.scanNextMummerHit + protected void setHit(String query, String target, int qstart, int qend, int tstart, int tend, int match, + int pctid, int pctsim, String strand) { + this.queryHits.name = query.intern(); + this.queryHits.start = qstart; + this.queryHits.end = qend; + + this.targetHits.name = target.intern(); + this.targetHits.start = tstart; + this.targetHits.end = tend; + + this.matchLen = match; // best of T and Q mummer reported length + this.pctid = pctid; + this.pctsim = pctsim; + this.strand = strand.intern(); // reduce hit memory footprint + + isRev = strand.contains(""-"") && strand.contains(""+""); + + int s = queryHits.start; int e = queryHits.end; + queryHits.start = (s < e ? s : e); + queryHits.end = (s < e ? e : s); + + s = targetHits.start; e = targetHits.end; + targetHits.start = (s < e ? s : e); + targetHits.end = (s < e ? e : s); + } + protected void swapCoords() {// isSelf - if sequences are in different files, grp1_idx h2.queryHits.start) return -1; + + if (targetHits.start < h2.targetHits.start)return 1; + else if (targetHits.start > h2.targetHits.start)return -1; + + return 0; + } + // called by HitBin on filtering clustered hit; if false, they may still be used if topN + protected boolean useAnnot() { + if (annotIdx1 > 0 && annotIdx2 > 0) { + if (matchLen>FhaveLen2) return true; + } + if (annotIdx1 > 0 || annotIdx2 > 0) { + if (nSubHits>=FhaveNSubs || matchLen>=FhaveLen1) return true; + } + return false; + } + protected boolean useAnnot2() { + if (annotIdx1 > 0 && annotIdx2 > 0) { + if (matchLen>FhaveLen2) return true; + } + return false; + } + protected boolean useAnnot1() { + if (annotIdx1 > 0 || annotIdx2 > 0) { + if (nSubHits>=FhaveNSubs || matchLen>=FhaveLen1) return true; + } + return false; + } + + protected int maxLength() { + return Math.max(queryHits.length(), targetHits.length()); + } + protected boolean isDiagHit() { + return queryHits.grpIdx == targetHits.grpIdx && queryHits.start == targetHits.start && queryHits.end == targetHits.end; + } + // for debug + protected String getInfo() { + return String.format(""GrpIdx %2d %2d Query %,10d %,10d Target %,10d %,10d "", + queryHits.grpIdx, targetHits.grpIdx, queryHits.start, queryHits.end, targetHits.start, targetHits.end); + } + /**************************************************************** + * mergeOlapDiagHits methods + */ + private void merge(Hit h) { + this.queryHits.grpIdx = h.queryHits.grpIdx; + this.queryHits.start = Math.min(h.queryHits.start, this.queryHits.start); + this.queryHits.end = Math.max(h.queryHits.end, this.queryHits.end); + this.targetHits.grpIdx = h.targetHits.grpIdx; + this.targetHits.start = Math.min(h.targetHits.start, this.targetHits.start); + this.targetHits.end = Math.max(h.targetHits.end, this.targetHits.end ); + + if (h.origHits>1) System.out.println(""Orig "" + h.origHits); + this.origHits += h.origHits; + + this.matchLen = this.queryHits.end - this.queryHits.start; + this.pctid = (this.pctid == 0 ? h.pctid : (this.pctid + h.pctid) / 2); + this.pctsim = (this.pctsim == 0 ? h.pctsim : (this.pctsim + h.pctsim) / 2); + } + private boolean isOverlapping(Hit h) { + return (this.queryHits.isOverlapping(h.queryHits) && + this.targetHits.isOverlapping(h.targetHits)); + } + + private boolean sameStrand(Hit h) { + return (strand == null && h.strand == null) || (strand.equals(h.strand)); + } + + /******************************************************************* + * XXX STATIC - manipulation of hits + ********************************************************************/ + /******************************************************************* + * Break the hit into pieces, taking care to not leave a tiny leftover hit, and for + * cases where query and target are different lengths (maybe not possible with mummer). + * Note, hits have been previously fixed so start < end. [AnchorMain.breakHit] + */ + static protected Vector splitMUMmerHit(Hit hit) { + try { + int fSplitLen = Group.FSplitLen; + + Vector ret = new Vector(); + + int minLeftover = fSplitLen/10; + + int qlen = hit.queryHits.length(); + int tlen = hit.targetHits.length(); + + int qleft = qlen%fSplitLen; + int tleft = tlen%fSplitLen; + + int qparts = (qleft >= minLeftover ? (1 + qlen/fSplitLen) : (qlen/fSplitLen)); + int tparts = (tleft >= minLeftover ? (1 + tlen/fSplitLen) : (tlen/fSplitLen)); + + int parts = Math.min(qparts,tparts); + int qhStart=hit.queryHits.start, qhEnd=hit.queryHits.end; + int thStart=hit.targetHits.start, thEnd=hit.targetHits.end; + + if (parts == 1) { + hit.idx=6; + ret.add(hit); + } + else if (!hit.isRev) { // build (parts-1) hits of fixed size, and put the rest into the final hit + for (int i = 1; i < parts; i++) { + int qstart = qhStart + fSplitLen * (i-1); + int qend = qstart + fSplitLen - 1; + int tstart = thStart + fSplitLen * (i-1); + int tend = tstart + fSplitLen - 1; + Hit h = new Hit(hit, qstart, qend, tstart, tend, 1); + ret.add(h); + } + int qstart = qhStart + fSplitLen * (parts-1); + int tstart = thStart + fSplitLen * (parts-1); + + Hit h = new Hit(hit, qstart, qhEnd, tstart, thEnd, 2); + ret.add(h); + } + else if (hit.isRev) {// forward through the query, backward through target + for (int i = 1; i < parts; i++) { + int qstart = qhStart + fSplitLen * (i-1); + int qend = qstart + fSplitLen - 1; + int tend = thEnd - fSplitLen * (i-1); + int tstart = tend - fSplitLen + 1; + Hit h = new Hit(hit, qstart, qend, tstart, tend, 3); + ret.add(h); + } + int qstart = qhStart + fSplitLen*(parts-1); + int tend = thEnd - fSplitLen*(parts-1); + + Hit h = new Hit(hit, qstart, qhEnd, thStart, tend, 4); + ret.add(h); + } + return ret; + } + catch (Exception e) {ErrorReport.print(e, ""Split MUMmer hit""); return null;} + } + /****************************************************************** + * to merge hit lists; CAS575 still merges, but does not save + * called in AnchorsMain.preFilterHits2 + * not a complete merge b/c doesn't ever merge two clusters + */ + protected static void mergeOlapDiagHits(Vector hits) { + if (hits.size() <= 1) return; + + Vector mergedHits = new Vector(); + for (Hit h1 : hits) { + boolean overlap = false; + + for (Hit h2 : mergedHits) { + // sameStrand test b/c otherwise we can't label the orientation of the hits. + // show-coords -k should take care of most of the wrong-strand problem + if ( h1.sameStrand(h2) && h1.isOverlapping(h2) ) { + overlap = true; + h2.merge(h1); + break; // WMN what if it hits two? + } + } + if (!overlap) + mergedHits.add(h1); + } + + if (mergedHits.size() < hits.size()) { + hits.clear(); + hits.addAll(mergedHits); + } + } + /*************************************************************** + * called in AnchorsMain.clusterHits2 + */ + protected static int totalWS=0; + protected static Vector clusterHits2(Vector hitVec, HitType htype, AnnotElem qAnno, AnnotElem tAnno) throws Exception { + Vector retHits = new Vector (); + if (hitVec.size()==0) return retHits; + + Vector rHits = new Vector (); + Vector sHits = new Vector (); + for (Hit ht : hitVec) { + if (FcheckRev) { + if (ht.isRev) rHits.add(ht); + else sHits.add(ht); + } + else rHits.add(ht); + } + // heuristic: if same/diff orient, only make clusters of both if the both have >2 subhits + int r=rHits.size(), s=sHits.size(); + if (r>=s || r>2) retHits.addAll(clusterCreate(rHits, htype, qAnno, tAnno)); + if (s>=r || s>2) retHits.addAll(clusterCreate(sHits, htype, qAnno, tAnno)); + + return retHits; + } + private static Vector clusterCreate(Vector hitVec, HitType htype, AnnotElem qAnno, AnnotElem tAnno) throws Exception { + Vector retHits = new Vector (); + int numHits = hitVec.size(); + + if (numHits==0) return null; + + if (numHits == 1) { + Hit h = hitVec.firstElement(); + h.mHT = htype; + h.nSubHits = 1; + if (qAnno.isGene()) h.annotIdx1 = qAnno.idx; + if (tAnno.isGene()) h.annotIdx2 = tAnno.idx; + setStrand(h, qAnno, tAnno, 1); + retHits.add(h); + return retHits; + } + + // Process list + Hit clHit = new Hit( numHits*2 ); + clHit.mHT = htype; + if (qAnno.isGene()) clHit.annotIdx1 = qAnno.idx; + if (tAnno.isGene()) clHit.annotIdx2 = tAnno.idx; + + clHit.nSubHits=numHits; + clHit.queryHits.grpIdx = hitVec.get(0).queryHits.grpIdx; + clHit.targetHits.grpIdx = hitVec.get(0).targetHits.grpIdx; + clHit.strand = hitVec.get(0).strand; + setStrand(clHit, qAnno, tAnno, numHits); + + clHit.matchLen = clHit.origHits = 0; + int i = 0; + double sumPctID = 0, sumPctSim = 0, sumMatch=0; + int qSlast=0, qElast=0, tSlast=0, tElast=0, tMatch=0, qMatch=0; + + sortByQuery(hitVec); + + for (Hit sh : hitVec) { + clHit.queryHits.subHits[i] = sh.queryHits.start; + clHit.targetHits.subHits[i] = sh.targetHits.start; + i++; + + clHit.queryHits.subHits[i] = sh.queryHits.end; + clHit.targetHits.subHits[i] = sh.targetHits.end; + i++; + + clHit.queryHits.start = Math.min(sh.queryHits.start, clHit.queryHits.start); + clHit.queryHits.end = Math.max(sh.queryHits.end, clHit.queryHits.end); + clHit.targetHits.start = Math.min(sh.targetHits.start, clHit.targetHits.start); + clHit.targetHits.end = Math.max(sh.targetHits.end, clHit.targetHits.end ); + + clHit.origHits += sh.origHits; + + sumPctSim += sh.pctsim * sh.matchLen; + sumPctID += sh.pctid * sh.matchLen; + sumMatch += sh.matchLen; + + // Compute subhit length for query + int qM = (sh.queryHits.end - sh.queryHits.start + 1); + if (qMatch>0) { + int qolap = Utils.intervalsOverlap(sh.queryHits.start, sh.queryHits.end, qSlast, qElast); + if (qolap<0) qMatch += qM; + else qMatch += (qM-qolap); + } + else qMatch = qM; + qSlast = sh.queryHits.start; qElast=sh.queryHits.end; + } + clHit.pctid = (int) Math.round(sumPctID/sumMatch); + clHit.pctsim = (int) Math.round(sumPctSim/sumMatch); + + // Compute subhit length for target + sortByTarget(hitVec); + for (Hit sh : hitVec) { + int tM = (sh.targetHits.end - sh.targetHits.start + 1); + + int tolap = Utils.intervalsOverlap(sh.targetHits.start, sh.targetHits.end, tSlast, tElast); + if (tolap<0) tMatch += tM; + else tMatch += (tM-tolap); + tSlast = sh.targetHits.start; tElast=sh.targetHits.end; + } + clHit.matchLen = Math.max(tMatch, qMatch); // take best + + retHits.add(clHit); + return retHits; + } + /***************************************************** + * make hit strands correspond to genes + * ht.isRev is +/- or -/+; anno.isRev is - + */ + private static void setStrand(Hit ht, AnnotElem qAnno, AnnotElem tAnno, int numHits) { + ht.isRev = ht.strand.contains(""+"") && ht.strand.contains(""-""); + if (!qAnno.isGene() && !tAnno.isGene()) return; + + boolean bHtEQ = !ht.isRev; + + if (qAnno.isGene() && tAnno.isGene()) { + String ts = (tAnno.isRev) ? ""-"" : ""+""; + String qs = (qAnno.isRev) ? ""-"" : ""+""; + boolean isGnEQ = ts.equals(qs); + + if (bHtEQ!=isGnEQ) {// this is still processed + if (Globals.TRACE && numHits>3 && totalWS<1) { + String msg = String.format(""%2d subhits cluster (%s) for Q gene %6d (%s) and T %6d (%s)"", + numHits, ht.strand, qAnno.genenum, qs, tAnno.genenum, ts); + System.out.println(msg); + } + if (numHits>3) totalWS++; + } + else ht.strand = qs + ""/"" + ts; + } + else if (qAnno.isGene()) { + String qs = (qAnno.isRev) ? ""-"" : ""+""; + if (!bHtEQ) ht.strand = qs + ""/"" + qs; + else if (qs.equals(""+"")) ht.strand = ""+/-""; + else ht.strand = ""-/+""; + } + else if (tAnno.isGene()) { + String ts = (tAnno.isRev) ? ""-"" : ""+""; + if (!bHtEQ) ht.strand = ts + ""/"" + ts; + else if (ts.equals(""+"")) ht.strand = ""-/+""; + else ht.strand = ""+/-""; + } + } + /*********************************************************/ + protected static void sortByTarget(Vector hits) { // AnchorMain saveResults + Collections.sort(hits, + new Comparator() { + public int compare(Hit h1, Hit h2) { + return h1.targetHits.start - h2.targetHits.start; + } + } + ); + } + protected static void sortByQuery(Vector hits) { // clusterHits2 + Collections.sort(hits, + new Comparator() { + public int compare(Hit h1, Hit h2) { + return h1.queryHits.start - h2.queryHits.start; + } + } + ); + } + /*************************************************************** + ***************************************************************/ + protected class SubHit { + protected int start, end, score, grpIdx = 0; + protected String name; + protected int[] subHits; // set in clusterHits; array of sub-hits start/end coordinates; + protected HitStatus status = HitStatus.Undecided; // AnchorsMain {In, Out, Undecided }; + + protected SubHit(SubHit h) { + end = h.end; + start = h.start; + grpIdx = h.grpIdx; + name = h.name; + status = h.status; + subHits = new int[h.subHits.length]; + for (int i = 0; i < subHits.length; i++) subHits[i] = h.subHits[i]; + } + + protected SubHit(int numSubs) { + subHits = new int[numSubs]; + } + + public String toString() { + String s = """"; + for (int i = 0; i < subHits.length - 1; i+=2) + s += subHits[i] + "":"" + subHits[i+1] + "",""; + return s; + } + + protected int length() { return (Math.abs(end-start)+1); } + + protected boolean isOverlapping(SubHit h) { + return Utils.intervalsTouch(this.start, this.end, h.start, h.end); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/Group.java",".java","13240","416","package backend.anchor1; + +import java.util.TreeSet; +import java.util.HashSet; +import java.util.TreeMap; +import java.util.HashMap; +import java.util.Vector; + +import backend.Constants; + +import java.sql.ResultSet; + +import database.DBconn2; +import symap.Globals; +import util.ErrorReport; + +/** + * Called in Proj to load all groups + * Mainly used by AnchorMain - creates non-genes from hits that do not overlap genes + */ +public class Group { + public static boolean bSplitGene=false;// split hit/gene if true; -sg will split + + protected static final int FSplitLen = 50000; + private static final int FAnnotBinSize = 30000; // annoSetMap + private static final int FHitBinSize = 10000; // hitBinMap + private static final int FMaxHitAnno = 100000; + + protected int avgGeneLen = 1000, maxGeneLen = 50000; // use these defaults if no anno for project + + protected int idx; + protected String fullname; // displayName + chrName with prefix + private String chrName; // prefix removed + private QueryType mQT; // AnchorsMain { Query, Target, Either }; + + // Created during scan1 to create annotSetMap; then finish with create hitBinMap from annos + private TreeMap annoSetMap; // list of AnnoSet (of AnnotElems) per b; fast lookup + private HashSet annoElemSet; // list of AnnotElem (Gene, non-gene, n/a) + + // Created during scan2 to create cluster hits + private TreeMap> hitBinMap; // list of HitBin containing Hits per b + private Vector hitBins; // list of HitBin containing Hits + + private int topN = 0; + + protected Group(int topN, String name, String fullname, int idx, int qType) { + this.topN = topN; + this.chrName = name; + this.fullname = fullname; + this.idx = idx; + + if (qType==Constants.QUERY) this.mQT = QueryType.Query; + else if (qType==Constants.TARGET) this.mQT = QueryType.Target; + else this.mQT = QueryType.Either; + + annoElemSet = new HashSet (); + annoSetMap = new TreeMap(); + hitBins = new Vector(); + hitBinMap = new TreeMap>(); + } + + protected String idStr() { return """" + idx + ""("" + chrName + "")"";} // AnchorMain1.clusterHits2 + + /******************* ANNO BINS ******************************/ + /************************************************************ + * Called from AnchorsMain1.loadAnnoBins [loadAnnotation] + */ + protected int createAnnoFromGenes(DBconn2 dbc2) { + try { + HashSet idxSplit = new HashSet (); + ResultSet rs; + + if (bSplitGene) { + rs = dbc2.executeQuery(""SELECT idx, start, end, genenum, (end-start) as len FROM pseudo_annot "" + + "" WHERE grp_idx="" + idx + "" and type ='gene' order by genenum, len DESC""); + int lastIdx=0, lastStart=0, lastEnd=0, lastGN=-1, lastCnt=0; + while (rs.next()) { + int idx = rs.getInt(1); + int s = rs.getInt(2); + int e = rs.getInt(3); + int g = rs.getInt(4); + if (lastGN!=g) { + if (lastCnt>1) idxSplit.add(lastIdx); + lastIdx=idx; lastStart=s; lastEnd=e; lastGN=g; lastCnt=0; + } + else if (lastGN==g) { + if (isContained(lastStart, lastEnd, s, e)) lastCnt++; + } + } + } + avgGeneLen = maxGeneLen = 0; + int totalGenes = 0; + + rs = dbc2.executeQuery(""SELECT idx, start, end, strand, genenum FROM pseudo_annot "" + + "" WHERE grp_idx="" + idx + "" and type ='gene'""); + while (rs.next()){ + int annotIdx = rs.getInt(1); + int s = rs.getInt(2); + int e = rs.getInt(3); + boolean isRev = rs.getString(4).contentEquals(""-""); + int gn = rs.getInt(5); + + int len = (e-s+1); + if (idxSplit.contains(annotIdx)) { + int minLeftover = FSplitLen/10; + int left = len%FSplitLen; + int parts = (left >= minLeftover ? (len/FSplitLen +1) : (len/FSplitLen)); + + for (int i = 1; i < parts; i++) { + int start = s + FSplitLen*(i-1); + int end = start + FSplitLen - 1; + AnnotElem ae = new AnnotElem(annotIdx, start, end, isRev, gn, GeneType.Gene); + updateAnnotBins(ae); + } + int start = s + FSplitLen * (parts-1); + AnnotElem ae = new AnnotElem(annotIdx, start, e, isRev, gn, GeneType.Gene); + updateAnnotBins(ae); + } + else { + AnnotElem ae = new AnnotElem(annotIdx, s, e, isRev, gn, GeneType.Gene); + updateAnnotBins(ae); + } + + int length = (e-s+1); + avgGeneLen += length; + maxGeneLen = Math.max(maxGeneLen, length); + totalGenes++; + } + rs.close(); + if (totalGenes > 0) { + avgGeneLen /= totalGenes; + maxGeneLen = Math.min(maxGeneLen, FMaxHitAnno); // still need a limit on this; use 100k + } + if (maxGeneLen==0) maxGeneLen=50000; + if (avgGeneLen==0) avgGeneLen=1000; + if (Globals.TRACE) System.out.println(""avg: "" + avgGeneLen + "" max: "" + maxGeneLen + "" "" + fullname); + return totalGenes; + } + catch (Exception e) {ErrorReport.print(e, ""load genes and bin them""); return 0;} + } + + /*********************************************************** + * AnchorMain1.scanFile1 + */ + protected void createAnnoFromHits1(int hstart, int hend, boolean isRev) { + int bs = Math.max((hstart - avgGeneLen)/FAnnotBinSize, 0); + int be = (hend + avgGeneLen)/FAnnotBinSize; + + int newStart = hstart, newEnd = hend; + TreeSet ngOlaps = new TreeSet(); + + for (int b = bs; b <= be; b++) { + HashSet list = getAnnoBinList(b); + if (list==null) continue; + + for (AnnotElem ae : list) { + int olap = getOlap(hstart, hend, ae.start, ae.end); + if (ae.isGene()){ + if (olap > 0) return; // Have an anno already from a gene + } + else { + if (olap > -avgGeneLen) { // create a bin to catch overlapping and close hits + int tryStart = Math.min(newStart, ae.start); + int tryEnd = Math.max(newEnd, ae.end); + if (!overlapGene(tryStart, tryEnd)) { + ngOlaps.add(ae); + newStart = tryStart; + newEnd = tryEnd; + } + } + } + } + } + + if (ngOlaps.size() == 1 ){ + if (ngOlaps.first().start <= hstart && ngOlaps.first().end >= hend) return; + } + + // remove all hits that are covered by newStart, newEnd + for (AnnotElem ae : ngOlaps) removeAnnotation(ae); + + // add one or more new ones spanning the region + for (int s = newStart; s < newEnd; s += maxGeneLen){ + int e = Math.min(newEnd, s + maxGeneLen - 1); + AnnotElem ae = new AnnotElem(0, s, e, isRev, 0, GeneType.NonGene); + updateAnnotBins(ae); + } + } + private boolean overlapGene(int hstart, int hend){ + int bs = hstart/FAnnotBinSize; + int be = hend/FAnnotBinSize +1; + + for (int b = bs; b <= be; b++) { + HashSet list = getAnnoBinList(b); + if (list==null) continue; + + for (AnnotElem ae : list) { + if (!ae.isGene()) continue; + + int overlap = getOlap(hstart, hend, ae.start, ae.end); + if (overlap>=0) return true; + } + } + return false; + } + private void removeAnnotation(AnnotElem ae){ + annoElemSet.remove(ae); + + int bs = ae.start/FAnnotBinSize; + int be = ae.end/FAnnotBinSize; + + for (int b = bs; b <= be; b++) { + if (annoSetMap.containsKey(b) ) { + AnnotSet as = annoSetMap.get(b); + as.remove(ae); + } + } + } + // used by both createAnnoFromGenes and createAnnoFromHits + private void updateAnnotBins(AnnotElem a) { + annoElemSet.add(a); + + int bs = a.start/FAnnotBinSize; // since 30k, start and end usually the same + int be = a.end/FAnnotBinSize; + for (int b = bs; b <= be; b++) { + AnnotSet as; + if (!annoSetMap.containsKey(b) ) { + as = new AnnotSet(); + annoSetMap.put(b, as); + } + else as = annoSetMap.get(b); + + as.add(a); + } + } + // For getBestOlapAnno for clustering and getAnnoHitOlapForSave + private HashMap getAllOlapAnnos(int hstart, int hend){ + int bs = hstart/FAnnotBinSize; + int be = hend/FAnnotBinSize +1; + + HashMap retMap = new HashMap(); + + for (int b = bs; b <= be; b++) { + HashSet list = getAnnoBinList(b); + if (list==null) continue; + + for (AnnotElem ae : list) { + + int overlap = getOlap(hstart, hend, ae.start, ae.end); + + if (overlap >= 0) { + if (!retMap.containsKey(ae) || overlap > retMap.get(ae)) + retMap.put(ae, overlap); + } + } + } + return retMap; + } + + /***************************************************************************** + * called from AnchorMain.clusterHits2 while clustering hits into subhits + */ + protected AnnotElem getBestOlapAnno(int hStart, int hEnd) { + AnnotElem best = null; + int bestOlap=0, curOlap=0; + + HashMap annoMap = getAllOlapAnnos(hStart, hEnd); + + for (AnnotElem cur : annoMap.keySet()) { + curOlap = annoMap.get(cur); + + if (best == null ) { // first time + best = cur; + bestOlap = curOlap; + continue; + } + + if (!cur.isGene() && best.isGene()) continue; + + if (cur.isGene() && !best.isGene()) { + best = cur; + bestOlap = curOlap; + continue; + } + + // either both are genes or both are not + if (curOlap > bestOlap) { + best = cur; + bestOlap = curOlap; + } + else if (curOlap == bestOlap) { + int curExtra = Math.abs(hStart-cur.start) + Math.abs(hEnd-cur.end); + int bestExtra = Math.abs(hStart-best.start) + Math.abs(hEnd-best.end); + if (curExtra vals = getAllOlapAnnos(start, end); + int [][] retVals = new int [vals.size()][4]; + int i=0; + for (AnnotElem ae : vals.keySet()) { + retVals[i][0] = ht.idx; + retVals[i][1] = ae.idx; + + double dolap = (double) vals.get(ae); + dolap = (dolap/(double)(ae.end-ae.start)) *100.0; + retVals[i][2] = (int) Math.round(dolap); + + if (ht.annotIdx1==ae.idx) retVals[i][3]=ht.annotIdx2; + else if (ht.annotIdx2==ae.idx) retVals[i][3]=ht.annotIdx1; + i++; + } + return retVals; + } + catch (Exception e) {ErrorReport.print(e, ""getting annotation overlaps""); throw e; } + } + /********************* HIT BINS *******************************/ + /*************************************************************** + * called after scanFile1 + * AnnotElem 1-to-1 with HitBin; then HitBin is put in hitBinMap, which has more entries than HitBin + */ + protected void createHitBinFromAnno2(String proj){ + for (AnnotElem ae : annoElemSet) { + HitBin hb = new HitBin(ae.start, ae.end, ae.mGT, topN, mQT); + hitBins.add(hb); + + int bs = ae.start/FHitBinSize; + int be = ae.end/FHitBinSize; + + for (int b = bs; b <= be; b++){ + if (!hitBinMap.containsKey(b)) hitBinMap.put(b, new Vector()); + hitBinMap.get(b).add(hb); + } + } + } + + /*********************************************************************** + * AnchorMain.filterClusterHits2; add to HitBin with best overlap if pass filters [checkAddToHitBin2] + ***************************************************************/ + protected void filterAddToHitBin2(Hit hit, int start, int end) throws Exception { // query/target start end + int bs = start/FHitBinSize; + int be = end/FHitBinSize; + HitBin hbBest = null; + int bestOlap = 0; + + // find best HitBin; whether this gets filtered or not depends on what is already in HitBin + // Multiple HitBins can have same AnnoHits + for (int b = bs; b <= be; b++) { + if (!hitBinMap.containsKey(b)) continue; // should not happen because all added earlier + + for (HitBin hbin : hitBinMap.get(b)) { + int olap = getOlap(hbin.start, hbin.end, start, end); + + if (olap <= 0) continue; + + if (olap > bestOlap) { // always true for 1st + hbBest = hbin; + bestOlap = olap; + } + else if (olap == bestOlap) { + if (hbin.start < hbBest.start || + (hbin.start== hbBest.start && hbin.end > hbBest.end)){ + hbBest = hbin; + bestOlap = olap; + } + } + } + } + // Filter + if (hbBest != null) + hbBest.filterAddHit2(hit, start, end); + else + System.err.println(""SyMAP error: filterAddtoHitBin "" + start + "" "" + end); + } + + // Called from AnchorMain1 to add this groups filtered hits to the main hashset + protected void filterFinalAddHits(HashSet finalHits) throws Exception { + for (HitBin hb : hitBins){ + hb.filterFinalAddHits(finalHits); + } + } + private boolean isContained(int s1,int e1, int s2, int e2){ + return (s2 >= s1 && e2 <= e1); + } + private int getOlap(int s1,int e1, int s2, int e2) { + int gap = Math.max(s1,s2) - Math.min(e1,e2); + return -gap; + } + + /** annoSetMap methods **/ + private HashSet getAnnoBinList(int bin) {// called by createAnnoFromHits and getAllOlapAnnos + if (annoSetMap.containsKey(bin)) return annoSetMap.get(bin).mList; + return null; // this happens a lot + } + + private class AnnotSet { + private HashSet mList; + + private AnnotSet() {mList = new HashSet();} + private void add(AnnotElem ae) {mList.add(ae);} + private void remove(AnnotElem ae){mList.remove(ae);} + } + protected String getInfo() { + return String.format(""%5s AnnoSetMap %,5d ElemSet %,5d hitBinMap %,5d HitBins %,5d"", + chrName, annoSetMap.size(), annoElemSet.size(), hitBinMap.size(), hitBins.size()); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/HitBin.java",".java","4161","135","package backend.anchor1; + +import java.util.Vector; + +import java.util.Comparator; +import java.util.HashSet; +import java.util.Collections; + +/***************************************************************** +// Represents a group of binned cluster hits along a group. +// Or the set of hits of a particular query (e.g. gene). CAS575 removed BinStat code +**********************************************************/ + +public class HitBin { + private final static double FperBin=backend.Constants.FperBin; // 0.8*matchLen top piles to save + protected int start, end; + protected GeneType mGT = GeneType.NA;// AnchorsMain {Gene, NonGene, NA} + private QueryType mQT; // AnchorsMain {Query, Target, Either }; + private int mTopN=0; + + protected int mHitsConsidered = 0, nHitsRemoved = 0; + + private Vector mHits; + private int mMinMatch = 0; // lowest matchLen of mHits; will not consider anything lower + + // Group.createHitBin1; place holders + protected HitBin(int start, int end, GeneType mGT, int topn, QueryType qt) { + this.start = start; + this.end = end; + this.mGT = mGT; + this.mQT = qt; + this.mTopN = topn; + + mHits = new Vector(topn,2); + } + // Group.filterAddToHitBin2 + protected HitBin(Hit h, int start, int end, int topn, QueryType qt) { + this.mMinMatch = h.matchLen; + this.start = start; + this.end = end; + this.mTopN = topn; + this.mQT = qt; + + mHits = new Vector(topn,2); + mHits.add(h); + + mHitsConsidered = 1; + } + /**************************************************************** + * Called from Group + ************************************************************/ + protected void filterAddHit2(Hit hit, int shStart, int shEnd) { + mHitsConsidered++; + + if (mHits.size() >= mTopN && hit.matchLen < mMinMatch && !hit.useAnnot()) return; + + mHits.add(hit); + start = Math.min(start, shStart); + end = Math.max(end, shEnd); + Collections.sort(mHits, new CompareByMatch()); // ascending hasAnnot or matchLen + + int topNmatch=0; + + if (mHits.size() >= mTopN+2) { + topNmatch = mHits.get(mTopN-1).matchLen; // if Top2=2, then 2nd highest length + topNmatch = (int) Math.round(topNmatch * FperBin); + + for (int i = mHits.size()-1; i>=mTopN; i--) { + Hit h = mHits.get(i); + + if (h.matchLen <= topNmatch || !h.useAnnot()) { // making this an && explodes the number of hits + mHits.remove(i); + nHitsRemoved++; + break; + } + } + } + mMinMatch = mHits.get(mHits.size()-1).matchLen; + } + protected int getnHits() { if (mHits==null) return -1; return mHits.size();} + + /****************************************************************** + * AnchorMain.filterHitsFinal -> Group.filterAddHits -> add to HashSet hits + * The mHits were filtered above during 2nd scan; they are further filtered here with same filters + * Keep mTopN by length, fullAnnot regardless, 80% of length + ****************************************************************/ + protected void filterFinalAddHits(HashSet addToHits) { + int nHits = mHits.size(); + if (nHits==0) return; + + Collections.sort(mHits, new CompareByMatch()); // ascending matchLen + + int thresh = 0; + if (nHits >= mTopN) { + thresh = mHits.get(mTopN-1).matchLen; + thresh *= FperBin; // 0.8 so keep 80% of mTopN matchLen + } + + for (int i = 0; i < nHits; i++) { + Hit h = mHits.get(i); + + if (!h.useAnnot()) { + if (h.nSubHits==1 && h.matchLen<=Hit.FhaveLen2) continue; + if (i >= mTopN && h.matchLen< thresh) continue; + } + + switch (mQT){ + case Query: + h.queryHits.status = HitStatus.In; + h.binsize1 = mHitsConsidered; + addToHits.add(h); + break; + case Target: + h.targetHits.status = HitStatus.In; + h.binsize2 = mHitsConsidered; + addToHits.add(h); + break; + default: + break; + } + } + mHits.clear(); + } + protected String getInfo() {return String.format(""Hit bin %,10d %,10d %4d"", start, end, mHits.size());} + + private static class CompareByMatch implements Comparator { + public int compare(Hit h1, Hit h2) { + if (h2.matchLen != h1.matchLen) { + return h2.matchLen - h1.matchLen; + } + else return h1.compareTo(h2); // sorts on start + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/Proj.java",".java","2990","98","package backend.anchor1; + +import java.sql.ResultSet; +import java.util.TreeMap; +import java.util.Vector; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import database.DBconn2; +import symap.manager.Mproject; +import util.ErrorReport; +import util.ProgressDialog; + +/***************************************************** + * Used by AnchorMain1 + * + * Contains Mproject object plus groups and annotation; CAS575 removed BinStats + */ +public class Proj { + protected int idx; + protected String name, grpPrefix, category = """", displayName = """"; + protected Mproject mProj; + + private Vector groupVec; + private TreeMap idx2Grp; + private TreeMap grpName2Idx; + private boolean hasAnnot = true; + + private DBconn2 dbc2; + private Pattern namePat; + + private long totalSize = 0; + private int topN=2; + + /***************************************************************** + * QueryType: AnnotLoadMain - Either; + * AnchorMain, SyntenyMain - Target, query + */ + protected Proj(DBconn2 dbc2, ProgressDialog log, Mproject proj, String name, int topN, int qType) throws Exception { + this.dbc2 = dbc2; + this.mProj = proj; + this.name = name; + this.topN = topN; + + idx = proj.getIdx(); + grpPrefix = mProj.getGrpPrefix().trim(); + category = mProj.getdbCat(); + displayName = mProj.getDisplayName(); + totalSize = mProj.getLength(); + hasAnnot = mProj.hasGenes(); + + String regx = ""("" + grpPrefix + "")?(\\w+).*""; + namePat = Pattern.compile(regx,Pattern.CASE_INSENSITIVE); + groupVec = new Vector(0,1); + idx2Grp = new TreeMap(); + grpName2Idx = new TreeMap(); + + loadGroups(qType); + } + private void loadGroups(int qType) throws Exception { + try { + ResultSet rs = dbc2.executeQuery(""SELECT idx, name, fullname FROM xgroups WHERE proj_idx="" + idx); + while(rs.next()) { + int idx= rs.getInt(1); + String name = rs.getString(2); + String fullname = rs.getString(3); + + Group grp = new Group(topN,name, displayName + ""."" + fullname,idx,qType); + groupVec.add(grp); + + idx2Grp.put(idx,grp); + grpName2Idx.put(name,idx); + grpName2Idx.put(fullname,idx); + } + rs.close(); + } + catch (Exception e) {ErrorReport.print(e, ""load groups""); throw e;} + } + /**********************************************************************/ + public String getName() { return name; } + protected int getIdx() { return idx; } + protected boolean hasAnnot() {return hasAnnot;} + + protected Vector getGroups() { return groupVec; } + protected Group getGrpByIdx(int idx) {return idx2Grp.get(idx);} + protected long getSizeBP() { return totalSize; } + + protected int grpIdxFromQuery(String name) { + String s = name; + + Matcher m = namePat.matcher(name); + if (m.matches()) s = m.group(2); + + if (grpName2Idx.containsKey(s)) return grpName2Idx.get(s); + return -1; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/backend/anchor1/AnnotElem.java",".java","1446","54","package backend.anchor1; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Vector; + +/***************************************** + * Created in Group, accessed in AnchorMain1 as bestOlapAnno + */ +public class AnnotElem implements Comparable { + protected int start, end, len, idx, genenum; + protected boolean isRev; + protected GeneType mGT = GeneType.NA; // {Gene, NonGene, NA} + protected int mID; + + private static int NEXTID = 0; + + protected AnnotElem( int idx, int start, int end, boolean isRev, int genenum, GeneType gt){ + this.idx = idx; + this.start = start; + this.end = end; + len = Math.abs(end-start)+1; + this.isRev = isRev; + this.genenum =genenum; + this.mGT = gt; + mID = NEXTID; + NEXTID++; + } + + protected String getInfo() { + return String.format(""%5d idx=%-5d gn=%5d (%,10d %,10d l=%,5d %5s) %s"", mID, idx, genenum, start, end, (end-start+1), isRev, mGT.toString()); + } + + protected int getLength() { return len; } + + protected boolean isGene(){ + return (mGT == GeneType.Gene); + } + public int compareTo(AnnotElem _a2) { // needed for HashSet in AnchorMain + AnnotElem a2 = (AnnotElem)_a2; + if (mID < a2.mID) return -1; + if (mID > a2.mID) return 1; + return 0; + } + public static void sortByStart(Vector ae) { + Collections.sort(ae, + new Comparator() { + public int compare(AnnotElem h1, AnnotElem h2) { + return h1.start - h2.start; + } + } + ); + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/blockview/BlockViewFrame.java",".java","19141","611","package blockview; + +import java.awt.*; +import java.awt.event.*; +import java.sql.*; +import java.util.Vector; +import java.util.TreeMap; +import java.util.HashSet; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import javax.swing.event.*; +import javax.swing.*; + +import database.DBconn2; +import symap.manager.Mproject; +import util.ImageViewer; +import util.ErrorReport; +import util.Jcomp; +/************************************************ + * Draws the blocks for a synteny pair + */ + +public class BlockViewFrame extends JFrame{ + private static final long serialVersionUID = 1L; + public static final int MAX_GRPS = 150; + public static final int maxColors = 100; + private final int fChromWidth = 8; + private final int fLayerWidth = 8; + private final int fChromSpace = 25; + private final int fBlockMaxHeight = 700; + + private int mRefIdx, mIdx2; + private String refName, refType, name2, type2; + private DBconn2 tdbc2; + private Vector mColors; + + private TreeMap>> mLayout; + private TreeMap mRefNames, mGrp2Names; + private TreeMap mRefSizes; + private Vector mRefOrder; + private Vector mBlockRects; + private TreeMap grpColorOrder; + private Vector mGrps2; + private Vector mBlocks; + private JButton saveBtn; + + private boolean reversed = false; + private int mPairIdx; + + private int bpPerPx = 10000; + private int chromLabelOffset = 0; + private int chromXOffset = 0; + private Font chromeFont, legendFont, chromFontVert; + private boolean bChromLabelVert = false; + private boolean bGtMaxGrpsRef = false, bGtMaxGrps2 = false; + private int unGrp2 = 0; // idx of the unanchored group, ""0"" + private JPanel mainPane = null; + private JScrollPane scroller = null; + + public BlockViewFrame(String title, DBconn2 dbc2, int projXIdx, int projYIdx) throws Exception { + super(title); + mRefIdx = projXIdx; + mIdx2 = projYIdx; + + this.tdbc2 = new DBconn2(""BlocksG-"" + DBconn2.getNumConn(), dbc2); + init(); + } + private void init() { + try { + if (!initFromDB()) return; + if (!layoutBlocks()) return; + + getUniqueColors(maxColors); + chromeFont = new Font(""Verdana"",0,14); + legendFont = new Font(""Verdana"",0,12); + AffineTransform rot90 = new AffineTransform(0,-1,1,0,0,0); + chromFontVert = chromeFont.deriveFont(rot90); + + this.getContentPane().removeAll(); + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + mainPane = Jcomp.createPagePanel(); + mainPane.setLayout(new GridBagLayout()); + scroller = new JScrollPane(mainPane); + + GridBagConstraints cPane = new GridBagConstraints(); + cPane.gridx = cPane.gridy = 0; cPane.fill = GridBagConstraints.CENTER; + + // Top row + JPanel topRow = Jcomp.createRowPanel(); + topRow.setLayout(new GridBagLayout()); + + GridBagConstraints cRow = new GridBagConstraints(); + cRow.gridx = cRow.gridy = 0; cRow.fill = GridBagConstraints.SOUTHEAST; + + JLabel title = Jcomp.createBoldLabel(name2 + "" to "" + refName + "" synteny"", 18); + + topRow.add(title,cRow); + cRow.gridx++; + topRow.add(new JLabel("" ""),cRow); + + if (!bGtMaxGrps2 ) { + cRow.gridx++; cRow.fill = GridBagConstraints.SOUTHEAST; + JLabel revLabel = Jcomp.createHtmlLabel(""Reverse"", ""Reverse reference""); // ul + revLabel.addMouseListener(reverseClick); + topRow.add(revLabel,cRow); + } + else { + System.out.println(""Warning: one of the genomes has >"" + MAX_GRPS + "" sequences""); + System.out.println("" this causes the 'reverse' option to not work on the block view""); + System.out.println("" use scripts/lenFasta.pl to find cutoff length for Minimum Length.""); + System.out.println("" email symap@agcol.arizona.edu if you would like further instructions""); + } + cRow.gridx++; + topRow.add(new JLabel("" ""),cRow); + + saveBtn = Jcomp.createIconButton(""/images/print.gif"", ""Save Image""); + saveBtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + ImageViewer.showImage(""Blocks"", mainPane); + } + }); + cRow.gridx++; + topRow.add(saveBtn,cRow); + + cPane.gridy++; + mainPane.add(topRow,cPane); + + // Legend + JPanel keyRow = Jcomp.createPlainPanel(); + JLabel key = Jcomp.createVentanaLabel(name2 + "" "" + type2 + "" color key"", 12); + keyRow.add(key); + cPane.gridy++; + mainPane.add(keyRow,cPane); + + JPanel legendPane = Jcomp.createRowPanel(); + drawLegend(legendPane); + cPane.gridy++; + mainPane.add(legendPane,cPane); + + // Click for detail + JPanel selectRow = Jcomp.createPlainPanel(); + JLabel select = Jcomp.createVentanaLabel(refName + "" "" + refType + "" - click for detail view"", 12); + selectRow.add(select); + cPane.gridy++; + mainPane.add(selectRow,cPane); + + // Blocks panel + BlockPanel blockPanel = new BlockPanel(this); + blockPanel.setVisible(true); + cPane.gridy++; + mainPane.add(blockPanel,cPane); + + int nLevels = 0; + for (int grp : mLayout.keySet()) nLevels += mLayout.get(grp).size(); + int totalWinWidth = (mLayout.size()*(fChromWidth + fChromSpace)) + (nLevels*fLayerWidth); // used by legend + int d1winWidth = totalWinWidth; + if (d1winWidth>1000) d1winWidth=1000; + else if (d1winWidth<400) d1winWidth=400; + int height = fBlockMaxHeight + chromLabelOffset + 100; + + Dimension d1 = new Dimension(d1winWidth, height); + setPreferredSize(d1); + setMinimumSize(d1); // without this, panel is not all shown, but can be resized + + Dimension d2 = new Dimension(totalWinWidth + 20, height + 20); + blockPanel.setPreferredSize(d2); blockPanel.setMinimumSize(d2); + + this.setLocationRelativeTo(null); + this.getContentPane().add(scroller); + this.validate(); + this.repaint(); + } + catch(Exception e){ErrorReport.print(e, ""Initializing panel for blocks"");} + } + public void dispose() { // override + setVisible(false); + tdbc2.close(); + super.dispose(); + } + private boolean initFromDB() { + try { + int cnt = tdbc2.executeCount(""select count(*) as ngrps from xgroups where proj_idx="" + mRefIdx); + bGtMaxGrpsRef = (cnt > MAX_GRPS); + + cnt = tdbc2.executeCount(""select count(*) as ngrps from xgroups where proj_idx="" + mIdx2); + bGtMaxGrps2 = (cnt > MAX_GRPS); + + if (bGtMaxGrpsRef && bGtMaxGrps2) { + System.out.println(""Genomes have too many chromosomes/contigs to show in block view""); + return false; + } + if (bGtMaxGrpsRef) { + int tmp = mRefIdx; + mRefIdx = mIdx2; + mIdx2 = tmp; + bGtMaxGrps2 = true; + bGtMaxGrpsRef = false; + } + reversed = false; + mPairIdx = tdbc2.executeInteger(""select idx from pairs where proj1_idx="" + mIdx2 + "" and proj2_idx="" + mRefIdx); + + if (mPairIdx<0) { + mPairIdx = tdbc2.executeInteger(""select idx from pairs where proj2_idx="" + mIdx2 + "" and proj1_idx="" + mRefIdx); + reversed = true; + if (mPairIdx<0) { + System.out.println(""Unable to find project pair""); + return false; + } + } + unGrp2 = tdbc2.executeInteger(""select idx from xgroups where name='0' and proj_idx="" + mIdx2); + + Mproject tProj = new Mproject(); + String display_name = tProj.getKey(tProj.sDisplay); + String grp_type = tProj.getKey(tProj.sGrpType); + + refName = tdbc2.executeString(""select value from proj_props where name='""+display_name+""' and proj_idx="" + mRefIdx); + refType = tdbc2.executeString(""select value from proj_props where name='""+ grp_type +""' and proj_idx="" + mRefIdx); + if (refType == null) refType = ""Chromosomes""; // should be loaded, but if not... + + name2 = tdbc2.executeString(""select value from proj_props where name='""+ display_name+""' and proj_idx="" + mIdx2); + type2 = tdbc2.executeString(""select value from proj_props where name='""+grp_type+""' and proj_idx="" + mIdx2); + if (type2 == null) type2 = ""Chromosomes""; + + return true; + } + catch(Exception e){ErrorReport.print(e, ""Init from DB""); return false;} + } + private MouseListener reverseClick = new MouseAdapter() + { + public void mouseEntered(MouseEvent e) { + Cursor cur = new Cursor(Cursor.HAND_CURSOR); + setCursor(cur); + } + public void mouseExited(MouseEvent e) { + Cursor cur = new Cursor(Cursor.DEFAULT_CURSOR); + setCursor(cur); + } + public void mouseClicked(MouseEvent e) { + reverseView(); + } + }; + private void reverseView() { + int tmp = mIdx2; + mIdx2 = mRefIdx; + mRefIdx = tmp; + chromLabelOffset = 0; + init(); + } + private boolean layoutBlocks() { + try { + ResultSet rs; + + HashSet chrBlocks = new HashSet (); + String sql1=""""; + if (!reversed) sql1 = ""select grp2_idx from blocks where pair_idx="" + mPairIdx; + else sql1 = ""select grp1_idx from blocks where pair_idx="" + mPairIdx; + rs = tdbc2.executeQuery(sql1); + while (rs.next()) { + int idx = rs.getInt(1); + if (!chrBlocks.contains(idx)) chrBlocks.add(idx); + } + + mRefNames = new TreeMap(); + mRefSizes = new TreeMap(); + mRefOrder = new Vector(); + mLayout = new TreeMap>>(); //xgroups.idx, + int maxChrLen = 0; + + // Get chr names and sizes + rs = tdbc2.executeQuery(""select idx,name,length from xgroups "" + + "" join pseudos on pseudos.grp_idx=xgroups.idx "" + + "" where proj_idx="" + mRefIdx + "" order by sort_order asc""); + while (rs.next()){ + int idx = rs.getInt(""idx""); + if (!chrBlocks.contains(idx)) continue; + + int chrLen = rs.getInt(""length""); + String name = rs.getString(""name""); + mRefNames.put(idx, name); // chromosome number + mRefSizes.put(idx, chrLen); + mLayout.put(idx, new TreeMap>()); + mRefOrder.add(idx); + maxChrLen = Math.max(maxChrLen,chrLen); + if (name.length() >= 6) { + bChromLabelVert = true; + chromeFont = chromFontVert; + } + } + rs.close(); + + bpPerPx = maxChrLen/fBlockMaxHeight; + if (bpPerPx<=0) bpPerPx=1; + + // get the blocks in decreasing order of size. + // as we add each one to the list we assign it an index which is just its order in the list. + mBlocks = new Vector(); + mBlockRects = new Vector(); + + String sql=""""; + if (!reversed) { + sql = ""select grp1_idx as grp2, grp2_idx as grpRef, start2 as start,end2 as end from blocks "" + + "" where pair_idx="" + mPairIdx + "" order by (end2 - start2) desc""; + } + else { + sql = ""select grp2_idx as grp2, grp1_idx as grpRef, start1 as start,end1 as end from blocks "" + + "" where pair_idx="" + mPairIdx + "" order by (end1 - start1) desc""; + } + rs = tdbc2.executeQuery(sql); + while (rs.next()) { + int grp2 = (bGtMaxGrps2 ? unGrp2 : rs.getInt(""grp2"")); + int grpRef = rs.getInt(""grpRef""); + int start = rs.getInt(""start""); + int end = rs.getInt(""end""); + + Block b = new Block(grpRef,grp2,start/bpPerPx,end/bpPerPx); + mBlocks.add(b); + b.mI = mBlocks.size() - 1; + } + rs.close(); + + // go through the blocks and make the layout + for(int i = 0; i < mBlocks.size(); i++){ + Block b = mBlocks.get(i); + TreeMap> chrLayout = mLayout.get(b.mGrpRef); + if (chrLayout==null) continue; + + // find the first level where this block can fit + int L; + for (L = 1; ;L++) { + if (!chrLayout.containsKey(L)){ + break; + } + else { + boolean hasSpace = true; + for (Block b1 : chrLayout.get(L)) { + if (b.overlaps(b1)){ + hasSpace = false; + break; + } + } + if (hasSpace) { + break; + } + } + if (!chrLayout.containsKey(-L)){ + L = -L; + break; + } + else { + boolean hasSpace = true; + for (Block b1 : chrLayout.get(-L)) { + if (b.overlaps(b1)) { + hasSpace = false; + break; + } + } + if (hasSpace) { + L = -L; + break; + } + } + } + if (!chrLayout.containsKey(L)) { + chrLayout.put(L, new Vector()); + } + chrLayout.get(L).add(b); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Block layout"");; return false;} + } + private void blockMouseClick(MouseEvent m) + { + for (int i = 0; i < mRefOrder.size(); i++) { + Rectangle blockRect = mBlockRects.get(i); + if (blockRect.contains(m.getPoint())) { + int grpIdx = mRefOrder.get(i); + Block2Frame frame = new Block2Frame(tdbc2, mRefIdx, mIdx2,grpIdx,mPairIdx,reversed); + frame.setVisible(true); + + } + } + } + private void blockMouseMoved(MouseEvent m) { + if (mBlockRects.size()==0) return; + for (int i = 0; i < mRefOrder.size(); i++) { + Rectangle blockRect = mBlockRects.get(i); + if (blockRect.contains(m.getPoint())) { + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + return; + } + } + setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + private void paintBlocks(Graphics g){ + boolean bStoreRects = mBlockRects.isEmpty(); + + if (chromLabelOffset == 0) { + g.setFont(chromeFont); + FontMetrics fm = g.getFontMetrics(chromeFont); + + for (String name : mRefNames.values()) { + Rectangle2D r = fm.getStringBounds(name, g); + chromLabelOffset = Math.max(chromLabelOffset,(int)r.getHeight()); + if (bChromLabelVert) { + chromXOffset = Math.max(chromXOffset, (int)r.getWidth()); + } + } + chromLabelOffset += 12; + } + + int y0 = 20; + int yA = y0 + chromLabelOffset; + int x = 10; + for (int i = 0; i < mRefOrder.size(); i++) { + int xA = x; + + int refIdx = mRefOrder.get(i); + TreeMap> chrLayout = mLayout.get(refIdx); + int chromHeight = mRefSizes.get(refIdx)/bpPerPx; + + int L; + for (L = -1;chrLayout.containsKey(L); L--); + for (L++; L < 0; L++) { + for (Block b : chrLayout.get(L)) { + int y1 = chromLabelOffset + b.mS + y0; + int ht = (b.mE - b.mS); + g.setColor(new Color(mColors.get(grpColorOrder.get(b.mGrp2)))); + g.fillRect(x, y1, fLayerWidth, ht); + } + x += fLayerWidth; + } + g.setColor(Color.black); + g.setFont(chromeFont); + g.drawString(mRefNames.get(refIdx),x + chromXOffset, chromLabelOffset - 10 + y0); + + g.setColor(Color.lightGray); + g.fillRect(x,chromLabelOffset + y0, fChromWidth,chromHeight); + int yB = yA + chromHeight; + x += fChromWidth; + for (L=1; chrLayout.containsKey(L); L++) { + for (Block b : chrLayout.get(L)) { + int y1 = chromLabelOffset + b.mS + y0; + int ht = (b.mE - b.mS); + g.setColor(new Color(mColors.get(grpColorOrder.get(b.mGrp2)))); + g.fillRect(x, y1, fLayerWidth, ht); + } + x += fLayerWidth; + } + int xB = x; + if (bStoreRects) mBlockRects.add(new Rectangle(xA,yA,xB-xA,yB-yA)); + x += fChromSpace; + } + } + private void drawLegend(JPanel pane) throws Exception { + grpColorOrder = new TreeMap(); + ResultSet rs; + mGrps2 = new Vector(); + mGrp2Names = new TreeMap(); + Dimension d = new Dimension(25, 25); + + if (bGtMaxGrps2) { + grpColorOrder.put(unGrp2, 0); + mGrps2.add(unGrp2); + mColors.add(0, 0); + JPanel f = new JPanel(); + f.setPreferredSize(d); f.setMinimumSize(d); + f.setVisible(true); + f.setBackground(Color.black); + pane.add(f); + JLabel l = new JLabel(""0 (unordered) ""); + l.setFont(legendFont); + pane.add(l); + return; + } + // Proceed with drawing + // unanchored blocks have grp_idx=0 (unGrp2=0) + rs = tdbc2.executeQuery(""select count(*) as count from blocks where pair_idx="" + mPairIdx + + "" and (grp1_idx="" + unGrp2 + "" or grp2_idx="" + unGrp2 + "")""); + rs.next(); + if (rs.getInt(""count"") > 0) { + grpColorOrder.put(unGrp2, 0); + mGrps2.add(unGrp2); + mGrp2Names.put(unGrp2, ""0""); + mColors.add(0, 0); + } + // get all chromosomes for second species + rs = tdbc2.executeQuery(""select name,idx from xgroups where name != '0' and proj_idx="" + mIdx2 + + "" order by sort_order asc""); // sort_order is by name unless 'ordered_against' + int i = mGrps2.size(); + while (rs.next() ) { + String name = rs.getString(1); + int idx = rs.getInt(2); + mGrps2.add(idx); + mGrp2Names.put(idx, name); + grpColorOrder.put(idx,i); + i++; + if (i > maxColors) i = 1; + } + rs.close(); + + int j=0; + for (i = 0; i < mGrps2.size(); i++) { + int idx = mGrps2.get(i); + JPanel f = new JPanel(); + f.setPreferredSize(d); f.setMinimumSize(d); + f.setVisible(true); + f.setBackground(new Color(mColors.get(j))); + j++; // let it cycle through colors, will have dups, but better than black + if (j>=mColors.size()) j=0; + pane.add(f); + JLabel l = new JLabel("" "" + mGrp2Names.get(idx) + "" ""); + l.setFont(legendFont); + pane.add(l); + } + } + private int colorInt(int R, int G, int B) { + return (R<<16) + (G<<8) + B; + } + private void getUniqueColors(int amount) { + int max = (0xE0 << 16) + (0xE0 << 8) + 0xE0; + int step = (15*max)/(4*amount); + mColors = new Vector(); + + mColors.add(colorInt(255,0,0)); + mColors.add(colorInt(0,0,255)); + mColors.add(colorInt(20,200,70)); + mColors.add(colorInt(138,0,188)); + mColors.add(colorInt(255,165,0)); + mColors.add(colorInt(255,181,197)); + mColors.add(colorInt(210, 180, 140)); + mColors.add(colorInt(64,224,208)); + mColors.add(colorInt(165,42,42)); + mColors.add(colorInt(0,255,255)); + mColors.add(colorInt(230,230,250)); + mColors.add(colorInt(255,255,0)); + mColors.add(colorInt(85,107, 47)); + mColors.add(colorInt(70,130,180)); + + for (int c = 0xE0; mColors.size() <= amount ; c += step ){ + c %= max; + int R = c >> 16; + int G = c >> 8; + int B = c & 0xFF; + if (Math.abs(R-G) <= 0x30 && Math.abs(R-B) <= 0x30 && Math.abs(B-G) <= 0x30) { + continue; // too gray + } + boolean tooClose = false; + for (int j = 0; j < mColors.size(); j++){ + int c1 = mColors.get(j); + int R1 = c1 >> 16; int G1 = c1 >> 8; int B1 = c1 & 0xFF; + if ( Math.abs(R - R1) <= 0x30 && Math.abs(G - G1) <= 0x30 && Math.abs(B - B1) <= 0x30){ + tooClose = true; + break; + } + if (tooClose) continue; + } + mColors.add(c); + } + } + + class BlockPanel extends JPanel implements MouseInputListener { + private static final long serialVersionUID = 1L; + BlockViewFrame blockFrame; + + public BlockPanel(BlockViewFrame _blockFrame) { + super(); + setBackground(Color.white); + blockFrame = _blockFrame; + addMouseListener(this); + addMouseMotionListener(this); + } + public void paintComponent(Graphics g) { + super.paintComponent(g); //paint background + blockFrame.paintBlocks(g); + } + public void mouseClicked(MouseEvent m){ + blockFrame.blockMouseClick(m); + } + public void mousePressed(MouseEvent m){ + } + public void mouseEntered(MouseEvent m){ + } + public void mouseReleased(MouseEvent m){ + } + public void mouseExited(MouseEvent m) { + } + public void mouseDragged(MouseEvent m) { + } + public void mouseMoved(MouseEvent m) { + blockFrame.blockMouseMoved(m); + } + } + class Block { + int mS; int mE; + int mGrp2; int mGrpRef; + int mI; + + public Block(int _ref, int _grp2, int _s, int _e) { + mGrpRef = _ref; + mGrp2 = _grp2; + mS = _s; + mE = _e; + } + public boolean overlaps(Block b){ + return (Math.max(b.mS, mS) <= Math.min(b.mE,mE) + 30); // should match value in Block2Frame + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/blockview/Block2Frame.java",".java","17493","584","package blockview; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.sql.*; +import java.util.Vector; +import java.util.TreeMap; +import java.awt.geom.Rectangle2D; +import javax.swing.event.*; + +import database.DBconn2; +import symap.manager.Mproject; +import symap.mapper.HfilterData; +import symap.Globals; +import symap.drawingpanel.SyMAP2d; +import util.ErrorReport; +import util.ImageViewer; +import util.Utilities; +import util.Jcomp; + +/******************************************** + * Block view for a single selected chromosome + */ +public class Block2Frame extends JFrame { + private static final long serialVersionUID = 1L; + private final int fBlockMaxHeight = 800; + private final int fChromWidth = 15, fChromWidth2 = 25; // width of Ref Chr; all others + private final int fLayerWidth = 90; // width of level + private final int fTooManySeqs = 75; + + private DBconn2 tdbc2; + + private int bpPerPx; + private int mRefIdx; + private String refName, tarName, grpPfx; + private int mIdx2, mGrpIdx, mPairIdx; + private Vector mColors; + private boolean unorderedRef, unordered2, mReversed; + private int unGrp2; + private Vector mBlocks; + private TreeMap> mLayout; + private int mRefSize; + private String mRefChr; + private TreeMap mGrp2Names; + private TreeMap colorOrder; + + private boolean savedRects = false; + private JButton saveBtn; + private JPanel mainPane; + private int farL, farR; + + // Called from BlockViewFrame - subwindow + public Block2Frame(DBconn2 tdbc2, int refIdx, int idx2, int grpIdx, int pairIdx, boolean reversed) { + super(""SyMAP "" + Globals.VERSION + "" - Block Detail View""); + mRefIdx = refIdx; + mIdx2 = idx2; + mGrpIdx = grpIdx; + mPairIdx = pairIdx; + mReversed = reversed; + + this.tdbc2 = new DBconn2(""BlocksC-"" + DBconn2.getNumConn(), tdbc2); + + setBackground(Color.white); + getUniqueColors(100); + + init(); + } + private void init() { + try { + if (!initFromDB()) return; + if (!layoutBlocks()) return; + + this.getContentPane().removeAll(); + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + mainPane = Jcomp.createPagePanel(); + mainPane.setLayout(new GridBagLayout()); + JScrollPane scroller = new JScrollPane(mainPane); + + GridBagConstraints cPane = new GridBagConstraints(); + cPane.gridx = cPane.gridy = 0; + cPane.fill = GridBagConstraints.NORTH; + + // top row + JPanel topRow = Jcomp.createPlainPanel(); + topRow.setLayout(new GridBagLayout()); + + JLabel title = Jcomp.createBoldLabel(tarName+ "" to "" + refName + "" "" + grpPfx + mRefChr, 18); + GridBagConstraints cRow = new GridBagConstraints(); + cRow.gridx = cRow.gridy = 0; + topRow.add(title,cRow); + + cRow.gridx++; + topRow.add(new JLabel("" ""),cRow); + + saveBtn = Jcomp.createIconButton(""/images/print.gif"", ""Save Image""); + saveBtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + ImageViewer.showImage(""Block"", mainPane); + } + }); + cRow.gridx++; + topRow.add(saveBtn,cRow); + + topRow.setVisible(true); + mainPane.add(topRow,cPane); + + // Click for detail + JPanel selectRow = Jcomp.createPlainPanel(); + JLabel select = Jcomp.createVentanaLabel(""Click block for 2D display"", 12); + + selectRow.add(select); + cPane.gridy++; + mainPane.add(selectRow,cPane); + + // Block panel + BlockPanel blockPanel = new BlockPanel(this); + blockPanel.setVisible(true); + cPane.gridy++; + mainPane.add(blockPanel,cPane); + + // dimensions + int chrmHt = (mRefSize/bpPerPx) + 100; + int totalWinWidth = ((1+mLayout.size()) * fLayerWidth) + fChromWidth; + int d1winWidth = totalWinWidth; + if (d1winWidth>1000) d1winWidth=1000; + else if (d1winWidth<400) d1winWidth=400; + Dimension d = new Dimension(d1winWidth, chrmHt); + setPreferredSize(d); setMinimumSize(d); + + d = new Dimension(totalWinWidth,chrmHt); + blockPanel.setPreferredSize(d); blockPanel.setMinimumSize(d); + + this.setLocationRelativeTo(null); + this.getContentPane().add(scroller); + this.validate(); + this.repaint(); + } + catch(Exception e){ErrorReport.print(e, ""Init for Chromosome Blocks"");} + } + // Main Block can be closed separately, so this needs its own tdbc closed + public void dispose() { // override; + setVisible(false); + tdbc2.close(); + super.dispose(); + } + private boolean initFromDB() { + try { + ResultSet rs; + + // xgroups + int cnt = tdbc2.executeCount(""select count(*) as ngrps from xgroups where proj_idx="" + mRefIdx); + unorderedRef = (cnt > fTooManySeqs); + + cnt = tdbc2.executeCount(""select count(*) as ngrps from xgroups where proj_idx="" + mIdx2); + unordered2 = (cnt > fTooManySeqs); + + if (unorderedRef && unordered2) { + System.out.println(""Genomes have too many chromosomes/contigs to show in block view""); + return false; + } + + unGrp2 = tdbc2.executeInteger(""select idx from xgroups where name='0' and proj_idx="" + mIdx2); + + rs = tdbc2.executeQuery(""select name,length from xgroups join pseudos on pseudos.grp_idx=xgroups.idx "" + + "" where xgroups.idx="" + mGrpIdx); + if (!rs.next()) { + System.out.println(""Unable to find reference group "" + mGrpIdx); + return false; + } + mRefSize = rs.getInt(""length""); + mRefChr = rs.getString(""name""); + + mGrp2Names = new TreeMap(); + colorOrder = new TreeMap(); + if (unordered2) { + colorOrder.put(unGrp2, 0); + mGrp2Names.put(unGrp2,""0""); + mColors.add(0, 0); + } + else { + boolean haveUnanch = false; + cnt = tdbc2.executeCount(""select count(*) as count from blocks where pair_idx="" + mPairIdx + + "" and (grp1_idx="" + unGrp2 + "" or grp2_idx="" + unGrp2 + "")""); + haveUnanch = (0 < cnt); + if (haveUnanch) { + colorOrder.put(unGrp2, 0); + mGrp2Names.put(unGrp2,""0""); + mColors.add(0, 0); + } + } + + rs = tdbc2.executeQuery(""select name, idx from xgroups where proj_idx="" + mIdx2 + "" and name != '0' order by sort_order asc""); + int i = mGrp2Names.size(); + while (rs.next()) { + int idx = rs.getInt(""idx""); + mGrp2Names.put(idx, rs.getString(""name"")); // name has grp_prefix removed + colorOrder.put(idx,i); + i++; + } + + Mproject tProj = new Mproject(); + String grp_prefix = tProj.getKey(tProj.lGrpPrefix); + + rs = tdbc2.executeQuery(""select value from proj_props where name='"" + grp_prefix + ""' and proj_idx="" + mRefIdx); + grpPfx = rs.next() ? rs.getString(""value"") : ""Chr""; + rs.close(); + + String display_name = tProj.getKey(tProj.sDisplay); + refName = tdbc2.executeString(""select value from proj_props where name='""+display_name+""' and proj_idx="" + mRefIdx); + tarName = tdbc2.executeString(""select value from proj_props where name='""+display_name+""' and proj_idx="" + mIdx2); + + return true; + } + catch(Exception e){ + ErrorReport.print(e, ""Init from DB for blocks""); + return false; + } + } + private void paintBlocks(Graphics g1) throws Exception { + Graphics2D g2 = (Graphics2D) g1; + g2.setFont(new Font(""Verdana"",0,14)); + int y0 = 40; + int x = fLayerWidth/2; + int chromHeight = mRefSize/bpPerPx; + int chromXLeft, chromXRight; + + Stroke stroke0 = new BasicStroke(1.0f); + Stroke stroke1 = new BasicStroke(2.0f); + float [] dash = {2f, 2f}; + Stroke stroke2 = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, dash, 2.0f); + + int L=farL; + chromXLeft = x + (-L)*(fLayerWidth); + chromXRight = chromXLeft + fChromWidth; + g2.setColor(Color.green); + + // Draw lines from ref to chr to the left + for (; L < 0; L++) { + for (Block b : mLayout.get(L)) { + int y1 = b.mS + y0; + int ht = b.mE - b.mS; + g2.drawLine(x, y1, chromXLeft, y1); + g2.drawLine(x, y1+ht-1, chromXLeft, y1+ht-1); + } + x += fLayerWidth; + } + // Draw lines from ref to chr to the rigth + x += fChromWidth + fLayerWidth - fChromWidth2; + for (L=1; mLayout.containsKey(L); L++) { + for (Block b : mLayout.get(L)){ + int y1 = b.mS + y0; + int ht = b.mE - b.mS; + g2.drawLine(x, y1, chromXRight, y1); + g2.drawLine(x, y1+ht-1, chromXRight, y1+ht-1); + } + x += fLayerWidth; + } + + Font font1 = new Font(""verdana"",0,10); + Font font2 = new Font(""verdana"",Font.BOLD,10); + g2.setFont(font1); + x = fLayerWidth/2; + + for (L=farL; L < 0; L++) { + for (Block b : mLayout.get(L)){ + int y1 = b.mS + y0; + int ht = b.mE - b.mS; + int co = colorOrder.get(b.unordered ? unGrp2 : b.mGrp2); + g2.setColor(new Color(mColors.get(co))); + g2.fillRect(x, y1, fChromWidth2, ht); + g2.setColor(Color.black); + + if (b.bInv) g2.setStroke(stroke2); + else g2.setStroke(stroke1); + g2.drawRect(x, y1, fChromWidth2, ht); + + String chrName = mGrp2Names.get(b.mGrp2) + "":""; // e.g. 3: where 3 is chr3 + int offset = 7*chrName.length() + 1; + + g2.setFont(font2); + g2.drawString(chrName, x-10, y1-15); + g2.setFont(font1); + g2.drawString(b.name,x-10+offset, y1-15); + g2.drawString(b.numHits + "" anchors"",x-10, y1-5); + + if (!savedRects) { + b.blockRect = new Rectangle(x,y1,fChromWidth2,ht); + } + } + x += fLayerWidth; + } + // Draw ref chr + g2.setStroke(stroke0); + g2.setColor(Color.LIGHT_GRAY); + g2.fillRect(x, y0,fChromWidth,chromHeight); + g2.setColor(Color.black); + g2.drawRect(x, y0, fChromWidth, chromHeight); + g2.drawString(refName,x, y0-15); + g2.drawString(grpPfx + mRefChr,x, y0-5); + + // Draw rectangles to the right + x += fChromWidth + fLayerWidth - fChromWidth2; + for (L=1; L<=farR; L++) { + for (Block b : mLayout.get(L)) { + int y1 = b.mS + y0; + int ht = b.mE - b.mS; + int co = colorOrder.get(b.unordered ? unGrp2 : b.mGrp2); + g2.setColor(new Color(mColors.get(co))); + g2.fillRect(x, y1, fChromWidth2, ht); + g2.setColor(Color.black); + + if (b.bInv) g2.setStroke(stroke2); + else g2.setStroke(stroke1); + g2.drawRect(x, y1, fChromWidth2, ht); + String chrName = mGrp2Names.get(b.mGrp2) + "":""; + int offset = 7*chrName.length() + 1; + g2.setFont(font2); + g2.drawString(chrName, x-10, y1-15); + g2.setFont(font1); + g2.drawString(b.name,x-10+offset, y1-15); + g2.drawString(b.numHits + "" anchors"",x-10, y1-5); + + if (!savedRects) { + b.blockRect = new Rectangle(x,y1,fChromWidth2,ht); + } + } + x += fLayerWidth; + } + savedRects = true; + } + + private boolean layoutBlocks() { + try { + ResultSet rs; + + mLayout = new TreeMap>(); + + bpPerPx = mRefSize/fBlockMaxHeight; + + // get the blocks in decreasing order of size. + // as we add each one to the list we assign it an index which is just its order in the list. + mBlocks = new Vector(); + String sql; + if (!mReversed) { + sql =""select idx, grp1_idx as grp2, start2 as start, end2 as end, blocknum,"" + + "" start1 as s2, end1 as e2, corr "" + + "" from blocks where pair_idx="" + mPairIdx + + "" and grp2_idx="" + mGrpIdx + "" order by (end2 - start2) desc""; + } + else { + sql=""select idx, grp2_idx as grp2, start1 as start, end1 as end, blocknum, "" + + "" start2 as s2, end2 as e2, corr "" + + "" from blocks where pair_idx="" + mPairIdx + + "" and grp1_idx="" + mGrpIdx + "" order by (end1 - start1) desc""; + } + rs = tdbc2.executeQuery(sql); + while (rs.next()) { + int grp2 = rs.getInt(""grp2""); + int start = rs.getInt(""start""); + int end = rs.getInt(""end""); + int s2 = rs.getInt(""s2""); + int e2 = rs.getInt(""e2""); + int blocknum = rs.getInt(""blocknum""); + int idx = rs.getInt(""idx""); + boolean isInv = (rs.getFloat(""corr"")<0); + String blockName = Utilities.blockStr(mGrp2Names.get(grp2), mRefChr, blocknum); + Block b = new Block(grp2, start/bpPerPx, end/bpPerPx, s2, e2, blockName, idx, unordered2, isInv, blocknum); + mBlocks.add(b); + } + rs.close(); + + for (Block b : mBlocks) { + b.numHits = tdbc2.executeCount(""select count(*) as count from pseudo_block_hits where block_idx="" + b.idx); + + } + // go through the blocks and make layout; find the first level where this block can fit + // similar algorithm as BlockView, so order is basically the same + for(int i = 0; i < mBlocks.size(); i++) { + Block b = mBlocks.get(i); + + int L; + for (L = 1; ;L++) { + if (!mLayout.containsKey(L)) { + break; + } + else { + boolean hasSpace = true; + for (Block b1 : mLayout.get(L)) { + if (b.overlaps(b1)) { + hasSpace = false; + break; + } + } + if (hasSpace) { + break; + } + } + if (!mLayout.containsKey(-L)) { + L = -L; + break; + } + else { + boolean hasSpace = true; + for (Block b1 : mLayout.get(-L)) { + if (b.overlaps(b1)) { + hasSpace = false; + break; + } + } + if (hasSpace) { + L = -L; + break; + } + } + } + if (!mLayout.containsKey(L)) { + mLayout.put(L, new Vector()); + if (L<0) farL=L; + else farR=L; + } + mLayout.get(L).add(b); + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Layout blocks""); return false;} + } + private int colorInt(int R, int G, int B) { + return (R<<16) + (G<<8) + B; + } + + private void getUniqueColors(int amount) + { + int max = (0xE0 << 16) + (0xE0 << 8) + 0xE0; + int step = (15*max)/(4*amount); + mColors = new Vector(); + + mColors.add(colorInt(255,0,0)); + mColors.add(colorInt(0,0,255)); + mColors.add(colorInt(20,200,70)); + mColors.add(colorInt(138,0,188)); + mColors.add(colorInt(255,165,0)); + mColors.add(colorInt(255,181,197)); + mColors.add(colorInt(210, 180, 140)); + mColors.add(colorInt(64,224,208)); + mColors.add(colorInt(165,42,42)); + mColors.add(colorInt(0,255,255)); + mColors.add(colorInt(230,230,250)); + mColors.add(colorInt(255,255,0)); + mColors.add(colorInt(85,107, 47)); + mColors.add(colorInt(70,130,180)); + + for (int c = 0xE0; mColors.size() <= amount ; c += step ) { + c %= max; + int R = c >> 16; + int G = c >> 8; + int B = c & 0xFF; + if (Math.abs(R-G) <= 0x30 && Math.abs(R-B) <= 0x30 && Math.abs(B-G) <= 0x30) { + continue; // too gray + } + boolean tooClose = false; + for (int j = 0; j < mColors.size(); j++) { + int c1 = mColors.get(j); + int R1 = c1 >> 16; int G1 = c1 >> 8; int B1 = c1 & 0xFF; + if ( Math.abs(R - R1) <= 0x30 && Math.abs(G - G1) <= 0x30 && Math.abs(B - B1) <= 0x30) { + tooClose = true; + break; + } + if (tooClose) continue; + } + mColors.add(c); + } + } + + private class Block { + int mS; int mE; // on the reference, stored in *pixels*, so that the ""overlaps"" + int mS2; int mE2; // on the query, stored as *basepairs* + int mGrp2; + String name; + int numHits = 0; + int idx; + Rectangle2D blockRect; + boolean unordered; + boolean bInv; + int blockNum; // for 2D + + public Block(int _grp2, int _s, int _e, int _s2, int _e2, String _name, int _idx, + boolean _unord, boolean isInv, int bnum) + { + mGrp2 = _grp2; + mS = _s; + mE = _e; + mS2 = _s2; + mE2 = _e2; + name = _name; + idx = _idx; + unordered = _unord; + bInv = isInv; + blockNum = bnum; + } + public boolean overlaps(Block b) { + return (Math.max(b.mS, mS) <= Math.min(b.mE,mE) + 30); // should match value in BlockViewFrame + } + } + private void blockMouseMoved(MouseEvent m) { + for (Block b : mBlocks) { + if (b.blockRect.contains(m.getPoint())) { + Cursor c = new Cursor(Cursor.HAND_CURSOR); + setCursor(c); + return; + } + } + Cursor c = new Cursor(Cursor.DEFAULT_CURSOR); + setCursor(c); + + } + private void blockMouseClicked(MouseEvent m) { + for (Block b : mBlocks) { + if (b.blockRect.contains(m.getPoint())) { + show2DBlock(b); + return; + } + } + } + private void show2DBlock(Block b) { + Jcomp.setCursorBusy(this, true); + try { + SyMAP2d symap = new SyMAP2d(tdbc2, null); // makes new conn + symap.getDrawingPanel().setTracks(2); + + HfilterData hd = new HfilterData (); + hd.setForDP(b.blockNum); // only show block + symap.getDrawingPanel().setHitFilter(1,hd); // copy template + + symap.getDrawingPanel().setSequenceTrack(1,mRefIdx,mGrpIdx,Color.CYAN); + symap.getDrawingPanel().setSequenceTrack(2,mIdx2,b.mGrp2,Color.GREEN); + symap.getDrawingPanel().setTrackEnds(1,b.mS*bpPerPx,b.mE*bpPerPx); + symap.getDrawingPanel().setTrackEnds(2,b.mS2,b.mE2); + + symap.getFrame().showX(); + } + catch (Exception err) {ErrorReport.print(err, ""Show 2D View"");} + finally {Jcomp.setCursorBusy(this, false);} + } + private class BlockPanel extends JPanel implements MouseInputListener { + private static final long serialVersionUID = 1L; + Block2Frame blockFrame; + + public BlockPanel(Block2Frame _blockFrame) { + super(); + setBackground(Color.white); + blockFrame = _blockFrame; + addMouseListener(this); + addMouseMotionListener(this); + } + public void paintComponent(Graphics g) { + super.paintComponent(g); //paint background + try { + blockFrame.paintBlocks(g); + } + catch(Exception e) { + ErrorReport.print(e, ""Draw blocks""); + } + } + public void mouseClicked(MouseEvent m){ + blockFrame.blockMouseClicked(m); + } + public void mousePressed(MouseEvent m){ + } + public void mouseEntered(MouseEvent m){ + } + public void mouseReleased(MouseEvent m){ + } + public void mouseExited(MouseEvent m){ + } + public void mouseDragged(MouseEvent m){ + } + public void mouseMoved(MouseEvent m) { + blockFrame.blockMouseMoved(m); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapCE/SyMAPmanager.java",".java","11127","292","package symapCE; + +import java.awt.Component; +import java.io.File; +import java.util.HashSet; + +import backend.Constants; +import backend.anchor1.Group; +import props.PropertiesReader; +import symap.Ext; +import symap.Globals; +import symap.manager.ManagerFrame; +import util.ErrorReport; + +/********************************************* + * Called by symap and viewSymap scripts; print help; set options; starts ManagerFrame + */ +public class SyMAPmanager extends ManagerFrame { + private static final long serialVersionUID = 1L; + private static boolean isReadOnly; + + public static void main(String args[]) { + printVersion(); + + isReadOnly = equalOption(args, ""-r""); + + if (equalOption(args, ""-hhh"")) {// for me; put first + argPrintHidden(args); + System.exit(0); + } + if (equalOption(args, ""-h"") || equalOption(args, ""-help"") || equalOption(args, ""--h"")) { + argPrint(args); + System.exit(0); + } + if (argFail(args)) System.exit(0); // prints args; CAS579 add + + argSet(args); + if (!setArch()) return; // must go after setParams; reads configuration file + + SyMAPmanager frame = new SyMAPmanager(args); + frame.setVisible(true); + } + private SyMAPmanager(String args[]) {super(); } // Creates ManagerFrame; + + /** Args **/ + private static String [] rArgVec = {""-r"", ""-c"", ""-sql"", ""-p"", ""-a"", ""-go"", ""-pg"", ""-ac""}; // symap or viewSymap + private static String [] wArgVec = {""-mum"", ""-wsp"",""-v"", ""-nh""}; // symap + private static String [] hArgVec = { ""-ii"",""-tt"", ""-dd"", ""-dbd"", ""-bt"", ""-s"", ""-cs""}; // hidden + + private static void argPrint(String args[]) { + if (isReadOnly) System.out.println(""Usage: ./viewSymap [options]""); + else System.out.println(""Usage: ./symap [options]""); + + System.out.println("" -c string : Filename of config file (to use instead of symap.config)""); + System.out.println("" -sql : MySQL: for important settings and external programs""); + System.out.println("" -p N : Number of CPUs to use (same as setting CPUs on SyMAPmanager)""); // used in Query MSA + System.out.println("" -h : Show help to terminal and exit""); + + if (!isReadOnly) { // viewSymap is started with -r arg + System.out.println(""\nAlign&Synteny:""); + System.out.println("" -mum : MUMmer: Do not remove any mummer files""); + System.out.println("" -wsp : Algo2: print MUMmer hits that differ from gene strand""); + System.out.println("" -nh : NumHits: recompute for v5.7.9c""); + System.out.println("" -v : A&S verbose output (same as checking Verbose on Manager)""); + } + System.out.println(""\nDisplay:""); + System.out.println("" -a : 2D: do not trim alignments""); + System.out.println("" -go : Queries: show gene overlap instead of exon for Cluster Algo2""); + System.out.println("" -pg : Queries: for Cluster, run old PgeneF algorithm instead of the new Cluster algorithm""); + System.out.println("" -ac : Queries: for Cluster, retain all clusters regardless of size""); + } + private static void argPrintHidden(String args[]) { + System.out.println(""Developer only special flags ""); + System.out.println("" -ii Extra info on 2d popups, extra Query, check Case-insensitive database ""); + System.out.println("" -tt Trace output, and query zTest files ""); + System.out.println("" -dd Debug - mysql trace, etc""); + System.out.println("" -dbd Database - saves special tables to db""); + System.out.println("" -bt Synteny trace""); + System.out.println("" -s Regenerate summary""); + System.out.println("" -cs Collinear sets: recompute for v5.7.7""); + + } + private static void argSet(String args[]) { + if (args.length ==0) return; + + if (isReadOnly) { // used by viewSymap; set in ManagerFrame + inReadOnlyMode = true; + } + if (equalOption(args, ""-c"")) { + Globals.MAIN_PARAMS = getCommandLineOption(args, ""-c""); + if (Globals.MAIN_PARAMS==null) { + System.err.println(""-c must be followed by the name of a configuration file""); + System.exit(-1); + } + } + if (equalOption(args, ""-p"")) { // #CPU; + String x = getCommandLineOption(args, ""-p""); + try { + maxCPU = Integer.parseInt(x); + System.out.println(""-p Max CPUs "" + x); + } + catch (Exception e){ System.err.println(x + "" is not an integer. Ignoring."");} + } + if (equalOption(args, ""-sql"")) {// check MySQL for important settings; + Globals.bMySQL = true; + System.out.println(""-sql MySQL: check settings ""); + } + /** Display viewSymap and symap **/ + if (equalOption(args, ""-a"")) { + Globals.bTrim=false; + System.out.println(""-a 2D: Do not trim alignments""); + } + if (equalOption(args, ""-go"")) { + Globals.bQueryOlap=true; + System.out.println(""-go Queries: show gene overlap instead of exon for Cluster Algo2""); + } + if (equalOption(args, ""-pg"")) { // CAS563 add + Globals.bQueryPgeneF=true; + System.out.println(""-pg Queries: for Cluster, run old PgeneF algorithm instead of the new Cluster algorithm""); + } + if (equalOption(args, ""-ac"")) { // CAS579 add + Globals.bQuerySaveLgClust=true; + System.out.println(""-ac Queries: retain all clusters regardless of size""); + } + /** A&S symap **/ + if (equalOption(args, ""-v"")) {// also on ManagerFrame; verbose A&S output + Constants.VERBOSE = true; + System.out.println(""-v A&S verbose output""); + } + if (equalOption(args, ""-mum"")) { + System.out.println(""-mum MUMmer: Do not remove any mummer result files""); + Constants.MUM_NO_RM = true; + } + if (equalOption(args, ""-wsp"")) { + System.out.println(""-wsp Algo2: print MUMmer hits that differ from gene strand""); + Constants.WRONG_STRAND_PRT = true; + } + if (equalOption(args, ""-nh"")) {// CAS579c add + System.out.println(""-nh numHits: recompute numHits for v5.7.9c""); + Constants.NUMHITS_ONLY = true; + } + + /** -hhh viewSymap and symap **/ + if (equalOption(args, ""-ii"")) { + System.out.println(""-ii Extra info""); + Globals.INFO = true; + } + if (equalOption(args, ""-tt"")) { + System.out.println(""-tt Trace output and mysql to file (and -ii)""); + Globals.TRACE = Globals.INFO = true; + } + if (equalOption(args, ""-dd"")) { + System.out.println(""-dd Debug (and -ii)""); + Globals.DEBUG = Globals.INFO = true; + } + if (equalOption(args, ""-dbd"")) { + System.out.println(""-dbd Database - add tables to DB""); + Globals.DBDEBUG = true; + } + if (equalOption(args, ""-bt"")) { + System.out.println(""-bt Synteny trace""); + backend.synteny.SyntenyMain.bTrace = true; + } + if (equalOption(args, ""-cs"")) { // shown on -h for v5.7.7 + System.out.println(""-cs On A&S, ONLY execute the collinear sets computation""); + Constants.CoSET_ONLY = true; + } + if (equalOption(args, ""-s"")) { + System.out.println(""-s Regenerate summary""); + Globals.bRedoSum = true; + } + // not shown on -h; leave for possible updates + if (equalOption(args, ""-sg"")) { + System.out.println(""-sg Split genes (Algo1)""); + Group.bSplitGene= true; + } + } + /****************************************************************** + * Command line parameters + */ + private static boolean argFail(String args[]) {// return true + if (args.length==0) return false; + + if (args.length==1 && isReadOnly) return false; + + HashSet argSet = new HashSet (); + for (String x : rArgVec) argSet.add(x); + for (String x : hArgVec) argSet.add(x); + if (!isReadOnly) + for (String x : wArgVec) argSet.add(x); + + for (int i = 0; i < args.length; i++) { + String a = args[i]; + + if (a.startsWith(""-"") && !argSet.contains(a)) { + System.err.println(""*** Illegal argument: "" + a); + argPrint(args); + return true; + } + } + if (isReadOnly && args.length==2 && !args[1].startsWith(""-"")) { // viewSymap xxx (-r comes first) + System.err.println(""*** Illegal argument: "" + args[1]); + argPrint(args); + return true; + } + if (!isReadOnly && args.length==1 && !args[0].startsWith(""-"")) {// symap xxx (check 1st arg) + System.err.println(""*** Illegal argument: "" + args[0]); + argPrint(args); + return true; + } + return false; + } + private static boolean equalOption(String[] args, String name) { + for (int i = 0; i < args.length; i++) + if (args[i].equals(name)) + return true; + return false; + } + private static String getCommandLineOption(String[] args, String name){ + for (int i = 0; i < args.length; i++){ + if (args[i].startsWith(name) && !args[i].equals(name)){ + String ret = args[i]; + ret = ret.replaceFirst(name,""""); + return ret; + } + else if (args[i].equals(name) && i+1 < args.length) { + return args[i+1]; + } + } + return null; + } + /************************************************* + * Sets architecture (Available linux64, mac, macM4); Reads from symap.config + */ + private static boolean setArch() { + try { + String paramsfile = Globals.MAIN_PARAMS; + + if (util.FileDir.fileExists(paramsfile)) System.out.println(""Configuration file "" + paramsfile); + else ErrorReport.die(""Configuration file not available: "" + paramsfile); + + PropertiesReader dbProps = new PropertiesReader(new File(paramsfile)); + + // architecture + String userArch = dbProps.getProperty(""arch""); + if (userArch!=null) System.out.println("" Architecture: "" + userArch); + Ext.setArch(userArch); // if null, will determine it; prints errors if any found + + // mummer path + String mummer = dbProps.getProperty(""mummer_path""); + if (mummer!=null && mummer!="""") { + System.out.println("" MUMmer path: "" + mummer); + Ext.setMummer4Path(mummer); + } + return true; + } catch (Exception e) {ErrorReport.print(e, ""Setting architecture""); return false;} + } + /** Banner**/ + private static void printVersion() { + String url = util.Jhtml.BASE_HELP_URL; + String base = url.substring(0, url.length()-1); + System.out.println(""\nSyMAP "" + Globals.VERSION + Globals.DATE + "" "" + base); + System.out.println(""Running on "" + Ext.getPlatform() + "" with Java v"" + System.getProperty(""java.version"")); + } + private static boolean checkJavaSupported(Component frame) { // CAS559 update; CAS42 10/16/17 - did not work for Java SE 9 + try { + String userV = System.getProperty(""java.version""); + if (userV==null) { + System.err.println(""+++ Could not determine Java version - try to continue....""); + return true; + } + String [] ua = userV.split(""\\.""); + int u0=0, u1=0, u2=0; // this is suppose to have 3 numbers, but 22 just has 1; CAS569 + if (ua.length>=0) u0 = Integer.valueOf(ua[0]); + if (ua.length>=1) u1 = Integer.valueOf(ua[1]); + if (ua.length>=2) u2 = Integer.valueOf(ua[2]); + + String relV = Globals.JARVERION; // ""17.0.11""; + String [] rx = relV.split(""\\.""); + int r0 = Integer.valueOf(rx[0]), r1 = Integer.valueOf(rx[1]), r2 = Integer.valueOf(rx[2]); + + // u0 (); + theOptions = new JButton[menuItems.length]; + for(int x=0; x iter = theResults.iterator(); + while(iter.hasNext() && theSelection < 0) { + if(ae.getSource().equals(iter.next())) + theSelection = x; + x++; + } + showSelectedMenu(); + } + protected void addLeftTab(String label) { + JButton newResult = new JButton(label); + + newResult.setBorderPainted(false); + newResult.setFocusPainted(false); + newResult.setContentAreaFilled(false); + newResult.setMargin(new Insets(0, 0, 0, 0)); + newResult.setVerticalAlignment(AbstractButton.TOP); + newResult.setHorizontalAlignment(AbstractButton.LEFT); + newResult.addActionListener(theListener); + newResult.setBackground(Color.WHITE); + + theResults.add(newResult); + + buildPanel(); + + setSelection(theOptions.length + theResults.size() - 1); + } + protected void removeResult(int pos) { + theResults.get(pos).removeActionListener(theListener); + theResults.remove(pos); + buildPanel(); + setSelection(theOptions.length - 1); + } + + protected int getCurrentSelection() { return theSelection; } + protected String getCurrentSelectionLabel() { return theOptions[theSelection].getText(); } + + protected boolean updateLeftTab(String oldLabel, String newLabel) { + Iterator iter = theResults.iterator(); + while(iter.hasNext()) { + JButton temp = iter.next(); + if (temp.getText().equals(oldLabel)) { + temp.setText(newLabel); + buildPanel(); + return true; + } + } + return false; + } + + protected void setSelection(int selection) { + theSelection = selection; + showSelectedMenu(); + } + + private void buildPanel() { + removeAll(); + repaint(); + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + add(Box.createVerticalStrut(15)); // add space at top + + for(int x=0; x iter = theResults.iterator(); + while(iter.hasNext()) { + JPanel temp = new JPanel(); + temp.setLayout(new BoxLayout(temp, BoxLayout.LINE_AXIS)); + temp.setBackground(Color.WHITE); + temp.add(Box.createHorizontalStrut(10)); + temp.add(iter.next()); + Dimension d = temp.getPreferredSize(); + //Buffer for bold/plain text + d.width += 20; + temp.setMaximumSize(d); + temp.setAlignmentX(Component.LEFT_ALIGNMENT); + + add(temp); + } + setBackground(Color.WHITE); + showSelectedMenu(); + } + + private void showSelectedMenu() { + Font f = null; + int x; + for(x=0; x iter = theResults.iterator(); + while(iter.hasNext()) { + JButton temp = iter.next(); + if(x==theSelection) + f = new Font(temp.getFont().getName(), Font.BOLD, temp.getFont().getSize()); + else + f = new Font(temp.getFont().getName(), Font.PLAIN, temp.getFont().getSize()); + temp.setFont(f); + x++; + } + + } + private JButton [] theOptions = null; + private Vector theResults = null; + private ActionListener theListener = null; + private int theSelection = -1; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/CollapsiblePanel.java",".java","3341","115","package symapQuery; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/******************************************************** + * Called in QueryPanel to create the filter panels + */ +public class CollapsiblePanel extends JPanel { + private static final long serialVersionUID = 7114124162647988756L; + + protected CollapsiblePanel(String title, String description) { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBackground(Color.WHITE); + showIcon = createImageIcon(""/images/plus.gif""); + hideIcon = createImageIcon(""/images/minus.gif""); + + showHideButton = new JButton(title); + showHideButton.setBorderPainted(false); + showHideButton.setFocusPainted(false); + showHideButton.setContentAreaFilled(false); + showHideButton.setMargin(new Insets(5, 0, 5, 0)); + showHideButton.setAlignmentX(LEFT_ALIGNMENT); + showHideButton.addActionListener( + new ActionListener( ) { + public void actionPerformed(ActionEvent e) { + if (!visible) expand(); + else collapse(); + }}); + + if (!description.equals("""")) { + labelDescription = new JLabel("" "" + description); + labelDescription.setFont(new Font(labelDescription.getFont().getName(), Font.PLAIN, labelDescription.getFont().getSize())); + labelDescription.setAlignmentX(LEFT_ALIGNMENT); + labelDescription.setBackground(Color.WHITE); + } + + thePanel = new JPanel(); + thePanel.setLayout(new BoxLayout(thePanel, BoxLayout.Y_AXIS)); + thePanel.setBorder ( BorderFactory.createEmptyBorder(0, 20, 0, 20)); // was 5,20,10,20 CAS578 top,bottom were too much space + thePanel.setAlignmentX(LEFT_ALIGNMENT); + thePanel.setBackground(Color.WHITE); + + super.add( showHideButton ); + if (labelDescription != null) super.add( labelDescription ); + super.add( thePanel ); + + theSizeExpanded = getPreferredSize(); + collapse(); + theSizeCollapsed = getPreferredSize(); + + setAlignmentX(LEFT_ALIGNMENT); + } + + protected void collapse() { + visible = false; + showHideButton.setIcon(showIcon); + showHideButton.setToolTipText(""Expand""); + + setMaximumSize(theSizeCollapsed); + thePanel.setVisible(false); + } + + protected void expand() { + visible = true; + showHideButton.setIcon(hideIcon); + showHideButton.setToolTipText(""Collapse""); + + setMaximumSize(theSizeExpanded); + thePanel.setVisible(true); + } + /* over-ride */ + public Component add(Component comp) { + thePanel.add(comp); + if(!visible) { + expand(); + theSizeExpanded = getPreferredSize(); + collapse(); + } + else { + theSizeExpanded = getPreferredSize(); + expand(); + } + + return comp; + } + + private static ImageIcon createImageIcon(String path) { + java.net.URL imgURL = CollapsiblePanel.class.getResource(path); + if (imgURL != null) + return new ImageIcon(imgURL); + else + return null; + } + + private boolean visible = false; + private ImageIcon showIcon = null, hideIcon = null; + private JButton showHideButton = null; + private JLabel labelDescription = null; + private JPanel thePanel = null; + private Dimension theSizeExpanded = null, theSizeCollapsed = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/SpeciesPanel.java",".java","20279","571","package symapQuery; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Collections; +import java.util.TreeMap; +import java.util.Vector; +import java.util.HashMap; +import java.util.HashSet; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import symap.manager.Mproject; +import symap.manager.Mpair; +import util.ErrorReport; +import util.Jcomp; +import util.Popup; + +/****************************************************** + * For QueryPanel: + * Load DB data and creates SpeciesSelect panel for each species + * Do not read DB; isSelf projIdx is not real. + * CAS579c removed dead code, rearranged, renamed + */ +public class SpeciesPanel extends JPanel { + private static final long serialVersionUID = -6558974015998509926L; + private int dnameWidth = 85; // good fit for display name of 12 characters + + protected static int locOnly=1, locChr=2; // setEnable Loc, setEnable loc&Chr + private boolean isNoLoc=false; // do not enable Loc, even if chr selected + + protected SpeciesPanel(QueryFrame qFrame, QueryPanel qPanel) { + this.qFrame = qFrame; + this.qPanel = qPanel; + + spRows = new Vector (); // Will be sorted by DisplayName + setBackground(Color.WHITE); + + createSpRows(); + + createSpPanel(); + } + /************************************************************** + * Creates the Species Row objects and pairWhere + ********************************************************/ + private void createSpRows() { + try { + Vector mProjs = qFrame.getProjects(); // Sorted by DisplayName + boolean isSelf = qFrame.isSelf(); + + int [] spidx = new int [mProjs.size()]; + int x=0; + + // Create Rows that will be in the spPanel + for (Mproject proj : mProjs) { + // Split the grpMap into two strings + String chrNumStr="""", chrIdxStr=""""; + TreeMap idChrMap = proj.getGrpIdxMap(); + + for (int idx : idChrMap.keySet()) { + if (!chrNumStr.equals("""")) {chrNumStr += "",""; chrIdxStr += "","";} + + chrNumStr += proj.getGrpNameFromIdx(idx); + chrIdxStr += idx; + } + // Create row object and enter in the original order + SpeciesRow ssp = new SpeciesRow(proj.getDisplayName(), + proj.getIdx(), proj.getdbCat(), chrNumStr, chrIdxStr, proj.getdbAbbrev(), proj.hasGenes()); + spRows.add(ssp); + + spName2spIdx.put(proj.getDisplayName(), proj.getID()); + spIdx2spRow.put(proj.getID(), ssp); + if (isSelf) selfName[x] = proj.getDisplayName(); + spidx[x++] = proj.getIdx(); + + String [] chrIdxList = ssp.getChrIdxList(); + for (String idx : chrIdxList) chrIdx2spRow.put(Integer.parseInt(idx), ssp); + } + + // Create pairWhere from all pair indices - used in all queries but Orphan + // the order can be spidx[i]spidx[j] + String idList=""""; + for (int i=0; i0) { + if (idList.equals("""")) idList = idx+""""; + else idList += "","" + idx; + } + } + } + if (idList.equals("""")) Popup.showErrorMessage(""No synteny pairs. Attempts to Run Query will fail.""); + else if (!idList.contains("","")) pairWhere = ""PH.pair_idx="" + idList + "" ""; + else pairWhere = ""PH.pair_idx IN ("" + idList + "") ""; + } + catch(Exception e) {ErrorReport.print(e, ""Species panel"");} + } + /************************************************************ + * Creates the Species panel + ******************************************************/ + private void createSpPanel() { + if(spRows == null || spRows.size() == 0) return; + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + add(Box.createVerticalStrut(5)); + /* remove labelPanel, includePanel, excludePanel which do nothing; CAS579c */ + + // Adjust the chromosome select controls + Dimension maxSize = new Dimension(0,0); + for (SpeciesRow sp : spRows) { + Dimension tempD = sp.getChromSize(); + if (tempD.width > maxSize.width) maxSize = tempD; + } + for (SpeciesRow sp : spRows) sp.setChromSize(maxSize); + + // Categories + Vector sortedCat = new Vector (); + for(int x=0; x 1) add(new JLabel(catName.toUpperCase())); + firstOne = false; + } + JPanel row = Jcomp.createRowPanel(); + spObj.setChromSize(maxSize); + row.add(spObj); + + add(row); + add(Box.createVerticalStrut(1)); + } + } + } + setAlignmentX(Component.LEFT_ALIGNMENT); + revalidate(); + } + + /**************************************************************** + *******************************************************/ + protected int getNumSpecies() {return spRows.size();} + + protected String getPairIdxWhere() {return pairWhere;} // made in createRowsFromProj + + protected HashMap getSpName2spIdx() {return spName2spIdx;} // DBdata make keys + + // QueryPanel: clear + protected void setClear() { + for (SpeciesRow p : spRows) p.setClear(); + isNoLoc = false; + } + /*************************************************************** + * XXX QueryPanel: when a check box has changed, this is called to activate/deactivate species + * locOnly: Exact: Block, Collinear, or Hit check: no ChkBox, Chr, no Loc + * locChr: Gene, Anno and Single ChkBox, Chr, no Loc + * see two SpeciesRow ActionListener + */ + protected void setChkEnable(boolean isChk, int type, boolean isSelf) { // QueryPanel + isNoLoc = isChk; // even is chr changes, do not enable loc + + for (SpeciesRow p : spRows) { + if (type==locOnly) p.setLocEnable(isChk); + else p.setLocChrEnable(isChk); + } + if (isSelf && type==locChr && isChk) { + SpeciesRow p = spRows.get(1); + p.chkSpActive.setSelected(false); // do not let it change + p.chkSpActive.setEnabled(false); + p.lblChrom.setEnabled(false); p.cmbChroms.setEnabled(false); + } + } + /********** Selections ********************/ + // Return all valid chromosomes (if all, then null) + protected HashSet getGrpIdxSet() {// used in DBdata to filter out non-valid chromosomes + HashSet grpSet = new HashSet (); + for (SpeciesRow sp : spRows) { + HashSet rowSet = sp.getGrpIdx(); // checks for SpIgnore + for (int i : rowSet) grpSet.add(i); + } + if (grpSet.size()==0) return null; + return grpSet; + } + protected String getGrpIdxStr() { // same as above, but return list + String list=null; + for (SpeciesRow sp : spRows) { + HashSet rowSet = sp.getGrpIdx(); + for (int i : rowSet) { + if (list==null) list = i+""""; + else list += "",""+i; + } + } + return list; + } + // Return all selected chromosomes + protected HashSet getSelectGrpIdxSet() {// runMultiGene + HashSet idxSet = new HashSet (); + for (SpeciesRow sp : spRows) { + int index = sp.getSelChrIdx(); //ignore is checked in SpeciesRow + if(index > 0) idxSet.add(index); + } + return idxSet; + } + protected boolean hasSpSelectChr() { // has a selected chromosome + for (SpeciesRow sp : spRows) { + int index = sp.getSelChrIdx(); + if (index>0) return true; + } + return false; + } + protected boolean hasSpAllIgnoreRows() { // if fail, all rows are Ignore + for (SpeciesRow sp : spRows) + if (!sp.isSpIgnore()) return true; + return false; + } + protected boolean hasSpIgnoreRow() {// if fail, no row is disabled + for (SpeciesRow sp : spRows) + if (sp.isSpIgnore()) return true; + return false; + } + + /***** Specific for a species row *****/ + protected int getSpIdxFromSpName(String name) { + if (spName2spIdx.containsKey(name)) + return spName2spIdx.get(name); + else return -1; + } + protected String getSpNameFromSpIdx(int x) { + SpeciesRow p = spIdx2spRow.get(x); + return p.getSpName(); + } + protected int getSpIdxFromChrIdx(int x) { + SpeciesRow p = chrIdx2spRow.get(x); + return p.getSpIdx(); + } + protected String getSpNameFromChrIdx(int x) { + SpeciesRow p = chrIdx2spRow.get(x); + return p.getSpName(); + } + protected String getChrNumFromChrIdx(int x) { + SpeciesRow p = chrIdx2spRow.get(x); + + String [] num = p.getChrNumList(); + String [] idx = p.getChrIdxList(); + String xx = String.valueOf(x); + + for (int i=0; i (); + cmbChroms.addItem(""All""); + for(int x=0; x (); cmbScale.setBackground(Color.WHITE); + cmbScale.addItem(""bp""); cmbScale.addItem(""kb""); cmbScale.addItem(""mb""); + cmbScale.setSelectedIndex(1); + cmbScale.setEnabled(false); + + spRowPanel = Jcomp.createRowPanel(); + spRowPanel.add(chkSpActive); + spRowPanel.add(lblDisplayName); + + Dimension d = lblDisplayName.getPreferredSize(); + d.width = Math.max(d.width, dnameWidth); + lblDisplayName.setPreferredSize(d); lblDisplayName.setMinimumSize(d); + + spRowPanel.add(Box.createHorizontalStrut(1)); // make sure name does not run into chr + spRowPanel.add(lblChrom); spRowPanel.add(cmbChroms); + spRowPanel.add(Box.createHorizontalStrut(5)); + + spRowPanel.add(lblStart); spRowPanel.add(txtStart); + spRowPanel.add(lblStop); spRowPanel.add(txtStop); spRowPanel.add(cmbScale); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setAlignmentX(Component.LEFT_ALIGNMENT); + setBackground(Color.WHITE); + + add(spRowPanel); + add(Box.createVerticalStrut(5)); + } + + protected void setClear() { + cmbChroms.setSelectedIndex(0); txtStart.setText(""""); txtStop.setText(""""); + + lblChrom.setEnabled(true); cmbChroms.setEnabled(true); + lblStart.setEnabled(false); lblStop.setEnabled(false); + txtStart.setEnabled(false); txtStop.setEnabled(false); cmbScale.setEnabled(false); + + chkSpActive.setSelected(true); chkSpActive.setEnabled(false); + } + // Called when another filter using this is checked or unchecked + private boolean isSpIgnore() { + return chkSpActive.isEnabled() && !chkSpActive.isSelected(); + } + + // Called when block, hit, collinear checked or unchecked + private void setLocEnable(boolean isTurnOff) { + lblChrom.setEnabled(true); cmbChroms.setEnabled(true); + if (isTurnOff) { + lblStart.setEnabled(false); lblStop.setEnabled(false); + txtStart.setEnabled(false); txtStop.setEnabled(false); cmbScale.setEnabled(false); + } + else { + boolean isChr = !cmbChroms.getSelectedItem().equals(""All""); + + lblStart.setEnabled(isChr); lblStop.setEnabled(isChr); + txtStart.setEnabled(isChr); txtStop.setEnabled(isChr); cmbScale.setEnabled(isChr); + } + } + private void setLocChrEnable(boolean isChk) {// CAS579c this keep rechecking box with chkSpActive.setSelected(true); + setLocEnable(isChk); + if (isChk) { + chkSpActive.setEnabled(true); + if (!chkSpActive.isSelected()) { // must be checked for these to be enabled + lblChrom.setEnabled(false); cmbChroms.setEnabled(false); + } + } + else { + chkSpActive.setEnabled(false); + } + } + private String getStartFullNum() { // return null (error), 0 (none), number + if (!txtStart.isEnabled()) return ""0""; // CAS579c + String text = txtStart.getText().trim(); + if (text.contains("","")) text = text.replace("","",""""); // allow commas in input + if (text.equals("""") || text.equals(""0"")) return ""0""; + + try { + int temp = Integer.parseInt(text); + if(temp < 0) { + qPanel.showWarnMsg(""Invalid From (start) coordinate '"" + text + ""'""); + return null; + } + if (temp == 0) return ""0""; + return temp + getScaleDigits(); + } + catch(NumberFormatException e) { + qPanel.showWarnMsg(""Invalid From (start) coordinate '"" + text + ""'""); + return null; + } + } + private String getStopFullNum() {// return null (error), 0 (none), number + if (!txtStop.isEnabled()) return ""0""; // CAS579c + String etext = txtStop.getText().trim(); + if (etext.contains("","")) etext = etext.replace("","",""""); // allow commas in input + if (etext.equals("""") || etext.equals(""0"")) return ""0""; + + try { + int end = Integer.parseInt(etext); + if (end <= 0) { + qPanel.showWarnMsg(""Invalid To (end) coordinate '"" + etext + ""'""); + return null; + } + if (end == 0) return ""0""; + + String stext = getStartFullNum(); // check not >= end + if (!stext.equals(""0"")) { + int start = Integer.parseInt(stext); + if (start>=end) { + qPanel.showWarnMsg(""Invalid From (start) '"" + stext + ""' > To (end) '"" + etext + ""'""); + return null; + } + } + return end + getScaleDigits(); + } + catch(NumberFormatException e) { + Popup.showWarningMessage(""Invalid To (end) coordinate '"" + etext + ""'""); + return null; + } + } + private String getScaleDigits() { + if(cmbScale.getSelectedIndex() == 1) return ""000""; + if(cmbScale.getSelectedIndex() == 2) return ""000000""; + return """"; + } + + // for filter summary string + private String getStartkb() { + if (!txtStart.isEnabled()) return """"; // CAS579c + String num = txtStart.getText().trim(); + if (num.equals("""") || num.equals(""0"")) return """"; + if(cmbScale.getSelectedIndex() == 1) return num + ""kb""; + if(cmbScale.getSelectedIndex() == 2) return num + ""mb""; + return num + ""bp""; + } + private String getStopkb() { + if (!txtStop.isEnabled()) return """"; // CAS579c + String num = txtStop.getText().trim(); + if (num.equals("""") || num.equals(""0"")) return """"; + if(cmbScale.getSelectedIndex() == 1) return num + ""kb""; + if(cmbScale.getSelectedIndex() == 2) return num + ""mb""; + return num + ""bp""; + } + private String getSpAbbr() {return spAbbr;} + private String getSpName() {return lblDisplayName.getText();} + private String getSelChrNum() {return (String)cmbChroms.getSelectedItem();} + + private int getSelChrIdx() { // Selected chromosome idx + if (isSpIgnore()) return -1; + + String chr = (String)cmbChroms.getSelectedItem(); + if (chr.equals(""All"")) return -1; + + for (int i=0; i getGrpIdx() { // All chromosomes that will be queried + HashSet grpIdx = new HashSet (); + + if (!cmbChroms.isEnabled()) return grpIdx; // none can be selected + if (isSpIgnore()) return grpIdx; + + int idx = getSelChrIdx(); + if (idx!=-1) { // only one can be selected + grpIdx.add(idx); + return grpIdx; + } + for (int i=0; i cmbChroms = null; + private JLabel lblStart = null, lblStop = null, lblChrom = null; + private JTextField txtStart = null, txtStop = null; + private JComboBox cmbScale = null; + + private int spIdx=0; + private String strCategory = """"; + private String [] chrIdxList; + private String [] chrNumList; + private String spAbbr = """"; + private boolean hasGenes=true; + } // End species row panel + /***************************************************/ + private QueryFrame qFrame = null; + private QueryPanel qPanel = null; + + private String [] selfName = {"""",""""}; // isSelf shared same idx; this is for Summary + private Vector spRows = null; + private HashMap chrIdx2spRow = new HashMap (); + private HashMap spIdx2spRow = new HashMap (); + private HashMap spName2spIdx = new HashMap (); + private String pairWhere=""""; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/QueryPanel.java",".java","60768","1508","package symapQuery; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Vector; +import java.util.HashMap; +import java.util.HashSet; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; + +import database.DBconn2; +import symap.Globals; +import symap.manager.Mproject; +import util.Jcomp; +import util.Jhtml; +import util.Utilities; + +/*************************************************************** + * The QuerySetup panel. Called by QueryFrame, calls qFrame.makeTabTable(sql, sum, isSingle()) + * + * DBData filters: + * Locations - hit ends on two lines + * isAnnoStr - loads all rows then filters in DBdata (see not before makeChkAnnoWhere) + * isGeneNum - have to parse geneTag for suffix (search of number happens with MYSQL) + * isGeneNum - if any SP row deactivated, must fill in the other side in DBdata + * isGeneOlap - MySQL search will not return mate if one has Olap getGrpCoords() { return grpCoords;} // DBdata filter + +// Single + protected boolean isSingle() { return chkSingle.isEnabled() && chkSingle.isSelected(); } + protected boolean isSingleOrphan() { return isSingle() && radOrphan.isSelected();} // WHERE not exists + protected boolean isSingleGenes() { return isSingle() && radSingle.isSelected();} // WHERE + +// Pair Hits + protected boolean isBlock() {return radBlkYes.isEnabled() && radBlkYes.isSelected(); } + private boolean isNotBlock() {return radBlkNo.isEnabled() && radBlkNo.isSelected(); } + + // Annotated (Gene Hit) + protected boolean isEveryStarAnno() { + return (radAnnoEveryStar.isEnabled() && radAnnoEveryStar.isSelected()); + } + protected boolean isEveryAnno() { + return (radAnnoEvery.isEnabled() && radAnnoEvery.isSelected()); + } + protected boolean isOneAnno() {// DBdata filter + return radAnnoOne.isEnabled() && radAnnoOne.isSelected(); + } + protected boolean isBothAnno() { + return (radAnnoBoth.isEnabled() && radAnnoBoth.isSelected()); + } + protected boolean isOlapAnno_ii() { + return (radAnno_ii.isEnabled() && radAnno_ii.isSelected()); + } + private boolean isNoAnno() {return radAnnoNone.isEnabled() && radAnnoNone.isSelected(); } + + // Collinear size + protected boolean isCollinear() {return txtCoSetN.isEnabled() && !radCoSetIgn.isSelected() && txtCoSetN.getText().trim().length()> 0;} + +// Hit>= row + protected boolean isGeneOlapOr(){return radOlapOr.isSelected();} + protected boolean isGeneOlap() { + if (!txtGeneOlap.isEnabled()) return false; + return (getGeneOlap()>0); + } // DBdata filter + protected int getGeneOlap() {return getValidNum(txtGeneOlap.getText().trim());} + +// Exact Row + protected boolean isBlockNum() {return chkBlkNum.isEnabled() && chkBlkNum.isSelected();} + protected boolean isCollinearNum() {return chkCoSetNum.isEnabled() && chkCoSetNum.isSelected();} + private boolean isHitNum() {return chkHitNum.isEnabled() && chkHitNum.isSelected();} + protected boolean isGeneNum() {return chkGeneNum.isEnabled() && chkGeneNum.isSelected();} // mysql for num, DBdata filter for suffix; CAS579c no chk text + + protected String getGeneNum() { // DBdata filter; Text already checked + if (!isGeneNum()) return null; + return txtGeneNum.getText().trim(); + } + +// group + // multi DBdata filter + protected boolean isMultiN() {return chkMultiN.isEnabled() && chkMultiN.isSelected();} + protected boolean isMultiSame() {return radMultiSame.isEnabled() && radMultiSame.isSelected();} + protected boolean isMultiTandem() {return radMultiTandem.isEnabled() && radMultiTandem.isSelected();} + protected int getMultiN() { // Multi; Text already checked + if (!isMultiN()) return 0; + return getValidNum(txtMultiN.getText().trim()); + } + + // Clust DBdata files + protected boolean isClustN() { return chkClustN.isEnabled() && chkClustN.isSelected(); } + protected boolean isClPerSp() { return radClPerSp.isEnabled() && radClPerSp.isSelected(); } + + protected boolean isPGincTrans() { return radIncTrans.isEnabled() && radIncTrans.isSelected(); } + protected boolean isPGIncNoGene() { return radIncNoGene.isEnabled()&& radIncNoGene.isSelected(); } + protected boolean isPGIncOne() { return radIncOne.isEnabled() && radIncOne.isSelected(); } + protected boolean isPGIncIgn() { return radIncIgn.isEnabled() && radIncIgn.isSelected(); } + + protected boolean isClInclude(int sp) { return incSpecies[sp].isEnabled() && incSpecies[sp].isSelected(); } + protected boolean isClExclude(int sp) { return exSpecies[sp].isEnabled() && exSpecies[sp].isSelected();} + protected int getClustN() { // Clust; Text already checked + if (!isClustN()) return 0; + return getValidNum(txtClustN.getText().trim()); + } + protected HashSet getExcSpPos() { + HashSet spIdx = new HashSet (); + for(int p=0; p w) crow.add(Box.createHorizontalStrut(wFil1-w)); + + radCoSetGE = Jcomp.createRadio("">="", ""Show collinear sets >= N""); + radCoSetEQ = Jcomp.createRadio(""="", ""Show collinear sets = N""); + radCoSetLE = Jcomp.createRadio(""<="" , ""Show collinear sets <= N""); + radCoSetIgn = Jcomp.createRadio(""Ignore"", ""Do not search on sets""); + + ButtonGroup g = new ButtonGroup(); + g.add(radCoSetGE); g.add(radCoSetEQ); g.add(radCoSetLE); g.add(radCoSetIgn); + radCoSetIgn.setSelected(true); + crow.add(radCoSetGE); crow.add(Box.createHorizontalStrut(1)); + crow.add(radCoSetEQ); crow.add(Box.createHorizontalStrut(1)); + crow.add(radCoSetLE); crow.add(Box.createHorizontalStrut(1)); + crow.add(radCoSetIgn); + if (!bNoAnno && !bOneAnno) panel.add(crow); + + radCoSetGE.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) {txtCoSetN.setEnabled(true);}}); + radCoSetEQ.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) {txtCoSetN.setEnabled(true);}}); + radCoSetLE.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) {txtCoSetN.setEnabled(true);}}); + radCoSetIgn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) {txtCoSetN.setEnabled(false);}}); + txtCoSetN.setText(coDefNum); txtCoSetN.setEnabled(false); + + return panel; + } + /** Check boxes **/ + private JPanel createFilterPairExactPanel() { + JPanel panel = Jcomp.createPagePanelNB(); + JPanel row = Jcomp.createRowPanel(); + int sp1 = 3, sp2 = 11; + + lblChkExact = Jcomp.createLabel(""Exact"", ""Search for exact string; do not prefix with chromosome numbers""); + row.add(lblChkExact); row.add(Box.createHorizontalStrut(Jcomp.getWidth(wFil2-3, lblChkExact))); + + chkBlkNum = Jcomp.createCheckBox(""Block#"", ""Only the block number"", true); + chkBlkNum.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setExactRow(chkBlkNum.isSelected(), nChkBlk, SpeciesPanel.locOnly); + } + }); + txtBlkNum = Jcomp.createTextField("""", ""Enter Block# only"", 3, true); + row.add(chkBlkNum); row.add(Box.createHorizontalStrut(sp1)); + row.add(txtBlkNum); row.add(Box.createHorizontalStrut(sp2)); + + chkCoSetNum = Jcomp.createCheckBox(""Collinear set#"", ""Only the collinear set number"", true); + chkCoSetNum .addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setExactRow(chkCoSetNum.isSelected(), nChkCoSet, SpeciesPanel.locOnly); + } + }); + txtCoSetNum = Jcomp.createTextField("""", ""Enter Collinear# only"", 3, true); + if (!bNoAnno && !bOneAnno) { + row.add(chkCoSetNum); row.add(Box.createHorizontalStrut(sp1)); + row.add(txtCoSetNum); row.add(Box.createHorizontalStrut(sp2)); + } + chkHitNum = Jcomp.createCheckBox(""Hit#"", ""Enter Hit# (same as column Hit#)"", true); + chkHitNum.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setExactRow(chkHitNum.isSelected(), nChkHit, SpeciesPanel.locOnly); + } + }); + txtHitNum = Jcomp.createTextField("""", ""Enter Hit# "", 4, true); + row.add(chkHitNum); row.add(Box.createHorizontalStrut(sp1)); + row.add(txtHitNum); row.add(Box.createHorizontalStrut(sp2)); + + chkGeneNum = Jcomp.createCheckBox(""Gene#"", ""A Gene# with or without a suffix"", true); + chkGeneNum.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setExactRow(chkGeneNum.isSelected(), nChkGene, SpeciesPanel.locChr); + } + }); + txtGeneNum = Jcomp.createTextField("""", ""Enter Gene# only"", 4, true); + if (!(bNoAnno && bNoPseudo)) {// if noAnno has pseudo, they can be searched on + row.add(chkGeneNum); row.add(Box.createHorizontalStrut(sp1)); + row.add(txtGeneNum); + } + row.setMaximumSize(row.getPreferredSize()); + row.setAlignmentX(LEFT_ALIGNMENT); + panel.add(row); + + return panel; + } + /** Filter Hit attributes - active with all pair searches except Chks **/ + private JPanel createFilterPairHitPanel() {// CAS578 add + JPanel panel = Jcomp.createPagePanelNB(); + JPanel row = Jcomp.createRowPanel(); + + int w=2; + lblHitId = Jcomp.createLabel(""%Id "", ""Approximate percent identity of subhits""); + txtHitId = Jcomp.createTextField(""0"", ""Approximate percent identity of subhits"", w, true); + + lblHitSim = Jcomp.createLabel(""%Sim "", ""Approximate percent similarity of subhits""); + txtHitSim = Jcomp.createTextField(""0"", ""Approximate percent similarity of subhits"", w, true); + + lblHitCov = Jcomp.createLabel(""Cov "", ""Largest summed merged subhit lengths of the two species""); + txtHitCov = Jcomp.createTextField(""0"", ""Largest summed merged subhit lengths of the two species"", w*2, true); + + lblGeneOlap = Jcomp.createLabel(olapDesc + "" %Olap "", olapDesc + "" overlap""); + txtGeneOlap = Jcomp.createTextField(""0"", olapDesc + "" overlap"", w, true); + radOlapOr = Jcomp.createRadio(""Either"", ""At least one has %Olap>=N""); + radOlapAnd = Jcomp.createRadio(""Both"", ""Both have %Olap>=N""); + ButtonGroup o = new ButtonGroup(); o.add(radOlapOr); o.add(radOlapAnd); radOlapOr.setSelected(true); + + w=15; + lblHitGE = Jcomp.createLabel(""Hit >= "", ""Value >= input number""); + row.add(lblHitGE); row.add(Box.createHorizontalStrut(Jcomp.getWidth(wFil2, lblHitGE))); + row.add(lblHitId); row.add(txtHitId); row.add(Box.createHorizontalStrut(w)); + row.add(lblHitSim); row.add(txtHitSim); row.add(Box.createHorizontalStrut(w)); + row.add(lblHitCov); row.add(txtHitCov); + if (!bNoAnno) { + row.add(Box.createHorizontalStrut(w*3)); + row.add(lblGeneOlap); row.add(txtGeneOlap); row.add(Box.createHorizontalStrut(2)); + if (!bOneAnno) {row.add(radOlapOr); row.add(Box.createHorizontalStrut(2)); row.add(radOlapAnd);} + } + + row.setMaximumSize(row.getPreferredSize()); + row.setAlignmentX(LEFT_ALIGNMENT); + panel.add(row); + return panel; + } + /** Filter Multi-hit and Cluster hits **/ + private JPanel createFilterGroupPanel() { + JPanel panel = Jcomp.createPagePanelNB(); + + /* Multi-hit geness */ + JPanel mrow = Jcomp.createRowPanel(); + chkMultiN = Jcomp.createCheckBox(""Multi-hit genes "", ""Genes with multiple hits to the same species; sets Group column"", false); + chkMultiN.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (chkMultiN.isSelected()) { + setChkAll(nChkMulti); // checks off except this one + setCoSetRow(false); + } + else { + setChkAll(nChkNone); + setCoSetRow(true); + } + boolean tip = chkClustN.isSelected() || chkMultiN.isSelected(); + lblGrpTip.setEnabled(tip); + setRefresh(); + }}); + mrow.add(chkMultiN); + + lblMultiN = Jcomp.createLabel("">= "", "">= N hits""); + mrow.add(lblMultiN); + + txtMultiN = Jcomp.createTextField(groupDefNum, "">= N hits"", 3); + mrow.add(txtMultiN); + mrow.add(Box.createHorizontalStrut(5)); + + chkMultiMinor = Jcomp.createCheckBox(""Minor*"", ""If checked, include minor gene hits"", false); + mrow.add(chkMultiMinor); + + mrow.add(Box.createHorizontalStrut(6)); + lblMultiOpp = Jcomp.createLabel("" Opposite: "", ""Opposite chromosome""); + mrow.add(lblMultiOpp); + + radMultiTandem = Jcomp.createRadio(""Tandem"", ""If checked, the N hits for a gene must be to sequential genes""); + if (!bOneAnno) {mrow.add(radMultiTandem); mrow.add(Box.createHorizontalStrut(1));} + + radMultiSame = Jcomp.createRadio(""Same Chr"", ""If checked, the N hits for a gene must be to the same opposite chromosome""); + mrow.add(radMultiSame); mrow.add(Box.createHorizontalStrut(1)); + + radMultiDiff = Jcomp.createRadio(""Diff Chr"", ""If checked, the N hits for a gene can be to any set of chromosomes""); + mrow.add(radMultiDiff); mrow.add(Box.createHorizontalStrut(1)); + + ButtonGroup ag = new ButtonGroup(); + ag.add(radMultiDiff); ag.add(radMultiTandem); ag.add(radMultiSame); radMultiSame.setEnabled(true); + + if (!bNoMulti) {panel.add(mrow); panel.add(Box.createVerticalStrut(5));} + + /* Cluster hits */ + JPanel crow = Jcomp.createRowPanel(); + if (isPgeneF) chkClustN = Jcomp.createCheckBox(""PgeneF"", ""Putative gene families; Sets Group column"", false); + else chkClustN = Jcomp.createCheckBox(""Cluster genes"", ""Cluster overlapping genes; Sets Group column"", false); + + chkClustN.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (chkClustN.isSelected()) { + setChkAll(nChkClust); + setCoSetRow(false); + } + else { + setChkAll(nChkNone); + setCoSetRow(true); + } + boolean tip = chkClustN.isSelected() || chkMultiN.isSelected(); + lblGrpTip.setEnabled(tip); + setRefresh(); + } + }); + chkClustN.setSelected(false); + crow.add(chkClustN); + int w = chkMultiN.getPreferredSize().width; + crow.add(Box.createHorizontalStrut(w - chkClustN.getPreferredSize().width)); + + lblClustN = Jcomp.createLabel("">= "", "">= N""); + crow.add(lblClustN); + + txtClustN = Jcomp.createTextField(groupDefNum, "">= N"", 3); + crow.add(txtClustN); crow.add(Box.createHorizontalStrut(8)); + + // crow for Cluster only; + radClHit = Jcomp.createRadio(""Total hits"", "">=N hits with shared genes""); + radClPerSp = Jcomp.createRadio(""Genes per species"", "">=N unique genes per species""); + if (!isPgeneF) { + crow.add(radClHit); crow.add(Box.createHorizontalStrut(8)); crow.add(radClPerSp); + + ButtonGroup rad = new ButtonGroup(); + rad.add(radClHit); rad.add(radClPerSp); radClHit.setSelected(true); + } + + // crow for PgeneF only; Originally No Annotation, Complete Linkage, At least one checkboxes; now can only select one + lblIncFilters = Jcomp.createLabel(""Include: "", ""Filters for included species""); + radIncOne = Jcomp.createRadio(""At least one"", ""Each group must have at least one of each included species""); + radIncIgn = Jcomp.createRadio(""Ignore"", ""No filters on included species""); + radIncNoGene = Jcomp.createRadio(""No gene"",""The included species may not have hits that align to genes""); + radIncTrans = Jcomp.createRadio(""Linkage"", ""For >2 species: for hits A-B and B-C, there must also be hit A-C""); + + ButtonGroup inc = new ButtonGroup(); + if (isPgeneF) { + crow.add(lblIncFilters); crow.add(Box.createHorizontalStrut(2)); + crow.add(radIncNoGene); crow.add(Box.createHorizontalStrut(2)); + inc.add(radIncNoGene); + + if (nSpecies>2) { + crow.add(radIncOne); crow.add(Box.createHorizontalStrut(2)); + crow.add(radIncTrans); crow.add(Box.createHorizontalStrut(2)); + crow.add(radIncIgn); crow.add(Box.createHorizontalStrut(2)); + inc.add(radIncOne); inc.add(radIncTrans); inc.add(radIncIgn); radIncOne.setSelected(true); + } + else { + crow.add(radIncIgn); crow.add(Box.createHorizontalStrut(2)); + inc.add(radIncIgn); radIncIgn.setSelected(true); + } + } + if (!bNoClust) panel.add(crow); // Vertical box in if statement + + // Include/exclude + Vector theProjects = qFrame.getProjects(); + speciesName = new String [nSpecies]; + speciesAbbr = new String [nSpecies]; + incSpecies = new JCheckBox[nSpecies]; // vector of checkboxes + for(int x=0; x0); + radIncNoGene.setEnabled(cnt>0); + radIncTrans.setEnabled(cnt>0); + radIncIgn.setEnabled(cnt>0); + } + }); + } + exSpecies = new JCheckBox[theProjects.size()]; + for(int x=0; x0); + radIncNoGene.setEnabled(cnt>0); + radIncTrans.setEnabled(cnt>0); + radIncIgn.setEnabled(cnt>0); + } + }); + } + + lblInclude = Jcomp.createLabel("" Include: ""); + lblExclude = Jcomp.createLabel("" Exclude: ""); + if (nSpecies>2 && !bNoClust) { + JPanel row = Jcomp.createRowPanel(); + + row.add(lblInclude); + for(int x=0; x0); + radIncNoGene.setEnabled(cnt>0); + radIncTrans.setEnabled(cnt>0); + radIncIgn.setEnabled(cnt>0); + } + // Single and Anno can both be checked at same time; both turn on locChr; + // Single turns off everything else; Anno only turns off Exact + private void setAnnoSingleRow() {// CAS579c add + boolean bSingle = chkSingle.isSelected(); + boolean bAnno = isAnnoStr(); + + txtAnno.setEnabled(bAnno); + + if (bSingle) { + setChkAll(nChkSingle); // Disable Exact rows + setRadioRows(false); + setHitRow(false); + spPanel.setChkEnable(true, SpeciesPanel.locChr, isSelf); + } + else if (bAnno) { + setChkAll(nChkSingle); // disable Exact + chkSingle.setEnabled(true); chkSingle.setSelected(false); // Now enable single check + radOrphan.setEnabled(false); radSingle.setEnabled(false); + + setRadioRows(true); + setHitRow(true); + spPanel.setChkEnable(true, SpeciesPanel.locChr, isSelf); + } + else { + setChkAll(nChkNone); + setRadioRows(true); + setHitRow(true); + spPanel.setChkEnable(false, SpeciesPanel.locChr, isSelf); + } + + setRefresh(); + } + // In Block, Annotated (Gene), CoSet, Clear + private void setRadioRows(boolean b) { + lblBlkOpts.setEnabled(b); radBlkYes.setEnabled(b);radBlkNo.setEnabled(b);radBlkIgn.setEnabled(b); + + lblAnnoOpts.setEnabled(b); radAnnoEvery.setEnabled(b);radAnnoEveryStar.setEnabled(b); + radAnnoOne.setEnabled(b); radAnnoBoth.setEnabled(b); radAnno_ii.setEnabled(b); + radAnnoNone.setEnabled(b); radAnnoIgn.setEnabled(b); + + setCoSetRow(b); + } + // Coset row - as needed for Groups + private void setCoSetRow(boolean b) { + lblCoSetN.setEnabled(b); txtCoSetN.setEnabled(b); + radCoSetGE.setEnabled(b); radCoSetEQ.setEnabled(b); + radCoSetLE.setEnabled(b); radCoSetIgn.setEnabled(b); + + if (b) txtCoSetN.setEnabled(!radCoSetIgn.isSelected()); + else txtCoSetN.setEnabled(b); + } + + // Hit panel: called by setClearDefaults, setExactRow, setSingleRow + private void setHitRow(boolean b) { + lblHitGE.setEnabled(b); + lblHitId.setEnabled(b); txtHitId.setEnabled(b); + lblHitSim.setEnabled(b); txtHitSim.setEnabled(b); + lblHitCov.setEnabled(b); txtHitCov.setEnabled(b); + lblGeneOlap.setEnabled(b); txtGeneOlap.setEnabled(b); + radOlapOr.setEnabled(b); radOlapAnd.setEnabled(b); + } + + // Exact (Block, Hit, Collinear, Gene); + // nChk is the number representing Checkbox, type is Species settings for Species Check and Start/end + private void setExactRow(boolean isSel, int nChk, int type) { + if (isSel) setChkAll(nChk); + else setChkAll(nChkNone); + + setRadioRows(!isSel); + setHitRow(!isSel); + + chkAnno.setEnabled(!isSel); + txtAnno.setEnabled(!isSel); + + spPanel.setChkEnable(isSel, type, (isSelf && nChk==nChkSingle)); + + setRefresh(); + } + + // panels do not repaint right on enable if this is not included + private void setRefresh() { + searchPanel.revalidate(); searchPanel.repaint(); + singlePanel.revalidate(); singlePanel.repaint(); + pairRadPanel.revalidate(); pairRadPanel.repaint(); + pairChkPanel.revalidate(); pairChkPanel.repaint(); + groupPanel.revalidate(); groupPanel.repaint(); + } + protected void showWarnMsg(String msg) { + JOptionPane.showMessageDialog(null, msg, ""Warning"", JOptionPane.WARNING_MESSAGE); + } + private int getValidNum(String text) { + try { + return Integer.parseInt(text); + } + catch (Exception e) {return -1;} + } + protected void setQueryButton(boolean b) { + if (b) btnExecute.setText(""Run Query""); + else btnExecute.setText(""Running...""); + btnExecute.setEnabled(b); + } + + /*************************************************************** + * XXX Make Query: All SQL and Summary methods CAS579c + */ + private class SQL { + private boolean bValidQuery=true; + + private String makeSQLclause() { + grpCoords.clear(); // in case makeSpChrWhere is not called + + bValidQuery=true; + TableColumns theFields = TableColumns.getFields(isIncludeMinor(), qFrame.isAlgo2()); + boolean bSingle = isSingle(); + + String sql = ""SELECT "" + theFields.getDBFieldList(bSingle); + if (bSingle) sql += makeSQLsingle(); + else sql += makeSQLpair(theFields.getJoins()); + + if (!bValidQuery) return null; + return sql; + } + /**************************************************** + * Single all genes: + * SELECT PA.idx, PA.grp_idx, PA.start, PA.end, PA.strand, PA.name, PA.tag, PA.numhits + * FROM pseudo_annot AS PA + * WHERE PA.type='gene' AND PA.grp_idx in (1,2,4,3) order by PA.idx + */ + private String makeSQLsingle() { + boolean bOrphan = isSingleOrphan(); + + String from = "" FROM pseudo_annot AS "" + Q.PA; + + String whereClause; + if (bOrphan) whereClause = "" WHERE not exists "" + + ""\n(SELECT * FROM pseudo_hits_annot AS PHA "" + + ""\nLEFT JOIN pseudo_hits as PH on PH.idx=PHA.hit_idx "" + // join to restrict pairs + ""\nWHERE PA.idx=PHA.annot_idx and "" + spPanel.getPairIdxWhere() + "") and ""; + else + whereClause= ""\nWHERE ""; + + whereClause += "" PA.type='gene'""; + + // Annotation + if (isAnnoStr()) { + String annoStr = txtAnno.getText(); + if (annoStr.equals("""")) { + showWarnMsg(""No annotation string entered\n""); + bValidQuery=false; + return """"; + } + String anno = ""PA.name LIKE '%"" + annoStr + ""%'""; + whereClause = makeJoinBool(whereClause, anno, AND); + } + String grp = ""(PA.grp_idx IN ("" + spPanel.getGrpIdxStr() + "")) ""; + whereClause = makeJoinBool(whereClause, grp, AND); + + if (!bOrphan) whereClause += "" order by PA.idx""; + + return from + whereClause; + } + + /********************************************************* + * Pair: + * SELECT PA.idx, PA.grp_idx, PA.start, PA.end, PA.strand, PA.name, PA.tag, PA.numhits, + * PH.idx, PH.hitnum, + * PH.proj1_idx, PH.proj2_idx, PH.grp1_idx, PH.grp2_idx, PH.start1, PH.start2, PH.end1, PH.end2, + * PH.pctid, PH.cvgpct, PH.countpct, PH.strand, PH.score, PH.htype, PH.runsize, PH.runnum, + * B.blocknum, B.score, + * PH.annot1_idx, PH.annot2_idx # not displayed, used to join two rows; allGenes PHA.annot_idx, PHA.annot2_idx + * FROM pseudo_hits AS PH + * LEFT JOIN pseudo_hits_annot AS PHA ON PH.idx = PHA.hit_idx + * LEFT JOIN pseudo_annot AS PA ON PHA.annot_idx = PA.idx + * LEFT JOIN pseudo_block_hits AS PBH ON PBH.hit_idx = PH.idx + * LEFT JOIN blocks AS B ON B.idx = PBH.block_idx where PH.pair_idx=1 ORDER BY PH.hitnum asc + * Hit SELECT "" + getDBFieldList() + "" FROM pseudo_hits AS "" + Q.PH + whereClause + * isOneAnno and annotation requires post-processing, though anno exists is checked below + * pseudo_hits: pctid=avg %id mummer, cvgpct=avg %sim, score=summed length + * pseudo_hits_annot: olap, exlap - use Q.olapCol + */ + private String makeSQLpair(String join) { + // these are the only text boxes not checked until computed + if (isMultiN()) isValidMulti(); if (!bValidQuery) return """"; + if (isClustN()) isValidCluster(); if (!bValidQuery) return """"; + if (isGeneOlap()) isValidHit(txtGeneOlap, ""Olap""); if (!bValidQuery) return """"; + if (isGroup()) isOneChrChkOnly(); if (!bValidQuery) return """";// CAS579b they do not work + if (isNoAnno()) isNoAnnoOnly(); if (!bValidQuery) return """";// CAS579c make sure this is not selected with anno + + // The where clause is fully computed, and the bValidQuery checked at the end in makeSQLclause + String whereClause = ""\n where "" + spPanel.getPairIdxWhere(); // PH.pair_idx in (...) + + // General: these work with almost everything (disabled if not) + String chrLoc = makeSpLocWhere(); + whereClause = makeJoinBool(whereClause, chrLoc, AND); + + if (isAnnoStr()) { + whereClause = makeJoinBool(whereClause, makeChkAnnoWhere(), AND); + } + + if (isSelf) { // DIR_SELF + int g1 = spPanel.getSelChrIdx(0); + int g2 = spPanel.getSelChrIdx(1); + + if (g1 == -1 && g2 == -1) { + whereClause = makeJoinBool(whereClause, ""PH.refidx=0"", AND); + } + else if (g1>0 && g2>0) { + if (g1>g2) whereClause = makeJoinBool(whereClause, ""PH.refidx=0"", AND); // grp1>grp2 lower tile + else if (g10"", AND); // grp1PH.start2"", AND); // below the diagonal (do not use PH.refidx=0) + } + else { // select 1 grpIdx + String locStr = ""((PH.grp1_idx>=PH.grp2_idx and PH.refidx=0) "" + + "" or (PH.grp1_idx0))""; + whereClause = makeJoinBool(whereClause, locStr, AND); + } + } + + // Exact: only one can be selected + if (isHitNum()) { + whereClause = makeJoinBool(whereClause, makeChkHitWhere(), AND); + } + else if (isGeneNum()) { // check suffix in DBdata.passFilters + whereClause = makeJoinBool(whereClause, makeChkGeneNumWhere(), AND); + } + else if (isBlockNum()) { // if block, only anno filter and chromosome + whereClause = makeJoinBool(whereClause, makeChkBlockWhere(), AND); + } + else if (isCollinearNum()) { // if collinear, only anno filter and chromosome + whereClause = makeJoinBool(whereClause, makeChkCollinearWhere(), AND); + } + // Everything else + else { + // Hit>= + if (isValidHit(txtHitId, ""%Id"")) whereClause = makeJoinBool(whereClause, ""PH.pctid>="" + txtHitId.getText().trim(), AND); + if (isValidHit(txtHitSim, ""%Sim"")) whereClause = makeJoinBool(whereClause, ""PH.cvgpct>="" + txtHitSim.getText().trim(), AND); + if (isValidHit(txtHitCov, ""Cov"")) whereClause = makeJoinBool(whereClause, ""PH.score>="" + txtHitCov.getText().trim(), AND); + // Olap is done in DBdata because it checks all; will not return mate if one is < and the other >= + + // Block o Yes o No + if (isBlock()) whereClause = makeJoinBool(whereClause, ""PBH.block_idx is not null"", AND); + else if (isNotBlock()) whereClause = makeJoinBool(whereClause, ""PBH.block_idx is null"", AND); + + // Annotate (Gene) + if (isNoAnno()) { + whereClause = makeJoinBool(whereClause, ""PH.gene_overlap=0"", AND); + } + else if (isOneAnno()) {// finished in DBdata + whereClause = makeJoinBool(whereClause, ""PH.gene_overlap=1"", AND); + } + else if (isBothAnno()) { + whereClause = makeJoinBool(whereClause, ""PH.gene_overlap=2"", AND); + } + else if (isEveryAnno() || isEveryStarAnno() || isAnnoStr() || isOlapAnno_ii()) { + whereClause = makeJoinBool(whereClause, ""PH.gene_overlap>0"", AND); + } + // Groups + else if (!isPgeneF && (isMultiN() || isClustN())) {// pgenef not included because it can have all g0 + if (isClustN()) isValidCluster(); + if (isMultiTandem()) whereClause = makeJoinBool(whereClause, ""PH.gene_overlap=2"", AND); + else whereClause = makeJoinBool(whereClause, ""PH.gene_overlap>0"", AND); + } + // Collinear size o >= o < o = + int n = isCoSetSzN(true); + String op = ""PH.runsize>="" + n; + if (radCoSetEQ.isSelected()) op = ""PH.runsize="" + n; + else if (radCoSetLE.isSelected()) op = ""PH.runsize>0 and PH.runsize<="" + n; + if (n>0) whereClause = makeJoinBool(whereClause, op, AND); + } + String order = ""\n ORDER BY PH.hitnum asc""; + return "" FROM pseudo_hits AS "" + Q.PH + join + "" "" + whereClause + order; + } + + /******************************************************** + * Search; Convert filter string to where statement + *****/ + /* Make annotation string */ + // 1. the following is no faster and needs special processing; (PA.name LIKE '%"" + annoStr + ""%') ""; + // if PA.name was changed to VARCHAR, it would be faster + // 2. limiting rows based on chrs requires getting the other half in DBdata (like geneNum) - can be a lot of rows + // DBdata filters all rows + private String makeChkAnnoWhere() { + String annoStr = txtAnno.getText().trim(); + + if (annoStr.equals("""")) { + showWarnMsg(""No annotation string entered\n""); + bValidQuery=false; + return """"; + } + String where = "" (PH.annot1_idx>0 or PH.annot2_idx>0) and PH.gene_overlap>0""; + return where; + } + private String makeChkBlockWhere() { + String block = txtBlkNum.getText().trim(); + + int n = getValidNum(block); + if (n>0) return ""B.blocknum="" + n; + + showWarnMsg(""Invalid block number '"" + block + ""'. Should be single number.\n"" + + "" Set chromosomes to narrow it down to a block, e.g. Chr1.Chr2.B where B=block""); + txtBlkNum.setText(""""); + bValidQuery=false; + return """"; + } + private String makeChkCollinearWhere() { + String run = txtCoSetNum.getText().trim(); + + int n = getValidNum(run); + if (n>0) return ""PH.runnum="" + n; + + showWarnMsg(""Invalid collinear set '"" + run + ""'. Should be single number.\n"" + + ""e.g. Collinear 2.3.100.3 has set number 100.\n"" + + "" A set number can occur for every pair, so set the chromosomes to narrow down to a single set.""); + bValidQuery=false; + return """"; + } + private String makeChkHitWhere() { + String num = txtHitNum.getText().trim(); + + int n = getValidNum(num); + if (n>0) return ""PH.hitnum="" + n; + + showWarnMsg(""Invalid hit# '"" + num + ""'. Should be single number.\n""); + txtHitNum.setText(""""); + bValidQuery=false; + return """"; + } + private String makeChkGeneNumWhere() { + String gnTxt = txtGeneNum.getText().trim(); + + String gnStr = gnTxt; + if (!gnStr.equals("""") && Utilities.isValidGenenum(gnStr)) { + if (gnStr.contains(""."")) { + if (gnStr.endsWith(""."")) gnStr = gnStr.substring(0, gnStr.indexOf(""."")); + if (gnStr.contains(""."")) { + String [] tok = gnStr.split(""\\.""); + int x = Utilities.getInt(tok[0]); + if (x != -1) gnStr = x+""""; + else gnStr = """"; + } + } + } else gnStr=""""; + + if (gnStr.equals("""")) { + showWarnMsg(""The Gene# entered is '"" + gnTxt + + ""', which is not a valid Gene#. \nEnter a number, or number.suffix\n""); + txtGeneNum.setText(""""); + bValidQuery=false; + return """"; + } + String where = "" (PH.annot1_idx>0 or PH.annot2_idx>0) and PA.genenum="" + gnStr; + String grp = ""(PA.grp_idx IN ("" + spPanel.getGrpIdxStr() + "")) ""; + where = makeJoinBool(where, grp, AND); + + return where; + } + + // The chromosomes are queried in MySQL and the locations in DBdata; Works for both orphan and hit + // This only works for Chr and Loc; ignored are in Single, Anno, and Gene + private String makeSpLocWhere() { + if (!spPanel.hasSpAllIgnoreRows()) { + showWarnMsg(""At least one species must be checked (i.e. before Species name).""); + bValidQuery=false; + return """"; + } + String grpList="""", where=""""; + grpCoords.clear(); + + // First check to see if any chromosomes are selected; if not, then pairIdx is sufficient + if (!spPanel.hasSpSelectChr() && !spPanel.hasSpIgnoreRow()) return """"; + + // CAS579c was checking if species=2, and the results worked only part of the time (the ones I tested) + for(int p=0; p 0) cnt++;; + } + if (cnt<=1) return true; + + showWarnMsg(""Only one chromosome may be selected for a Gene# or Group search\n""); + bValidQuery=false; + return false; + } + private void isNoAnnoOnly() { // CAS579c add to disallow + String msg=null; + if (isAnnoStr()) msg = ""None (no annotated) is set with annotation description""; + else if (isGeneOlap())msg = ""None (no annotated) is set with Olap (requiring gene overlap)""; + else if (isMultiN()) msg = ""None (no annotated) is set with Multi-hit gene""; + else if (isClustN()) msg = ""None (no annotated) is set with Cluster gene""; + else return; + + showWarnMsg(msg + ""\nThis will produce 0 results.""); + bValidQuery=false; + return; + } + /* Size for Collinear set */ + private int isCoSetSzN(boolean prt) { + if (!txtCoSetN.isEnabled() || radCoSetIgn.isSelected()) return 0; + String ntext = txtCoSetN.getText(); + if (ntext.length()==0) { + if (prt) showWarnMsg(""Colliner size is blank: must be positive number."" + + ""\ne.g. Collinear 2.3.100.3 - the size is 3.""); + bValidQuery=false; + return 0; + } + try { + int n = Integer.parseInt(ntext); + if (n<0) { + if (prt) showWarnMsg(""Invalid Colliner size ("" + ntext + ""), must be positive."" + + ""\n e.g. Collinear 2.3.100.3 - the size is 3.""); + bValidQuery=false; + return 0; + } + return n; + } catch (Exception e) { + if (prt) showWarnMsg(""Invalid Colliner integer (""+ ntext + "")"" ); + bValidQuery=false; + }; + return 0; + } + /* Hit >=: for all 4 Hit values */ + private boolean isValidHit(JTextField hitTxt, String col) { + if (!hitTxt.isEnabled()) return false; + + String num = hitTxt.getText().trim(); + if (num.equals("""") || num.equals(""0"")) return false; + + int n = getValidNum(num); + if (n==0) return false; + if (n>0) return true; + + showWarnMsg(""Invalid Hit '"" + col + ""'. Should be single positive number.\n""); + hitTxt.setText(""0""); + bValidQuery=false; + return false; + } + private boolean isValidMulti() { + if (!txtMultiN.isEnabled()) return true; + String ntext = txtMultiN.getText(); + + int n = getValidNum(ntext); + if (n>1) return true; + + showWarnMsg(""Invalid Multi size ("" + ntext + ""). Must be >1.""); + bValidQuery=false; + txtMultiN.setText(groupDefNum); + return false; + } + private boolean isValidCluster() { + if (!txtClustN.isEnabled()) return true; + String ntext = txtClustN.getText(); + + int n = getValidNum(ntext); + if (n<=0) { + showWarnMsg(""Invalid Clust size ("" + ntext + ""). Must greater than 0.""); + bValidQuery=false; + txtClustN.setText(groupDefNum); + return false; + } + int cnt=0; + for (int i = 0; i < nSpecies; i++){ + if (isClInclude(i)) cnt++; + } + if (cnt>1) return true; + + showWarnMsg(""Must have at least two included species\n""); + bValidQuery=false; + return false; + } + /******************************************************* + * Summary + */ + private String makeSummary() { + int numSpecies = spPanel.getNumSpecies(); + if(numSpecies ==0) return ""No species""; // not possible? + + String retVal=""""; + String anno = (isAnnoStr()) ? txtAnno.getText() : """"; + String loc = makeSummaryLoc(); + + retVal = makeJoinDelim(retVal, anno, ""; ""); + retVal = makeJoinDelim(retVal, loc, ""; ""); + + if (isSingle()) { + retVal = (isSingleOrphan()) ? ""Single Orphan genes"" : ""Single All genes""; + retVal = makeJoinDelim(retVal, loc, ""; ""); + retVal = makeJoinDelim(retVal, anno, ""; ""); + return retVal; + } + if (isHitNum()) { + retVal = makeJoinDelim(retVal, ""Hit#=""+txtHitNum.getText().trim(), ""; ""); + } + else if (isBlockNum()) { + retVal = makeJoinDelim(retVal, ""Block=""+txtBlkNum.getText().trim(), ""; ""); + } + else if (isCollinearNum()) { + retVal = makeJoinDelim(retVal, ""Collinear set ""+txtCoSetNum.getText().trim(), ""; ""); + } + else if (isGeneNum()) { + retVal = makeJoinDelim(retVal, ""Gene# ""+txtGeneNum.getText().trim(), ""; ""); + } + else { + if (isBlock()) retVal = makeJoinDelim(retVal, ""Block hits"", ""; ""); + else if (isNotBlock()) retVal = makeJoinDelim(retVal, ""No Block hits"", ""; ""); + + if (isEveryStarAnno()) retVal = makeJoinDelim(retVal, ""Every Gene +minor"", ""; ""); // must be before next if + else if (isEveryAnno()) retVal = makeJoinDelim(retVal, ""Every Gene"", ""; ""); + else if (isOneAnno()) retVal = makeJoinDelim(retVal, ""One Gene"", ""; ""); + else if (isBothAnno()) retVal = makeJoinDelim(retVal, ""Both Gene"", ""; ""); + else if (isNoAnno()) retVal = makeJoinDelim(retVal, ""No Gene hits"", ""; ""); + else if (isOlapAnno_ii()) { // -ii can do Minor or overlapping + if (isMinorOlap) retVal = makeJoinDelim(retVal, ""Minor genes"", ""; ""); + else retVal = makeJoinDelim(retVal, ""Overlapping genes"", ""; ""); + } + + int n = isCoSetSzN(false); + if (n>0) { + String op = "">=""; + if (radCoSetEQ.isSelected()) op = ""=""; + else if (radCoSetLE.isSelected()) op = ""<=""; + retVal = makeJoinDelim(retVal, ""Collinear size"" + op + n, ""; ""); + } + + if (isValidHit(txtHitId, ""%Id"")) retVal = makeJoinDelim(retVal, ""%Id>="" + txtHitId.getText().trim(), ""; ""); + if (isValidHit(txtHitSim, ""%Sim""))retVal = makeJoinDelim(retVal, ""%Sim>="" + txtHitSim.getText().trim(), ""; ""); + if (isValidHit(txtHitCov, ""Cov"")) retVal = makeJoinDelim(retVal, ""Cov>="" + txtHitCov.getText().trim(), ""; ""); + if (isValidHit(txtGeneOlap, ""%Olap"")) { + String or = (isGeneOlapOr()) ? "" (Either) "" : "" (Both) ""; + retVal = makeJoinDelim(retVal, olapDesc + "" Olap>="" + txtGeneOlap.getText().trim() + or, ""; ""); + } + + if (isMultiN()) { + String multi = ""Multi >="" + getMultiN(); + if (chkMultiMinor.isSelected()) multi += ""*""; + + if (radMultiSame.isSelected()) multi += "", Same Chr""; + else if (radMultiDiff.isSelected()) multi += "", Diff Chr""; + else if (radMultiTandem.isSelected())multi += "", Tandem""; + retVal = makeJoinDelim(retVal, multi, ""; ""); + } + + if (isClustN()) { + String clust = ""Cluster >="" + getClustN(); + if (isClPerSp()) clust += "" unique genes""; + else clust += "" hits""; + if (nSpecies>2) { + String inc="""", exc=""""; + int incCnt=0; + for (int i=0; i grpCoords = new HashMap (); + + // FilterSingle + private JCheckBox chkSingle = null; + private JRadioButton radOrphan = null, radSingle=null; + + // FilterPairRad - block, anno, coset + private JLabel lblBlkOpts = null; + private JRadioButton radBlkYes, radBlkNo, radBlkIgn; + + private JLabel lblAnnoOpts = null; + private JRadioButton radAnnoEvery, radAnnoEveryStar, radAnnoOne, radAnnoBoth, radAnnoNone, + radAnno_ii, radAnnoIgn; // -ii only + + private JTextField txtCoSetN = null; + private JLabel lblCoSetN = null; + private JRadioButton radCoSetGE, radCoSetEQ, radCoSetLE, radCoSetIgn; + + // FilterPair hit attributes + private JLabel lblHitGE, lblHitId, lblHitSim, lblHitCov, lblGeneOlap; + private JTextField txtHitId = null, txtHitSim = null, txtHitCov = null, txtGeneOlap = null; + private JRadioButton radOlapOr = null, radOlapAnd = null; + + // FilterPairChk + private JLabel lblChkExact; + private JCheckBox chkBlkNum = null, chkCoSetNum = null, chkHitNum = null, chkGeneNum = null; + private JTextField txtBlkNum = null, txtCoSetNum = null, txtHitNum = null, txtGeneNum = null; + + // FilterGroup + private JLabel lblGrpTip; + private JCheckBox chkMultiN = null; + private JTextField txtMultiN = null; + private JLabel lblMultiN = null, lblMultiOpp = null; + private JRadioButton radMultiSame=null, radMultiTandem=null, radMultiDiff=null; + private JCheckBox chkMultiMinor = null; + + private JCheckBox chkClustN = null; + private JTextField txtClustN = null; + private JLabel lblClustN = null; + private JRadioButton radClPerSp = null, radClHit; + private JCheckBox [] incSpecies = null, exSpecies = null; + private String [] speciesName = null; + private String [] speciesAbbr = null; + private JRadioButton radIncOne = null, radIncNoGene = null, radIncTrans = null, radIncIgn = null; + private JLabel lblInclude = null, lblExclude = null, lblIncFilters = null; + + private JButton btnExecute = null; + + // Not big enough to bother adding buttons to pnlStepOne.expand(); pnlStepOne.collapse() + private CollapsiblePanel pnlStep1 = null, pnlStep2 = null, pnlStep3 = null, pnlStep4 = null; + private QueryFrame qFrame = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/ComputePgeneF.java",".java","16181","495","package symapQuery; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; + +import javax.swing.JTextField; + +import util.ErrorReport; +import backend.Utils; +import symap.Globals; + +/********************************************************** + * Original pgenef algorithm; now replaces Multi if run with -g + */ +public class ComputePgeneF { + // Group the hits based on overlap on one side or the other. + // The hits have to be binned by location in order to avoid all-against-all searches. + // Aside from that it's just building a graph and finding the connected pieces. + // + // If they've chosen ""include only"", then we build the groups ONLY with hits between included species. + // Otherwise, we build the groups first, and then apply the include/exclude, as follows: + // includes: the group must hit ALL the included species + // excludes: the group must not hit ANY of the excluded species + // + // Output: + private HashMap hitIdx2Grp; // hitID to PgeneF num + private HashMap pgfSizes; // PgeneF sizes + + // Summary counts + private HashMap proj2regions = new HashMap (); + private HashMap projMap; + + // Input: + private QueryPanel qPanel; + private Vector rows; + private JTextField progress; + + //From query panel + private Vector > allIncChrBySp = new Vector>(); + private TreeSet allExcChr = new TreeSet(); + private TreeSet allIncChr = new TreeSet(); + private boolean incOnly, unAnnotOnly, isLinkage; + + // Working + private final int binsize = 100000; + private HashMap>> bins = + new HashMap>>(); // 1st index, grp; 2nd index, location bin + + private HashMap> hit2grp = new HashMap>(); + private HashMap grp2proj = new HashMap(); + + public ComputePgeneF( + Vector rowsFromDB, + QueryPanel lQueryPanel, + JTextField progress, + + HashMap hitIdx2Grp, + HashMap pgfSizes, + + HashMap projMap) { + + this.rows = rowsFromDB; + this.qPanel = lQueryPanel; + this.progress = progress; + + this.hitIdx2Grp = hitIdx2Grp; + this.pgfSizes = pgfSizes; + + this.projMap = projMap; + + computeGroups(); + + int n = qPanel.getClustN(), nGrpNum=1; + HashMap nhitIdx2Grp = new HashMap(); + HashMap ngrpSizes = new HashMap(); + HashMap old2new = new HashMap(); + + for (int hitIdx : hitIdx2Grp.keySet()) { + int oGrpNum = hitIdx2Grp.get(hitIdx); + int sz = pgfSizes.get(oGrpNum); + if (sz>=n) { + int ngrp; + if (old2new.containsKey(oGrpNum)) ngrp = old2new.get(oGrpNum); + else { + ngrp = nGrpNum++; + old2new.put(oGrpNum, ngrp); + } + nhitIdx2Grp.put(hitIdx, ngrp); + ngrpSizes.put(ngrp, sz); + } + } + Globals.tprt(String.format(""Rows: %,d Orig: %,d (%,d) New %,d (%,d)"", + rows.size(), hitIdx2Grp.size(), pgfSizes.size(), nhitIdx2Grp.size(), ngrpSizes.size())); + old2new.clear(); + + // update in/out structures + hitIdx2Grp.clear(); pgfSizes.clear(); + + for (int hitIdx : nhitIdx2Grp.keySet()) hitIdx2Grp.put(hitIdx, nhitIdx2Grp.get(hitIdx)); + for (int grpNum : ngrpSizes.keySet()) pgfSizes.put(grpNum, ngrpSizes.get(grpNum)); + + if (n>1) projMap.clear(); // incorrect after N removal + } + /************************************************************/ + private void computeGroups() { + try { + init(); + + int rowNum=0; + for (DBdata dd : rows){ + if(progress != null) { + if(progress.getText().equals(""Cancelled"")) return; + } + parseRowAndBin(dd); // creates hit2grp, bins included hits + if (rowNum%Q.INC ==0) + progress.setText(""PgeneF "" + rowNum + "" rows""); + rowNum++; + } + + // used to index into incCount array; where i is the species + TreeMap chrIdxTmp = new TreeMap(); + for (int sp = 0; sp < allIncChrBySp.size(); sp++) { + for (int gidx : allIncChrBySp.get(sp)) + chrIdxTmp.put(gidx,sp); + } + + // count the distinct regions on each chr and how many are annotated. + // This can be done group by group since whenever two regions overlap, + // their hits will be in the same group. + int grpNum=0; + + /** Loop through hits **/ + + Set hitList = hit2grp.keySet(); // since we alter hit2grp within + for (int hidx : hitList){ + // First remove the duplicate hits from this grp -- don't think this is necessary + HashSet fixedGrp = new HashSet(); + fixedGrp.addAll(hit2grp.get(hidx)); + hit2grp.put(hidx, fixedGrp); + + /** Exclude hits that don't pass the interface checks **/ + + // Each PgeneF group must have at least one hit from the + // Included species (this could have been done with spIdx) + if (allIncChrBySp.size() > 0) { + int[] chrCnt = new int[allIncChrBySp.size()]; + for (rhit h : hit2grp.get(hidx)) + { + if (chrIdxTmp.containsKey(h.gidx1)){ + int idx = chrIdxTmp.get(h.gidx1); + chrCnt[idx]++; + } + if (chrIdxTmp.containsKey(h.gidx2)) { + int idx = chrIdxTmp.get(h.gidx2); + chrCnt[idx]++; + } + } + boolean pass = true; + for (int i = 0; i < chrCnt.length; i++) { + if (chrCnt[i] == 0) { + pass = false; + break; + } + } + if (!pass) continue; + } + // Exclude selected species and Include 'No annotation of hits' + if (allExcChr.size() > 0 || allIncChr.size() > 0) { + boolean pass = true; + for (rhit h : hit2grp.get(hidx)){ + if (allExcChr.contains(h.gidx1) || allExcChr.contains(h.gidx2)) { + pass = false; + break; + } + if (unAnnotOnly){ + if (allIncChr.contains(h.gidx1)) { + if (h.annot1) { + pass = false; + break; + } + } + if (allIncChr.contains(h.gidx2)) { + if (h.annot2) { + pass = false; + break; + } + } + } + } + if (!pass) continue; + } + // Complete Linkage + if (isLinkage) { + HashMap> links = new HashMap>(); + for (rhit h : hit2grp.get(hidx)){ + if (allIncChr.contains(h.gidx1)) { + if (!links.containsKey(h.pidx1)) { + links.put(h.pidx1, new HashSet()); + } + links.get(h.pidx1).add(h.pidx2); + } + if (allIncChr.contains(h.gidx2)) { + if (!links.containsKey(h.pidx2)) { + links.put(h.pidx2, new HashSet()); + } + links.get(h.pidx2).add(h.pidx1); + } + } + int np = links.keySet().size(); + + boolean pass = true; + for (int pidx : links.keySet()) { + if (links.get(pidx).size() < np-1) { + pass = false; + break; + } + } + if (!pass) continue; + } + grpNum++; + HashMap pcounts = new HashMap(); + + // Count the regions in this group + HashMap> slist = new HashMap>(); + HashMap> elist = new HashMap>(); + HashMap> alist = new HashMap>(); + for (rhit h : hit2grp.get(hidx)){ + if (!slist.containsKey(h.gidx1)) { + slist.put(h.gidx1, new Vector()); + elist.put(h.gidx1, new Vector()); + alist.put(h.gidx1, new Vector()); + } + if (!slist.containsKey(h.gidx2)) { + slist.put(h.gidx2, new Vector()); + elist.put(h.gidx2, new Vector()); + alist.put(h.gidx2, new Vector()); + } + + slist.get(h.gidx1).add(h.s1); + elist.get(h.gidx1).add(h.e1); + alist.get(h.gidx1).add(h.annot1); + slist.get(h.gidx2).add(h.s2); + elist.get(h.gidx2).add(h.e2); + alist.get(h.gidx2).add(h.annot2); + } + for (int gidx : slist.keySet()){ + int[] results = new int[]{0,0}; + clusterIntervals(slist.get(gidx), elist.get(gidx), alist.get(gidx),results); + int nRegions = results[0]; + String pname = grp2proj.get(gidx); + + counterInc(proj2regions,pname,nRegions); + counterInc(pcounts,pname,nRegions); + } + + for (rhit h : hit2grp.get(hidx)) { + hitIdx2Grp.put(h.idx, grpNum); + } + pgfSizes.put(grpNum, hit2grp.get(hidx).size()); + + if (grpNum%100 ==0) + progress.setText(""PgeneF "" + rowNum + "" final groups""); + } // end for loop + + for (String proj : proj2regions.keySet()) { // make string output for summary + String x = String.format(""Regions: %,7d"", proj2regions.get(proj)); + projMap.put(proj, x); + } + } + catch (Exception e) {ErrorReport.print(e, ""Compute PgeneF""); } + } // end computeGroups + + /****************************************************************/ + private boolean parseRowAndBin(DBdata dd) { + try { + if (incOnly) { + if (!allIncChr.contains(dd.getChrIdx(0)) && !allIncChr.contains(dd.getChrIdx(1))){ + return false; // don't put in a group and will be skipped when loading the table. + } + } + + // Transfer data to nhit + rhit nhit = new rhit(); + + nhit.idx = dd.getHitIdx(); + nhit.gidx1 = dd.getChrIdx(0); + nhit.gidx2 = dd.getChrIdx(1); + nhit.pidx1 = dd.getSpIdx(0); + nhit.pidx2 = dd.getSpIdx(1); + int [] coords = dd.getCoords(); + nhit.s1 = coords[0]; + nhit.e1 = coords[1]; + nhit.s2 = coords[2]; + nhit.e2 = coords[3]; + nhit.annot1 = dd.hasGene(0); + nhit.annot2 = dd.hasGene(1); + + /** XXX Good hit - Bin for PgeneF **/ + // Go through the bins this hit is in and see if it overlaps any of the hits in them. + // Also add it to the bins. + TreeSet olaps = new TreeSet(); + + if (!bins.containsKey(nhit.gidx1)) { + bins.put(nhit.gidx1, new HashMap>()); + } + HashMap> bin1 = bins.get(nhit.gidx1); + if (!bins.containsKey(nhit.gidx2)) { + bins.put(nhit.gidx2, new HashMap>()); + } + HashMap> bin2 = bins.get(nhit.gidx2); + + for(int b1 = (int)(nhit.s1/binsize); b1 <= (int)(nhit.e1/binsize); b1++){ + if (!bin1.containsKey(b1)) { + bin1.put(b1, new HashSet()); + } + HashSet bin = bin1.get(b1); + for (rhit rh : bin) { + if ((rh.gidx1==nhit.gidx1 && Utils.intervalsOverlap(nhit.s1,nhit.e1,rh.s1,rh.e1,0)) || + (rh.gidx2==nhit.gidx1 && Utils.intervalsOverlap(nhit.s1,nhit.e1,rh.s2,rh.e2,0)) ) + { + olaps.add(rh); + } + } + bin.add(nhit); + } + for(int b2 = (int)(nhit.s2/binsize); b2 <= (int)(nhit.e2/binsize); b2++){ + if (!bin2.containsKey(b2)) { + bin2.put(b2, new HashSet()); + } + HashSet bin = bin2.get(b2); + for (rhit rh : bin){ + if ( (rh.gidx1==nhit.gidx2 && Utils.intervalsOverlap(nhit.s2,nhit.e2,rh.s1,rh.e1,0)) || + (rh.gidx2==nhit.gidx2 && Utils.intervalsOverlap(nhit.s2,nhit.e2,rh.s2,rh.e2,0)) ) + { + olaps.add(rh); + } + } + bin.add(nhit); + } + + // Combine all the earlier groups connected by the overlaps (or make a new group if no overlaps) + Collection maxGrp = null; + int maxGrpIdx = 0; + HashSet grpList = new HashSet(); + + // First get the non-redundant list of groups, and + // also find the biggest existing group so we can reuse it. + // (Because HashSet adds were costing a lot of time.) + + for (rhit rhit : olaps){ + int grpHitIdx = rhit.grpHitIdx; + if (grpHitIdx == 0) continue; // it's the new hit + if (!grpList.contains(grpHitIdx)){ + grpList.add(grpHitIdx); + if (maxGrp == null){ + maxGrp = hit2grp.get(grpHitIdx); + maxGrpIdx = grpHitIdx; + } + else{ + if (hit2grp.get(grpHitIdx).size() > maxGrp.size()){ + maxGrp = hit2grp.get(grpHitIdx); + maxGrpIdx = grpHitIdx; + } + } + } + } + if (maxGrp != null){ + for (int idx : grpList){ + if (idx != maxGrpIdx ){ + maxGrp.addAll(hit2grp.get(idx)); + for (rhit rh2 : hit2grp.get(idx)) { + rh2.grpHitIdx = maxGrpIdx; + } + hit2grp.remove(idx); + } + } + maxGrp.add(nhit); + nhit.grpHitIdx = maxGrpIdx; + } + else { + hit2grp.put(nhit.idx, new Vector()); + hit2grp.get(nhit.idx).add(nhit); + nhit.grpHitIdx = nhit.idx; + // System.out.println(""QQQ new grp idx:"" + nhit.idx); same as 4.2 + } + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Parse rs hit record""); return false;} + } + + private void clusterIntervals(Vector starts, Vector ends, Vector annots, + int[] results) + { + Vector cstarts = new Vector(); + Vector cends = new Vector(); + Vector cannots = new Vector(); + for (int i = 0; i < starts.size(); i++) { + Vector chits = new Vector(); + boolean cannot = annots.get(i); + int mins = starts.get(i); + int maxe = ends.get(i); + for (int j = 0; j < cstarts.size(); j++){ + if (Utils.intervalsOverlap(starts.get(i), ends.get(i), cstarts.get(j), cends.get(j), 0)){ + chits.add(j); + cannot = (cannot || cannots.get(j)); + mins = Math.min(mins, cstarts.get(j)); + maxe = Math.max(maxe, cends.get(j)); + } + } + if (chits.size() == 0){ + cstarts.add(mins); + cends.add(maxe); + cannots.add(cannot); + } + else { + // grow the first one and remove the rest + cstarts.set(chits.get(0),mins); + cends.set(chits.get(0),maxe); + cannots.set(chits.get(0), cannot); + for (int k = chits.size()-1; k >= 1; k--){ + int kk = chits.get(k); + cstarts.remove(kk); + cends.remove(kk); + cannots.remove(kk); + } + } + } + assert(cstarts.size() == cannots.size()); + results[0] = cstarts.size(); + int nannot = 0; + for (boolean b : cannots){ + if (b) nannot++; + } + results[1] = nannot; + } + private void init() { + incOnly = qPanel.isPGIncOne(); + unAnnotOnly = qPanel.isPGIncNoGene(); + isLinkage = qPanel.isPGincTrans(); + SpeciesPanel spPanel = qPanel.getSpeciesPanel(); + + for (int i = 0; i < spPanel.getNumSpecies(); i++){ + boolean incSp = qPanel.isClInclude(i); + boolean excSp = qPanel.isClExclude(i); + + TreeSet incs = (incSp) ? new TreeSet() : null; + + for (String idxstr : spPanel.getChrIdxList(i)) + { + if(idxstr != null && idxstr.length() > 0) { + int idx = Integer.parseInt(idxstr); + grp2proj.put(idx, qPanel.getSpeciesPanel().getSpName(i)); + if (!incSp && !excSp) continue; + + if (incSp){ + incs.add(idx); + allIncChr.add(idx); + } + if (excSp) { + allExcChr.add(idx); + } + } + } + if (incSp) { + allIncChrBySp.add(incs); + } + } // end going through chromosomes + } + private void counterInc(Map ctr, String key, int inc ){ + if (inc == 0) return; + if (!ctr.containsKey(key)) + ctr.put(key, inc); + else + ctr.put(key, ctr.get(key)+inc); + } + private class rhit implements Comparable{ + int gidx1, gidx2, pidx1, pidx2; + int s1, s2, e1, e2, idx; + int grpHitIdx; // the index of the group this hit is in + boolean annot1 = false, annot2 = false; + + public int compareTo(rhit h){ + if (idx < h.idx) return -1; + else if (idx > h.idx) return 1; + return 0; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/UtilReport.java",".java","56118","1525","package symapQuery; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HashMap; +import java.util.ArrayList; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JTextField; + +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Jhtml; +import util.Popup; +import util.Utilities; + +/*********************************************** + * Create report of gene, collinear genes or multi-hit gene + * Unannotated species cannot be reference (it would work for Genes Report, but it has no annotation so just disable it all) + */ +public class UtilReport extends JDialog { + private static final long serialVersionUID = 1L; + private final int defTxtWidth=40, padWithSpace=10; + private static String filePrefix = ""Report""; + + private static final String splitC = "";"", // local delimiter for lists + keyC = "","", // input key parameter + semiC = "";"", // fixed delimiter for output + keyVal = ""="", // between keyword and value + sDot = ""\\."", // split chr.gene# + keyDot = "".""; // use for hash key + private static final String isRef=""*"", // used in TSV for reference header; HTML uses italics + isAll=""+"", // no all species per row/union, add this to show all species + isCoSet=""#"", // Coset + isMulti=""#""; // Multi + private static final String isLink=""="", // Gene: linkage with direct neighbor + isLink3=""+"", // Gene: linkage with one over + isNone=""---""; + private static final String htmlSp="" "", htmlBr=""
"", tsvBr = ""| "", tsvRmk = ""### ""; + private String brLine; // Between Keyword values and Merge sets: Set in okay: ""|"" tsv,
html + + // Okay: From input menu: the setting are used as the defaults, except bIs settings + // Object is reused - so reset anything not wanted from last time + private boolean bIsGene1=false, bIsCoSet2=false, bIsMulti3=false; // the 4 types of reports + + // Default values the first time; set like this in clear(); 123 corresponds to the above 3 types + private boolean bPopHtml=true, bExHtml=false, bExTsv=false; + private boolean bAllSpRow1=false, // Gene, Multi: all species must be in each row; must be false for species=2 + bLinkRow1=false, // Gene: all species and at least one link + bAllLinkRow1=false, // Gene: complete graph of linked hits + bAllSpIgn1=false, // Gene, Multi: print all, add link if Gene && bShowLink1 + bShowLink1=true, // Gene: show links + bAllUnion2=true, // CoSet: all species must be in the union + bShowNum23=true, // CoSet & Multi: show the collinear/group set number + bShowBorder=true, // All: html table border + bTruncate=false, // All: Truncate description + bShowGene=false; // All: Show gene# before anno + + private int queryMultiN=0; // the cutoff for Multi-hit gene; not all Multi-hit are to genes, report requires N gene pairs + private int descWidth=40; + private boolean hasKey=false; + + private int refPos=-1; // posRef index into Gene.oTag array for reference + private int refSpIdx=0; + + private PrintWriter outFH = null; + private String title; + private String refSpName="""", refSpAbbr=""""; // for trace output and file name + private String note=""""; // put in header (only used by Clust) + + // Anno Keys: + private int nSpecies=0; // createSpecies + private HashMap spIdxPosMap = new HashMap (); // idx, pos + private HashMap spPosIdxMap = new HashMap (); // pos, idx + private String [] spInputKey; // okay + // buildCompute puts genes in map; buildXannoMap() add annotation + private HashMap spAnnoMap = new HashMap (); + + // build and output + private ArrayList unionVec = new ArrayList (); + private ArrayList geneVec = new ArrayList (); + + // CoSet: each gene points to its Union, which contains Collinear sets; see buildXunion: + // CoSet key = rd.chrIdx[i] + ""."" + rd.chrIdx[j] + ""."" + rd.collinearN; + // if bCoSetAll key = rd.spIdx[j] . rd.chrIdx[i] + ""."" + rd.chrIdx[j] + ""."" + rd.collinearN; + // need spIdx to count species in the union + // GroupN: see buildCompute + // tmpRefMap key; a Gene# can be in the table multiple times, hence, the search key is ""tag grpN"" + /***************************************************************************/ + protected UtilReport(TableMainPanel tdp) { // called 1st time for a Table; the report options can change, but not query + this.tPanel = tdp; // rows of the table are read for report + + queryMultiN = tdp.qPanel.getMultiN(); + spPanel = tdp.qPanel.spPanel; + + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + if (tdp.isCollinear) {bIsCoSet2=true; title=""Collinear Genes"";} + else if (tdp.isMultiN) {bIsMulti3=true; title=""Multi-hit Genes""; } + else {bIsGene1 =true; title=""Gene Pair"";} + + title = title + "" Report""; + setTitle(title); + title = ""SyMAP "" + title; + + mainPanel = Jcomp.createPagePanel(); + createSpeciesPanel(); + createDisplayPanel(); + createOutputPanel(); // click OK calls runReport + + pack(); + + setModal(true); // nothing else can happen until ok,cancel + toFront(); + setResizable(false); + setLocationRelativeTo(null); + } + + // Reference and keywords + private void createSpeciesPanel() { + int width = 100; + JPanel optPanel = Jcomp.createPagePanel(); + + nSpecies = tPanel.getNSpecies(); + + radSpecies = new JRadioButton[nSpecies]; + txtSpKey = new JTextField[nSpecies]; + + ButtonGroup bg = new ButtonGroup(); + + JPanel row = Jcomp.createRowPanel(); + JLabel label = Jcomp.createLabel(""Reference""); + row.add(label); + if (Jcomp.isWidth(width, label)) row.add(Box.createHorizontalStrut(Jcomp.getWidth(width, label))); + + row.add(Jcomp.createLabel(""Gene Annotation Columns"", + ""Enter comma-delimited list of keywords from All_Anno column for one or more species."")); + optPanel.add(row); + + // width may change if longer species name; + for(int p=0; p2 species being displayed."" + + ""\n Hover over an option for more details.""; + msg += ""\n\nSee ? for details.\n""; + + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + /**************************************************************8 + * XXX Shared + */ + private void runReportZoutput() { + /*-------- Settings ---------*/ + spInputKey = new String [nSpecies]; // List of input keywords per species + for (int i=0; i rowDataVec = new ArrayList (); + for (int row=0; row tmpRefMap = new HashMap (); // tag to gene + + for (TmpRowData rd : rowDataVec) { // nonRef was added separately + int i = -1; // if >2 species and a middle one selected, may be in 1st or 2nd column + if (rd.spIdx[0]==refSpIdx) i=0; + else if (rd.spIdx[1]==refSpIdx) i=1; + + String refTag = (bIsMulti3) ? (rd.geneTag[i] + "" "" + rd.groupN) : rd.geneTag[i]; // TmpRef key + + Gene gnObj=null; + if (!tmpRefMap.containsKey(refTag)) { + gnObj = new Gene(refPos, rd.geneTag[i], rd.groupN, rd.groupSz); + geneVec.add(gnObj); // gene can be in geneVec multiple times with different groups + tmpRefMap.put(refTag, gnObj); + + if (hasKey && !spInputKey[refPos].isEmpty()) { // All geneVec get put in nAnnoMap + HashMap nAnnoMap = spAnnoMap.get(refPos).nAnnoMap; + nAnnoMap.put(rd.geneTag[i], """"+rd.nRow); // nRow will be replaced with Anno from nRow + } + } + else gnObj = tmpRefMap.get(refTag); + + // Add other half + int j = (i==0) ? 1 : 0; + int posNon = spIdxPosMap.get(rd.spIdx[j]); + gnObj.addNonRef(posNon, rd.geneTag[j], rd.collinearSz, rd.collinearN, rd.groupN); + + if (hasKey && !spInputKey[posNon].isEmpty()) { + HashMap nAnnoMap = spAnnoMap.get(posNon).nAnnoMap; + if (!nAnnoMap.containsKey(rd.geneTag[j])) + nAnnoMap.put(rd.geneTag[j],""""+rd.nRow); + } + } + tmpRefMap.clear(); + if (geneVec.size()==0) return; + + // geneVec: sort by chr, by geneNum, by suffix + Collections.sort(geneVec, new Comparator () { + public int compare(Gene a, Gene b) { + if (a.rGrpN!=b.rGrpN) return a.rGrpN-b.rGrpN; + + if (!a.rChr.equals(b.rChr)) { + int c1=0, c2=0; + try { + c1 = Integer.parseInt(a.rChr); + c2 = Integer.parseInt(b.rChr); + } + catch (Exception e) {c1=c2=0;} + + if (c1==0) return a.rChr.compareTo(b.rChr); + else return c1-c2; + } + if (a.rGeneNum==b.rGeneNum) return a.rSuffix.compareTo(b.rSuffix); + else return a.rGeneNum-b.rGeneNum; + } + }); + + for (Gene gn : geneVec) gn.sortTags(); + + if (bIsCoSet2) buildXcoSet(rowDataVec);// create Unions of coSets; needs original rows with ref + else if (bIsMulti3) buildXmulti(); // Merge rows + else buildXrow(); + + rowDataVec.clear(); + + if (hasKey) buildXannoMap(); // Annotations from 1st loop + } + catch (Exception e) {ErrorReport.print(e, ""Build Gene Vec""); } + } + /********************************************************* + * Rows - set links and filter; + * all filtering is done here to by setting cntHits=0 if it is to be filtered + */ + private void buildXrow() { + try { + /*-- filter 1: all species --*/ + if (!bAllSpIgn1) { + for (Gene refGn: geneVec) { + if (refGn.cntSp != nSpecies) { + refGn.cntHits=0; + continue; + } + } + } + if ((!bShowLink1 && bAllSpIgn1) || nSpecies==2) return; + + /*-- Add links --*/ + // Union per non-ref gene; contains ugeneVec of Refs that it is linked to + HashMap nrTagUnMap = new HashMap (); + for (Gene refGn: geneVec) { + for (int pos=0; pos=4 && pos1-pos0!=1) { + if (refPos==0 || refPos==3) link = isLink3; + else if (pos1-pos0>2) link = isLink3; // jump over refPos + } + + tagList0[i0] = tagList0[i0] + link; + refGn.oTagList[pos0] = """"; + for (String t0 : tagList0) refGn.oTagList[pos0] += t0 + splitC; + + tagList1[i1] = link + tagList1[i1]; + refGn.oTagList[pos1] = """"; + for (String t1 : tagList1) refGn.oTagList[pos1] += t1 + splitC; + cntLinks++; + } // end loop through DBdata rows + nrTagUnMap.clear(); + note = String.format(""%,d Links"", cntLinks); + + /*-- Filter2 - every gene must have a least one link; can check oTagList string w/o splitting --*/ + if (bLinkRow1 || bAllLinkRow1) { + int cnt1to1=0, cntHard=0; + + for (Gene refGn: geneVec) { + if (refGn.cntHits==0) continue; // Filter1 failed + + for (int pos=0; pos0) { + if (refGn.cntHits==nSpecies-1) cnt1to1++; + else cntHard++; + } + } + note = String.format(""%,d single; %,d multi"", cnt1to1, cntHard); + } + if (!bAllLinkRow1) return; + + /* -- Filter 3: Each gene must link to at least one gene in each cell ------- */ + int cnt1to1=0, cntHard=0; + for (Gene refGn: geneVec) { + if (refGn.cntHits==0) continue; // already failed number of species test + + for (int pos=0; pos=4) { + if (pos==2) { + bHas = (tag.startsWith(isLink) && tag.endsWith(isLink)); + } + else { + bHas = tag.contains(isLink3); + } + } + if (!bHas) { + refGn.cntHits=0; + break; + } + } + if (refGn.cntHits==0) break; + } + if (refGn.cntHits>0) { + if (refGn.cntHits==nSpecies-1) cnt1to1++; + else cntHard++; + } + } + note = String.format(""%,d single; %,d multi"", cnt1to1, cntHard); + } + catch (Exception e) {ErrorReport.print(e, ""Build/Filter row""); } + } + /********************************************************* + * For multi-group, merge species + * geneVec does not have merged lists because + * tag = rd.geneTag[i] + "" "" + rd.groupN in order to not merge from same species during build + */ + private void buildXmulti() { + try { + HashMap tagRowMap = new HashMap (); // reference genes + ArrayList newGeneVec = new ArrayList (); + + int ix=0, cntMerged=0; + for (Gene gnObj : geneVec) { + if (gnObj.cntHits0) note = String.format(""%,d merged rows"", cntMerged); + + tagRowMap.clear(); + geneVec.clear(); + geneVec = newGeneVec; + } + catch (Exception e) {ErrorReport.print(e, ""Build Gene Vec for Group""); } + } + + /******************************************** + * Create Unions of CoSets. geneVec is sorted by tag. + */ + private void buildXcoSet(ArrayList tmpRowVec) { // tmpRowVec has only TmpRowData of Ref rows + try { + HashMap refMap = new HashMap (); + for (Gene gn : geneVec) { + gn.tmpCoSetArr = new ArrayList (); + refMap.put(gn.rTag, gn); + } + // Add CoSets to each gene + for (TmpRowData rd : tmpRowVec) { + int i = -1; + if (rd.spIdx[0]==refSpIdx) i=0; + else if (rd.spIdx[1]==refSpIdx) i=1; + String tag = (i!=-1) ? rd.geneTag[i] : null; + if (tag==null) continue; + + int j = (i==0) ? 1 : 0; + String key = rd.chrIdx[i] + keyDot + rd.chrIdx[j] + keyDot + rd.collinearN; // Collinear set key + if (bAllUnion2) key = rd.spIdx[j] + keyDot + key; // need spIdx to count species + + Gene gn = refMap.get(tag); + gn.tmpCoSetArr.add(key); + } + refMap.clear(); + + // create Unions + HashMap unionMap = new HashMap (); + + for (Gene gn : geneVec) { + Union unObj=null; // find if one exists for one of its coSets + + for (String key : gn.tmpCoSetArr) { + Union keyUnObj = (unionMap.containsKey(key)) ? unionMap.get(key) : null; + if (unObj==null && keyUnObj!=null) { + unObj = keyUnObj; + } + else if (unObj!=null && keyUnObj!=null && unObj!=keyUnObj) {// two keys for gene have separate unions + if (Globals.INFO) Globals.prt(""Conflict for "" + gn.rTag + "" "" + key); + Globals.tprt("">> Ref "" + gn.rTag + "" ""+ key + ""\n1. "" + unObj.toString() + ""\n2. "" + keyUnObj.toString()); + } + } + if (unObj==null) { + unObj = new Union(); + unionVec.add(unObj); + } + gn.unionObj = unObj; + + for (String key : gn.tmpCoSetArr) { + unObj.updateOne(key, gn); // counts number of species number in union + if (!unionMap.containsKey(key)) unionMap.put(key, unObj); + } + gn.tmpCoSetArr.clear(); + } + + if (!bAllUnion2) { + unionMap.clear(); + return; // 'Row all' does gn.cntCol in reportHTML + } + + // Count species for each union + HashSet spSet = new HashSet (); + for (Union unObj : unionMap.values()) { + for (String key : unObj.cosetCntMap.keySet()) { + String sp = key.split(sDot)[0]; + if (!spSet.contains(sp)) spSet.add(sp); + } + unObj.unSpCnt = spSet.size(); + spSet.clear(); + } + unionMap.clear(); + } + catch (Exception e) {ErrorReport.print(e, ""Build Gene Vec for Collinear""); } + } + + /****************************************************** + * Intialized in Okay; genes added in buildCompute; add anno here + * Get All_Anno key/values; uses spAnnoMap; puts HTML
between keyword values + */ + private boolean buildXannoMap() { + try { + TmpRowData rd = new TmpRowData(tPanel); // to get anno for current row + String xBreakSp = htmlBr+htmlSp; // indent when wraparound for HTML; none for TSV + + String notFoundKey=""""; + for (int nSp=0; nSp nAnnoMap = spAnnoMap.get(nSp).nAnnoMap; // annoMap for this species + + HashMap keyCntMap = new HashMap (); // lookup; cnt to make sure all are found + String [] set = spInputKey[nSp].split(keyC); + for (int i=0; i=descWidth) v = v.substring(0, descWidth-3)+""...""; + + String wval; + if (v.isEmpty() || v.equals(Q.empty)) wval = Q.dash; + else if (bExTsv) wval = v; + else if (v.length()>=descWidth) wval = Jhtml.wrapLine(v, descWidth, xBreakSp); + else wval = v; + + if (allVal!="""") allVal += brLine; // | or
between Keyword values + allVal += wval; + + keyCntMap.put(key, keyCntMap.get(key)+1); + } + } + if (allVal=="""") allVal = isNone; + nAnnoMap.put(tag, allVal); // replace row number with anno + } + int cutoff = (int) ((double)nAnnoMap.size()*0.01); // a keyword may not show on Column because <50; but not show as missing + Globals.tprt(""Keyword cutoff: "" + cutoff + "" from "" + nAnnoMap.size()); + for (String key : keyCntMap.keySet()) { + if (keyCntMap.get(key) tmpCoSetArr = null; // used for buildXcoSet only, cleared at end + + private Gene(int spPos, String tag, int grpN, int grpSz) { + oTagList = new String [nSpecies]; + for (int i=0; ignJ); + } + else { + int chrI = Utilities.getInt(tokI[0]); + int chrJ = Utilities.getInt(tokJ[0]); + if (chrI>0 && chrJ>0) bSort = chrI>chrJ; + else bSort = (tokI[0].compareTo(tokJ[0])>0); // chrs no int + } + if (bSort) { + swap = true; + String x = ntags[i]; ntags[i] = ntags[j]; ntags[j] = x; + if (bIsCoSet2) { + x = cosets[i]; cosets[i] = cosets[j]; cosets[j] = x; + } + tokI = ntags[i].split(sDot); // tags[i] was just changed + } + } + } + if (swap) { + oTagList[sp] = """"; + for (int i=0; i ugeneVec = new ArrayList (); + private HashMap cosetCntMap = null; + private int unSpCnt=0; // Computed in Xcoset; cnt of species in union + + private Union() { + if (bIsCoSet2 || bAllLinkRow1) cosetCntMap = new HashMap (); + } + private void updateOne(String key, Gene gn) { // CoSet only: count of collinear sets + if (!ugeneVec.contains(gn)) ugeneVec.add(gn); + + if (!cosetCntMap.containsKey(key)) cosetCntMap.put(key, 1); + else cosetCntMap.put(key, cosetCntMap.get(key)+1); + } + private void clear() { + ugeneVec.clear(); + if (cosetCntMap!=null) cosetCntMap.clear(); + } + } + // one per species where nAnnoMap contains gene values of keyword + private class Anno { + private HashMap nAnnoMap = new HashMap (); // gene#, value + } + /*********************************************************************** + * XXX Output: make class and share more between tsv and html + */ + private class Zoutput { + int gnIdx=0, unIdx=0; // Index into geneVec; index into unionVec + int gnNum=0, unNum=0; // Print row/union number + int cntOut=0, nAllNonRefSp=nSpecies-1; + Union lastUn=null, unObj=null; + String lastTag=""""; + + String tsvTab = ""\t""; // everything but row gets tab in front + + StringBuffer hBodyStr= new StringBuffer(); + + private void runReport() { + String report=null; + if (bExTsv) report = reportTSV(); + else report = reportHTML(); + if (report==null) return; + + if (bPopHtml) { + util.Jhtml.showHtmlPanel(null, (title+"" "" + refSpName), report); + } + else { + outFH = getFileHandle(); + if (outFH==null) return; + + outFH.println(report); + outFH.close(); + } + } + + /************************************************** + * build CSV for file; uses geneVec and spAnnoMap; + * Does not have repetitive Ref Tag isAll + */ + private String reportTSV() { + try { + // Column headings + String hColStr= ""Row#""; + for (int x=0; x0) hBodyStr.append(semiC+ "" ""); + if (bShowNum23) + hBodyStr.append(String.format(""%s %s"", gnTok[j], isCoSet + coSetTok[j])); + else hBodyStr.append(String.format(""%s"", gnTok[j])); + } + } + else { + for (int j=0; j0) hBodyStr.append(semiC+ "" ""); + hBodyStr.append(gnTok[j]); + } + } + } + } + if (hasKey) addAnnoCols(gnObj); + hBodyStr.append(""\n""); + } // End loop thru geneVec + + clearDS(); Globals.rclear(); + + if (cntOut==0) { + String opt = strOptions("""", ""\n""); + if (!opt.equals("""")) opt += ""\n""; + String msg = opt + ""No reference genes fit the Display options\n""; + JOptionPane.showMessageDialog(null, msg, ""No results"", JOptionPane.WARNING_MESSAGE); + return null; + } + String head = tsvRmk + title + strOptions(tsvRmk, ""\n""); + return head + ""\n"" + strStats(tsvRmk, ""\n"") + hColStr + ""\n"" + hBodyStr.toString(); + } + catch (Exception e) {ErrorReport.print(e, ""Build HTML""); return null;} + } + + /*********************************************************** + * build HTML for popup and file; uses geneVec and spAnnoMap + */ + private String reportHTML() { + try { + // column headings + String hColStr=""""; + int colSpan=1; + + hColStr += ""
#
""; // for row/union number + for (int x=0; x"" + spPanel.getSpName(x) + """" : spPanel.getSpName(x); + hColStr += ""
"" + name + ""
""; + } + for (int x=0; x"" + spPanel.getSpName(x) + """" : spPanel.getSpName(x); + hColStr += ""
"" + name + "" "" + spInputKey[x].trim() + ""
""; + colSpan++; + } + } + hColStr += ""\n""; + + // Table + while (true) { // loop through geneVec; while loop because the counts are different for Coset and Gene + if (bIsCoSet2 && unIdx>=unionVec.size() && gnIdx>=unObj.ugeneVec.size()) break; + if (gnIdx>=geneVec.size()) break; + + Gene gnObj = isFiltered(); + if (gnObj==null) continue; + + if (bIsCoSet2 && unObj!=lastUn) {// divider between unions + unNum++; + String setsz = String.format(""%d [%d sets]"", unNum, unObj.cosetCntMap.size()); + if (!bAllSpRow1 && !bAllUnion2 && unObj.unSpCnt==nAllNonRefSp) setsz += isAll; + if (!bShowBorder) hBodyStr.append(""
""); + hBodyStr.append("""" + setsz); + lastUn = unObj; + } + + /* Output row of columns for current gnObj */ + if (!bShowBorder) hBodyStr.append(""
""); + hBodyStr.append("""" + gnNum + htmlSp); + + for (int posSp=0; posSp"" + gnObj.oTagList[posSp] + mark + """"); + } + else if (gnObj.oTagList[posSp].equals("""")) { // no gene for this species + hBodyStr.append(""\n "" + htmlSp); + } + else { // one or more genes in non-ref column + hBodyStr.append(""\n ""); + String [] gnTok = gnObj.oTagList[posSp].split(splitC); // list of species genes; chr.genenum + + if (bIsCoSet2) { + String [] coSetTok = gnObj.oCoNList[posSp].split(splitC); // list of collinear Sz.N + for (int j=0; j0) hBodyStr.append(htmlBr); + hBodyStr.append(gnTok[j] + htmlSp); + if (bShowNum23) { + for (int k=gnTok[j].length(); k"" + tag + ""
""; + } + if (j==0) hBodyStr.append(tag); + else hBodyStr.append(htmlBr + tag); + } + } + else { + for (int j=0; jNo reference genes fit the Display options"" + tail; // html for popup + else { + String opt = strOptions("""", ""\n""); + if (!opt.equals("""")) opt += ""\n""; + String msg = opt + ""\nNo reference genes fit the Display options\n""; + JOptionPane.showMessageDialog(null, msg, ""No results"", JOptionPane.WARNING_MESSAGE); + return null; + } + } + return head + hColStr + hBodyStr.toString() + tail; // for file or popup + } + catch (Exception e) {ErrorReport.print(e, ""Build HTML""); return null;} + } + /* created after the body of table created */ + private String htmlHead() { + String htitle = (title + "" for "" + refSpName); // tab title + + // border-collapse: collapse does not work in popup; making border-spacing: 0px makes it too think + String head = ""\n\n"" + + """" + htitle + ""\n"" + ""\n\n\n"" + ""\n""; + + htitle = title + "" #"" + tPanel.theTableData.getNumRows(); // header title like cluster + head += ""
"" + htitle + """" + strOptions("""", htmlBr) + """";//
in tail + + if (cntOut==0) head += ""\n""; + else head += ""

"" + strStats("""", """") + ""

\n""; + return head; + } + + private String htmlTail() { + String tail=""
""; + if ((gnNum>100 || unNum>10) && bExHtml) tail += ""

Go to top\n""; + tail += ""\n""; + + return tail; + } + /********************************************************* + * Filters a row based on options set; Works for both HTML and TSV + */ + private Gene isFiltered() { + try { + Gene gnObj; + + if (bIsGene1 || bIsMulti3) { // gene report + gnObj = geneVec.get(gnIdx++); + + if (gnObj.cntHits==0) return null; // everything filtered already in buildXrow and buildXmult + } + else if (bIsCoSet2) { + if (unObj==null || gnIdx==unObj.ugeneVec.size()) { + if (unObj!=null) unObj.clear(); + unObj = unionVec.get(unIdx++); + gnNum=0; gnIdx=0; + } + gnObj = unObj.ugeneVec.get(gnIdx++); + if (bAllUnion2 && gnObj.unionObj.unSpCnt!=nAllNonRefSp) return null; + } + else { + Globals.tprt(""No Mode""); + gnObj = geneVec.get(gnIdx++); + } + + gnNum++; + if (++cntOut%100 == 0) Globals.rprt(""Processed "" + cntOut + "" genes""); + return gnObj; + } + catch (Exception e) {ErrorReport.print(e, ""Build HTML""); return null;} + } + /*********************************************************** + * Columns of the user input keyword=value + * already has
between a species keyword values, e.g. ID
Desc + */ + private void addAnnoCols(Gene gnObj) { + try { + for (int nSp=0; nSp"" + htmlSp); // nl make file manually editable + else hBodyStr.append("""" + htmlSp); + continue; + } + HashMap nAnnoMap = spAnnoMap.get(nSp).nAnnoMap; + String anno=""""; + String [] taglist = gnObj.oTagList[nSp].split(splitC); // already has keyword values delimited by
or | + + for (String tag : taglist) { + if (bIsMulti3) { + if (tag.startsWith(isMulti)) continue; + if (tag.startsWith(isMulti) || tag.startsWith(htmlBr)) { + anno += brLine; + continue; + } + } + if (bIsGene1 && tag.contains(isLink) || tag.contains(isLink3) ) { + tag = tag.replace(isLink, """"); // remove link for search & display + tag = tag.replace(isLink3, """"); + } + String showtag = """"; + if (bShowGene) { + if (bExTsv) showtag = tag; + else { + String sp=""""; + for (int i=0; i"" + anno); + } // end species loop to write annotation columns for this row + } + catch (Exception e) {ErrorReport.print(e, ""Build Anno Columns"");} + } + /************************************************************** + * First lines: title in HTML and remarks in TSV. Title made in + * Second line: Query filters; Report settings + * Works for both HTML and TSV by using: remark = """", ""###"" and br =
, ""\n"" + */ + private String strOptions(String remark, String br) {// see comment above + String qhead = br + remark + ""Query: "" + tPanel.theSummary; + qhead += br + remark + ""Reference: "" + refSpName; + + if (nSpecies>2) { + String rhead=""Display: ""; + if (bIsGene1) { // order is important + if (bAllLinkRow1) rhead += ""All species linked""; + else if (bLinkRow1) rhead += ""All species +link""; + else if (bAllSpRow1) rhead += ""All species per row""; + else rhead += ""All rows""; + } + else if (bIsCoSet2) { + if (bAllUnion2) rhead += ""All species per union""; + else rhead += ""All rows""; + } + else if (bIsMulti3) { + if (bAllSpRow1) rhead += ""All species per row""; + else rhead = """"; + } + if (!rhead.equals("""")) qhead += ""; "" + rhead; + } + return qhead; + } + + /* + * This goes right before the table to explain it, e.g. Arab: 100 Unique Gene Rows; 10 merged rows + * Works for both HTML and TSV by using: remark = """", ""###"" and br = """", ""\n"" */ + private String strStats(String remark, String br) { + String stats = remark + refSpName + "": ""; + + if (bIsCoSet2) stats += String.format(""%,d Unions of Collinear Sets"", unNum); + else if (bIsMulti3) stats += String.format(""%,d Unique Gene Rows"", gnNum); + else stats += String.format(""%,d Unique Gene Rows"", gnNum); + + if (note.equals("""")) return stats + br; + else return stats + ""; "" + note + br; + } + /* getFileHandle */ + private PrintWriter getFileHandle() { + String saveDir = Globals.getExport(); + + String type; + if (bIsCoSet2) type = ""CoSet_""; + else if (bIsMulti3) type = ""Multi_""; + else type = ""Gene_""; + + String name = filePrefix + type + refSpAbbr; + String fname = (bExHtml) ? name + "".html"" : name + "".tsv""; + + JFileChooser chooser = new JFileChooser(saveDir); + chooser.setSelectedFile(new File(fname)); + if(chooser.showSaveDialog(tPanel.qFrame) != JFileChooser.APPROVE_OPTION) return null; + if(chooser.getSelectedFile() == null) return null; + + String saveFileName = chooser.getSelectedFile().getAbsolutePath(); + if (bExTsv) { + if(!saveFileName.endsWith("".tsv"")) saveFileName += "".tsv""; + } + else { + if(!saveFileName.endsWith("".html"")) saveFileName += "".html""; + } + + if (new File(saveFileName).exists()) { + if (!Popup.showConfirm2(""File exists"",""File '"" + saveFileName + ""' exists.\nOverwrite?"")) return null; + } + PrintWriter out=null; + try { + out = new PrintWriter(new FileOutputStream(saveFileName, false)); + Globals.prt(""Write to "" + saveFileName); + } + catch (Exception e) {ErrorReport.print(e, ""Cannot open file - "" + saveFileName);} + + return out; + } + } + /*********************************************************************/ + // Interface + private TableMainPanel tPanel; + private SpeciesPanel spPanel; + private JPanel mainPanel; + + private JRadioButton [] radSpecies=null; + private JTextField [] txtSpKey=null; + + private JTextField txtDesc = null; + private JCheckBox chkTrunc = null, chkShowGene = null; + + private JRadioButton radAllSpRow, radLinkRow, radAllLinkRow, radAllSpUnion, radAllSpIgn; + private JCheckBox chkShowNum=null, chkShowLinks = null, chkBorder = null; + + private JRadioButton btnPop = null; + private JButton btnOK=null, btnCancel=null, btnClear=null, btnInfo=null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/Q.java",".java","6274","135","package symapQuery; + +import symap.Globals; + +/** + * Constants for Query and display + */ +public class Q { + static final int INC=5000; + static final String NOANNOVAL = ""---""; // A keyword for the species does not have a value + static final String GROUP = ""-"", COSET = "".""; + static final String DOT = Globals.DOT, // dot used between chr.chr.block and chr.chr.CoSz and Chr.gene#; hard-coded everywhere + SDOT = Globals.SDOT; // this is for split + + static final String empty = "".""; // Changed from ""-"" because was confused with negative strand + static final String dash = ""-""; // empty + static final String pseudo = Globals.pseudoChar; // no annot + static final String minor = Globals.minorAnno; + static final int iNoVal = -1; // gene coord defaults + + static final String delim = ""\n""; // uses as delimiter between Species::annoKey, and put annoKey on 2nd column line + static final String delim2 = "":""; // used for other keys + static final String stop = ""Stopped""; // set in TableMainPanel, checked in other files + + static final String rowCol = ""Row""; + static final String blockCol = ""Block""; // loadRow; equals TableData.ColumnComparator (for sorting) + static final String cosetCol = ""Collinear""; // loadRow; equals TableData.ColumnComparator + static final String hitCol = ""Hit#""; // loadRow; used for Align text + static final String grpCol = ""Group""; // loadRow; show synteny; GrpSize.Grp#. + static final String hitPrefix = ""Hit""; // Required prefix; Searches MUST BE for equal, or SpAbbr of ""Hitx"" would mess up + static final String hitSt = ""Hit\nSt""; // Leave \n so can search on full column in TableData + + static final String chrCol = ""Chr""; + static final String gStartCol = ""Gstart""; + static final String gEndCol = ""Gend""; + static final String gLenCol = ""Glen""; + static final String gStrandCol = ""Gst""; // endsWith TableData.ColumnComparator + static final String gNCol = ""Gene#""; // endsWith TableData.ColumnComparator; expects chr#.genenum.[suffix] + static final String hStartCol = ""Hstart""; + static final String hEndCol = ""Hend""; + static final String hLenCol = ""Hlen""; + static final String gHitNumCol = ""NumHits""; + static final String gOlap = ""%Olap""; + + static final String All_Anno = ""All_Anno""; + + // for SQL tables - see below for tables and fields used + static final String PA = ""PA""; // pseudo_annot + static final String PH = ""PH""; // pseudo_hits + static final String PHA = ""PHA""; // pseudo_annot_hits + static final String PBH = ""PBH""; // pseudo_block_hits + static final String B = ""B""; // block + + static final int AIDX = 1; // PA.idx + static final int AGIDX = 2; // PA.grp_idx + static final int ASTART = 3; // PA.start + static final int AEND = 4; // PA.end + static final int ASTRAND = 5; // PA.strand + static final int ANAME = 6; // PA.name (description) + static final int AGENE = 7; // PA.genenum + static final int ANUMHITS = 8; // PA.numhits - For singles + + static final int HITIDX = 9; // PH.idx + static final int HITNUM = 10; // PH.hitnum + static final int PROJ1IDX = 11; // PH.proj1_idx (can get from grpIdx, but this is for sanity checking + static final int PROJ2IDX = 12; // PH.proj2_idx + static final int GRP1IDX = 13; // PH.grp1_idx + static final int GRP2IDX = 14; // PH.grp1_idx + static final int HIT1START = 15; // PH.start1 + static final int HIT2START = 16; // PH.start2 + static final int HIT1END = 17; // PH.end1 + static final int HIT2END = 18; // PH.end2 + static final int PID = 19; // PH.pctid + static final int PSIM = 20; // PH.cvgpct + static final int HCNT = 21; // PH.countpct + static final int HST = 22; // PH.strand + static final int HSCORE = 23; // PH.score, Hit Cov + static final int HTYPE = 24; // PH.htype, EE, EI, etc + static final int COSIZE = 25; // PH.runsize + static final int CONUM = 26; // PH.runnum, + + static final int BNUM = 27; // B.blocknum + static final int BSCORE = 28; // B.blockscore + + static final int AOLAP = 29; // PHA.olap or exlap + + static final int ANNOT1IDX = 30; // PH.annot1_idx + static final int ANNOT2IDX = 31; // PH.annot2_idx + + /************************************************************** + * Relations: + * pseudo_annot + * ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // annot_idx + ""grp_idx INTEGER NOT NULL,"" + // xgroups.idx find species + ""type VARCHAR(20) NOT NULL,"" + // 'gene' check for orphan + ""name TEXT NOT NULL,"" + // description orphan and hit + ""start INTEGER NOT NULL,"" + // chr start orphan + ""end INTEGER NOT NULL,"" + // chr end orphan + + * pseudo_hits + * ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // hit_id + * ""pair_idx INTEGER NOT NULL,"" + // PH.pair_idx in (list) + * ""proj1_idx INTEGER NOT NULL,"" + // proj_props.proj_idx + ""proj2_idx INTEGER NOT NULL,"" + // proj_props.proj_idx + ""grp1_idx INTEGER NOT NULL,"" + // xgroups.idx + ""grp2_idx INTEGER NOT NULL,"" + // xgroups.idx + ""annot1_idx INTEGER default 0,"" + // is gene check + ""annot2_idx INTEGER default 0,"" + + ""start1 INTEGER NOT NULL,"" + + ""end1 INTEGER NOT NULL,"" + + ""start2 INTEGER NOT NULL,"" + + ""end2 INTEGER NOT NULL, "" + + ""runsize INTEGER default 0,"" + + ""pctid TINYINT UNSIGNED NOT NULL,"" + // Col6, Avg %ID + ""countpct INTEGER UNSIGNED default 0,"" + // unused 0 + ""cvgpct TINYINT UNSIGNED NOT NULL,"" + //was unused 0 -> + ""score INTEGER default 0,"" + + + * pseudo_block_hits + * ""hit_idx INTEGER NOT NULL,"" + + ""block_idx INTEGER NOT NULL,"" + + + * blocks + ""idx INTEGER AUTO_INCREMENT PRIMARY KEY,"" + // block_idx + ""blocknum INTEGER NOT NULL,"" + // is block check + ""score INTEGER default 0,"" + + + LEFT JOIN pseudo_block_hits as PBH on PBH.hit_idx=PH.idx + LEFT JOIN blocks as B on B.idx=PBH.block_idx + LEFT JOIN pseudo_hits_annot AS PHA ON PH.idx = PHA.hit_idx + LEFT JOIN pseudo_annot AS PA ON PHA.annot_idx = PA.idx + */ +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/ComputeMulti.java",".java","10063","312","package symapQuery; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.TreeMap; +import java.util.Vector; +import javax.swing.JTextField; + +import util.ErrorReport; + +/************************************ + * Multi filter; Return multi-hits >=n; If *Minor was checked, they are already included + * Filtering on location has already been done, but need to again here because the multi>N must be on a selected + * chromosome (if there is one). + * Input is a vector DBdata objects of two species, each will represent a row when created later. + */ + +public class ComputeMulti { + protected static final double bigOlap = 0.4; + + // Input: + private Vector inData; // initial input data (each will be a row); then reused for intermediate results + private HashSet grpIdxOnly; + private int [] spIdxList; + private HashMap sumProjMap; + private JTextField loadStatus; + + // parameters + private boolean isSameChr=false, isTandem=false; // minor is done on query + private int nHits = 0; + + // working + private int numFam = 1, saveNumFam=1; // save is for filterTandem + private boolean bSuccess = true; + + private Vector spData = new Vector (); // intermediate results + private int spIdxCur=-1, spIdxOpp=-1; // species index for current species and opposite + private int ii=-1, jj=-1; // The index for the current species and the opposite + + private int [][] spSummaryCnts; + + private String mkKey(DBdata dObj) { + if (dObj.annotIdx[ii]==0) return null; + if (dObj.geneTag[ii].endsWith(Q.pseudo)) return null; + + return isSameChr ? (dObj.annotIdx[ii] + "":"" + dObj.chrIdx[jj]) : (dObj.annotIdx[ii] + """"); + } + private boolean skipRow(DBdata dObj) { + if (spIdxCur!=dObj.spIdx[ii] || spIdxOpp!=dObj.spIdx[jj]) return true; + + if (grpIdxOnly.size()!=0 && !grpIdxOnly.contains(dObj.chrIdx[ii])) return true; + + return false; + } + //////////////////////////////////////////////////////////////////// + protected ComputeMulti(Vector dataFromDB, // input data + QueryPanel qPanel, // get parameters + JTextField loadStatus, // write to TableMainPanel in loadStatus bar + HashSet grpIdxOnly, // groups to process + int [] spIdxList, // species to process + HashMap projMap) // output counts for summary + { + this.inData = dataFromDB; + this.grpIdxOnly = grpIdxOnly; + this.spIdxList = spIdxList; + this.sumProjMap = projMap; + this.loadStatus = loadStatus; + + spSummaryCnts = new int [spIdxList.length][spIdxList.length]; + for (int i=0; i compute() { + Vector finalRows = new Vector (); + int rowNum=0; + + for (int sp1=0; sp10) { + int sz = spSummaryCnts[sp][j]-last; + String x = (spIdxList.length==2) ? String.format(""#%d"", sz) : + String.format(""#%d (%d)"", sz, spSummaryCnts[sp][j]); + msg += String.format(""%-11s "", x); + last = spSummaryCnts[sp][j]; + } + } + if (msg.isEmpty()) msg=""#0""; + sumProjMap.put(name, ""Groups: "" + msg); + } + return finalRows; + } + + /******************************************************* + * inRows is from the initial query or filterPiles + * spRows only has hits from sp0 and sp1 + */ + private void filterNhits() { + try { + HashMap geneCnt = new HashMap(); + spData.clear(); + + // build sets of genes and their counts; SameChr is used in the key + for (DBdata dObj : inData) { + if (skipRow(dObj)) continue; + + String key = mkKey(dObj); + if (key!=null) { + if (geneCnt.containsKey(key)) geneCnt.put(key, geneCnt.get(key)+1); + else geneCnt.put(key, 1); + + } + } + + // create rows with only the cnt>N row for this species pair + for (DBdata dObj : inData) { + if (skipRow(dObj)) continue; + + String key = mkKey(dObj); + if (key!=null) { + int num = (geneCnt.containsKey(key)) ? geneCnt.get(key) : 0; + + if (num>=nHits) {// is in a N group + if (dObj.grpN>0) spData.add((DBdata) dObj.copyRow()); // dObj can be in mult groups; already been assigned to one + else spData.add(dObj); + } + } + } + + // add group number and size + saveNumFam = numFam; // for tandem, which needs renumbering from here; + Collections.sort(spData, new SortForGrpByII()); + + HashMap geneGrpMap = new HashMap(); // geneTag, grpN + + for (DBdata dObj : spData) { // valid rows with valid keys and geneCnt entries + String key = mkKey(dObj); + int sz = geneCnt.get(key); + + int fn; + if (geneGrpMap.containsKey(key)) fn = geneGrpMap.get(key); + else { + fn = numFam++; + geneGrpMap.put(key, fn); + } + dObj.setGroup(fn,sz); // dObj.grpN = sz-fn + } + } + catch (Exception e) {ErrorReport.print(e, ""make multi-hit genes""); bSuccess=false;} + } + + /************************************************* + * Run after filterNhits in order to reduce sets to those with tandem + * In: spData sorted by geneTag/group; both genes Out: spData; + */ + private void filterTandem() { + try { + if (spData.size()==0) return; + + Collections.sort(spData, new SortForTandem()); + + Vector tanData = new Vector (); + TreeMap gTagMap = new TreeMap (); + + numFam = saveNumFam; // start where last pair set left off + + int curGrp=spData.get(0).grpN; + + for (DBdata dObj: spData) { + String [] v = dObj.geneTag[jj].split(""\\.""); // opposite + int g = Integer.parseInt(v[1]); // 0 is chr + + if (curGrp==dObj.grpN) { // will not include pseudo because of numbering + gTagMap.put(g, dObj); + continue; + } + + filterTandemEval(curGrp, gTagMap, tanData); + + // start next + gTagMap.clear(); + gTagMap.put(g, dObj); + curGrp = dObj.grpN; + } + filterTandemEval(curGrp, gTagMap, tanData); + + // finish + spData.clear(); + spData = tanData; + saveNumFam = numFam; + } + catch (Exception ee) {ErrorReport.print(ee, ""make multi-hit tandem""); bSuccess = false;} + } + // Groups will be renumbered; a gene group may split into multi-group, e.g. groupSize 10 may have two tandem interrupted by one gene + private void filterTandemEval(int curGrp, TreeMap gTagMap, Vector tanData) { + Vector nData = new Vector (); + int last = -1; + + for (int tag : gTagMap.keySet()) { // figure out if multiple sets of >=N + if (last!=-1 && (Math.abs(tag-last)>1)) { + if (nData.size()>=nHits) { + for (DBdata dObj : nData) { + dObj.setGroup(numFam, nData.size()); + tanData.add(dObj); + } + numFam++; + } + nData.clear(); + } + nData.add(gTagMap.get(tag)); + + last = tag; + } + if (nData.size()>=nHits) { + for (DBdata dObj : nData) { + dObj.setGroup(numFam, nData.size()); + tanData.add(dObj); + } + numFam++; + } + } + + ////////////////////////////////////////// + private class SortByGrpByAnno implements Comparator { // make sure annos sorted within group + public int compare(DBdata a, DBdata b) { + if (a.grpN==b.grpN) { + if (a.annotIdx[0]==b.annotIdx[0]) return a.annotIdx[1]-b.annotIdx[1]; + else return a.annotIdx[0]-b.annotIdx[0]; + } + return a.grpN - b.grpN; + } + } + private class SortForGrpByII implements Comparator { // only sort ii + public int compare(DBdata aa, DBdata bb) { + if (aa.chrIdx[ii]!=bb.chrIdx[ii]) return aa.chrNum[ii].compareTo(bb.chrNum[ii]); + + String [] v1 = aa.geneTag[ii].split(""\\.""); + String [] v2 = bb.geneTag[ii].split(""\\.""); + + int g1 = Integer.parseInt(v1[1]); // 0 is chr + int g2 = Integer.parseInt(v2[1]); + if (g1!=g2) return g1-g2; + + if (v1.length==3 && v2.length==3) return v1[2].compareTo(v2[2]); + + return 0; + } + } + private class SortForTandem implements Comparator { + public int compare(DBdata a, DBdata b) { + + if (a.chrIdx[ii]!= b.chrIdx[ii]) return a.chrIdx[ii]-b.chrIdx[ii]; + + if (a.annotIdx[ii]==b.annotIdx[ii]) return a.annotIdx[jj]-b.annotIdx[jj]; + + return a.annotIdx[ii]-b.annotIdx[ii]; + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/DBdata.java",".java","44957","1198","package symapQuery; + +import java.sql.ResultSet; +import java.util.Vector; +import java.util.TreeSet; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; + +import javax.swing.JTextField; + +import database.DBconn2; +import symap.Globals; +import symap.manager.Mproject; +import util.ErrorReport; +import util.Utilities; + +/************************************************ + * create the Vector rowsFromDB; + * TableDataPanel.buildTable calls the static method loadRowsFromDB, and passes in the result set. + * buildTable then calls makeRow on each DBdata to put in order. + * + * Each hit can appear in multiple records depending how many annotations it has. + * They are ordered by hit_idx so the identical hits will be consecutive. + * The code merges each hit_idx into a single row. + * + * if change column: loadHit, loadHitMerge, makeRow + */ +public class DBdata implements Cloneable { + private static boolean TRC = Globals.TRACE; + + private static Vector rows = null; // Output from rowsLoadFromDB + + private static TableMainPanel tablePanel; + private static QueryPanel qPanel; + private static SpeciesPanel spPanel; + private static JTextField loadStatus; + + // SpStructs + protected static String [] spNameList=null; // species Names; used in ComputeMulti/Clust + private static int [] spIdxList=null; // species spIdx in same order + private static HashMap annoKeys=null; // spIdx, keys in order + private static HashMap grpStart=null; // grpIdx, start + private static HashMap grpEnd=null; // grpIdx, end + private static HashSet geneIdxForOlap = new HashSet (); // for isOlapAnno; see qPanel.isMinorOlap + + private static boolean isSelf=false; + private static int cntMinorFail=0; // self-synteny cannot do minors + private static boolean isSingle=false, isIncMinor = true, isAnno = false; + private static HashSet grpIdxForAnno; + private static String geneNum=null; + private static int geneOlap=0; + + private static boolean bSuccess=true; + + private static int cntDup=0, cntFilter=0; // Globals.TRACE + private static int cntPlus2=0; // check for possible pre-v547 + + /*********************************************************************** + * STATIC loading rows + */ + protected static Vector rowsLoadFromDB( + TableMainPanel tblPanel, // to access bStopped; + ResultSet rs, // Result set, ready to be parsed + Vector projList, // species in order displayed + QueryPanel theQueryPanel, // for species information + String [] annoColumns, // Species\nkeyword array in order displayed + JTextField loadTextField, // write progress + + HashMap geneCntMap, // output variable of spIdx annotidx counts + HashMap sumProjMap) // output Clust and Multi summary output + { + clearStatic(); + rows = new Vector (); + + tablePanel = tblPanel; + qPanel = theQueryPanel; + loadStatus = loadTextField; + spPanel = qPanel.getSpeciesPanel(); + + isSelf = qPanel.isSelf(); + isSingle = qPanel.isSingle(); + isIncMinor = qPanel.isIncludeMinor(); // See loadHit; loadMergeHit + + geneNum = (qPanel.isGeneNum()) ? qPanel.getGeneNum() : null; // MySQL searches on genenum, but this search on suffix + geneOlap = (qPanel.isGeneOlap()) ? qPanel.getGeneOlap() : -1; // Checked in passFilterPair() + + isAnno = qPanel.isAnnoStr(); + grpIdxForAnno = (isAnno) ? spPanel.getGrpIdxSet() : null; // will be null if all are valid + + initSpStructs(projList, annoColumns, qPanel.getGrpCoords()); + + try { + rowsMake(rs); if (!bSuccess) return null; // DBdata will have both halves (unless single, gene, anno) + rowsFilter(); if (!bSuccess) return null; + rowsFinish(sumProjMap); if (!bSuccess) return null; + + sortRows(); + makeSumCnts(geneCntMap); + + if (qPanel.isIncludeMinor() && cntMinorFail>0) { // Gene# or Hit# + String gene = qPanel.getGeneNum(); + String x = (gene!=null) ? gene : ""Hit""; + String msg=String.format(""Gene# %s has %d minor hits\non self-chromosome\nthat could not be shown"", x, cntMinorFail); + util.Popup.showWarning(msg); + } + if (TRC) { + if (cntDup>0) System.out.format(""%6d Dups\n"", cntDup); + if (cntFilter>0) System.out.format(""%6d Filter\n"", cntFilter); + if (cntPlus2>0) System.out.format(""%6d hits with two non-best genes\n"", cntPlus2); + } + return rows; + } + catch (Exception e) {ErrorReport.print(e, ""Reading rows from db"");} + return rows; + } + private static void clearStatic() { // everything is static (rows gets recreated at start) + bSuccess = true; + if (annoKeys!=null) annoKeys.clear(); + if (grpStart!=null) grpStart.clear(); + if (grpEnd!=null) grpEnd.clear(); + if (spNameList!=null) spNameList=null; + if (spIdxList!=null) spIdxList=null; + + geneIdxForOlap.clear(); + geneNum = null; // BUG fix CAS579b was not clearing from last run + geneOlap = 0; + cntMinorFail = 0; + cntPlus2 = 0; + cntDup = 0; cntFilter = 0; // restart TEST_TRACE counts + } + /*********************************************************************** + * 1. Load and Merge 2nd side from ResultSet + *****************************************************************/ + private static void rowsMake(ResultSet rs) { + try { + int cntRowNum=0; + if (isSingle) { + while (rs.next()) { + DBdata dd = new DBdata(); + dd.rsLoadSingle(rs, cntRowNum++); + rows.add(dd); + + if (cntRowNum%Q.INC ==0) { + loadStatus.setText(""Processed "" + cntRowNum + "" rows...""); + if (tablePanel.bStopped) {rs.close(); bSuccess=false; return;} + } + } + rs.close(); + return; + } + // two records for each hit, for each side of pair; block, hitIdx, etc are the same, only anno diff + HashMap hitRowMap = new HashMap (); // for key lookup + + while (rs.next()) { + int hitIdx = rs.getInt(Q.HITIDX); + String key = hitIdx+""""; + if (isIncMinor) { + int a1=rs.getInt(Q.ANNOT1IDX), a2=rs.getInt(Q.ANNOT2IDX), a=rs.getInt(Q.AIDX); + boolean b = (a1!=a && a2!=a); + if (b) key = hitIdx + "":"" + a; // don't let it match with anything else; + } + + if (!hitRowMap.containsKey(key)) { // first occurrences of hit + DBdata dd = new DBdata(); + dd.rsLoadHit(rs, cntRowNum++); + rows.add(dd); + + hitRowMap.put(key, dd); + + if (cntRowNum%Q.INC ==0) { + loadStatus.setText(""Processed "" + cntRowNum + "" rows...""); + if (tablePanel.bStopped) {rs.close(); bSuccess=false; return;} + } + } + else { // merge further occurrences of hit + DBdata dd = hitRowMap.get(key); + dd.rsMergeHit(rs); + } + } + if (isIncMinor) rowsMakeMinor(); // fill in minor rows + + rs.close(); + if (TRC) Globals.prt(""Load rows "" + rows.size()); + } + catch (Exception e) {ErrorReport.print(e, ""Reading rows from db""); bSuccess=false;} + } + /******************************************************** + * Transfer gene information for Minor records: Example: + * Best gene X gene Y both annotated when two records, X & Y + * Other gene Z gene Y only Z annotated because no corresponding record for Y, so get from Best + * The other annotIdx=-1 and geneTag='.' as defaults + * + * PH.idx PH.annot1_idx PH.annot2_idx PA.idx Gennum + * 98 7670, 82902 7670 1358. 1 New Row + * 98 7670, 82902 82902 664. 2 Enter second + * 98 7670, 82902 82904 665. ***2 New row, add second + */ + private static void rowsMakeMinor() { + try { + // Find full rows + HashMap tagMap0 = new HashMap (); + HashMap tagMap1 = new HashMap (); + for (DBdata dObj : rows) { + if (!dObj.geneTag[0].equals(Q.empty) && !dObj.geneTag[1].equals(Q.empty)) { + tagMap0.put(dObj.annotIdx[0], dObj); + tagMap1.put(dObj.annotIdx[1], dObj); + } + } + + // assign + for (DBdata dd : rows) { + DBdata ddCp=null; + int x=0; + if (dd.annotIdx[0]>0 && dd.geneTag[0].equals(Q.empty)) { + if (tagMap0.containsKey(dd.annotIdx[0])) { + ddCp = tagMap0.get(dd.annotIdx[0]); + x=0; + } + } + else if (dd.annotIdx[1]>0 && dd.geneTag[1].equals(Q.empty)) { + if (tagMap1.containsKey(dd.annotIdx[1])) { + ddCp = tagMap1.get(dd.annotIdx[1]); + x=1; + } + } + if (ddCp==null) continue; + + dd.geneTag[x] = ddCp.geneTag[x]; + dd.gstart[x] = ddCp.gstart[x]; + dd.gend[x] = ddCp.gend[x]; + dd.glen[x] = ddCp.glen[x]; + dd.gstrand[x] = ddCp.gstrand[x]; + dd.golap[x] = ddCp.golap[x]; + dd.annotStr[x] = ddCp.annotStr[x]; + + TreeSet cpAnnoSet = (x==0) ? ddCp.geneSet0 : ddCp.geneSet1; + for (int an : cpAnnoSet) dd.geneSet0.add(an); // already checked for pseudo + + if (qPanel.isOlapAnno_ii()) { //-ii minor/overlap; This got removed at some point, CAS579c + if (!geneIdxForOlap.contains(dd.annotIdx[x])) geneIdxForOlap.add(dd.annotIdx[x]); + } + } + } + catch (Exception e) {ErrorReport.print(e, ""Finish all genes"");} + } + + /************************************************************ + * 2. Rows have been merged, but not finished + */ + private static void rowsFilter() { + try { + boolean isFilter = (grpStart.size()>0 || geneNum!=null || geneOlap>0 || isAnno + || qPanel.isOlapAnno_ii()); // isOlapAnno -ii + if (!isFilter) return; + + int cntRowNum=0; + Vector filterRows = new Vector (); + for (DBdata dd : rows) { + boolean pass = (isSingle) ? dd.passFilterSingle() : dd.passFilterPair(); + if (pass) { + filterRows.add(dd); + cntRowNum++; + dd.rowNum = cntRowNum; // renumber + if (cntRowNum%Q.INC ==0) { + loadStatus.setText(""Filtered "" + cntRowNum + "" rows...""); + if (tablePanel.bStopped) {bSuccess=false; return;} + } + } + else cntFilter++; + } + rows.clear(); + rows = filterRows; + } + catch (Exception e) {ErrorReport.print(e, ""filter rows""); bSuccess=false;} + } + /************************************************************** + * 3. Finish rows + */ + private static void rowsFinish(HashMap sumProjMap) { + try { + // Fill in other side from DB for geneNum + if (geneNum!=null) { + DBconn2 dbc = qPanel.getDBC(); + boolean isAlgo2 = qPanel.isAlgo2(); + + for (DBdata dd : rows) { + if (!dd.loadGeneFromDB(dbc, isAlgo2)) {bSuccess=false; return;} + } + } + // Create block string, chromosome strings and make anno keys + int cntRowNum=0; + for (DBdata dd : rows) { + if (!dd.finishRow()) {bSuccess=false; return;} + + cntRowNum++; + if (cntRowNum%1000 ==0) { + loadStatus.setText(""Finished "" + cntRowNum + "" rows...""); + if (tablePanel.bStopped) {bSuccess=false; return;} + } + } + if (tablePanel.bStopped) {bSuccess=false; return;} + + // Special processing + if (geneNum!=null) { + runGeneNum(rows); + } + else if (qPanel.isMultiN()) { // Multi - may remove rows and renumber + loadStatus.setText(""Compute multi-hit genes...""); + rows = runMultiGene(rows, sumProjMap); + } + else if (qPanel.isClustN()) { // Clust - may remove rows and renumber + loadStatus.setText(""Compute Clust and filter...""); + rows = runClustHits(rows, sumProjMap); + } + if (tablePanel.bStopped) {bSuccess=false; return;} + } + catch (Exception e) {ErrorReport.print(e, ""finish rows""); bSuccess=false;} + } + + /*********************************************************************** + * Initial sort and numbering of rows; should be like TableData.compare + * Multi is sorted in ComputeMulti + */ + private static void sortRows() { + try { + if (qPanel.isGroup()) { // highest precedence CAS577 + Collections.sort(rows, new Comparator () { + public int compare(DBdata a, DBdata b) { + String as=a.grpStr, bs=b.grpStr; + if (as.equals(Q.empty) && !bs.equals(Q.empty)) return 1; + if (!as.equals(Q.empty) && bs.equals(Q.empty)) return -1; + if (as.equals(bs)) return a.hitNum-b.hitNum; + + int retval=0; + String [] av = as.split(Q.GROUP); + String [] bv = bs.split(Q.GROUP); + + for(int x=1; x>=0 && retval == 0; x--) { // copied from TableData + boolean valid = true; + Integer leftVal = -1, rightVal = -1; + try { + leftVal = Integer.parseInt(av[x]); + rightVal = Integer.parseInt(bv[x]); + } + catch(Exception e) {valid = false; } // e.g. chr X + + if (valid) retval = rightVal.compareTo(leftVal); + else retval = bv[x].compareTo(av[x]); + } + return -retval; // reverse sort + } + }); + } + else if (qPanel.isCollinear() || qPanel.isBlock()) { // if change here, change in TableData.compare + Collections.sort(rows, new Comparator () { + public int compare(DBdata a, DBdata b) { + String as="""", bs=""""; + if (qPanel.isCollinear()) {as=a.collinearStr; bs=b.collinearStr;} // precedence to collinear; CAS577 + else {as=a.blockStr; bs=b.blockStr;} + + if (as.equals(Q.empty) && !bs.equals(Q.empty)) return 1; + if (!as.equals(Q.empty) && bs.equals(Q.empty)) return -1; + if (as.equals(bs)) return a.hitNum-b.hitNum; + + int retval=0; + String [] av = as.split(Q.SDOT); + String [] bv = bs.split(Q.SDOT); + int n = Math.min(av.length, bv.length); + boolean bCS = qPanel.isCollinear(); + + for(int x=0; x () { + public int compare(DBdata a, DBdata b) { + if (a.chrIdx[0]!=b.chrIdx[0]) return a.chrIdx[0] - b.chrIdx[0]; + if (a.chrIdx[1]!=b.chrIdx[1]) return a.chrIdx[1] - b.chrIdx[1]; + return a.hitNum-b.hitNum; + } + }); + } + // Number results for display + int rnum=1; + for (DBdata r : rows) r.rowNum = rnum++; + } + catch (Exception e) {ErrorReport.print(e, ""Sort rows"");} + } + + /***************************************************** + * 1. spNameList, spIdxList: projList - Create species columns in order of projects + * 2. annoKeys: annoColumns - contains spIdx::keyword entries for all projects. Passed in from TableMainPanel. + * 3. grpStart, grpEnd: grpCoords - Set up coordinates from the interface for filter + */ + private static void initSpStructs(Vector projList, String [] annoColumns, HashMap grpCoords) { + try { + int numSp = projList.size(); + + // 1. Species columns in order of projects + spNameList = new String [numSp]; + spIdxList = new int [numSp]; + for (int p=0; p (); + + // count number of keys per species + HashMap cntSpKeys = new HashMap (); + for (int i=0; i spName2spIdx = spPanel.getSpName2spIdx(); + for (String spName : cntSpKeys.keySet()) { + int spidx = spName2spIdx.get(spName); + + int cnt = cntSpKeys.get(spName); + String [] keys = new String [cnt]; + + for (int i=0, k=0; i (); + grpEnd = new HashMap (); + if (grpCoords.size()==0) return; + + for (int gidx : grpCoords.keySet()) { + String [] coords = grpCoords.get(gidx).split(Q.delim2); + int s=0, e=0; + try { + s = Integer.parseInt(coords[0]); + e = Integer.parseInt(coords[1]); + } + catch (Exception ex) {ErrorReport.print(ex, ""Cannot process coords "" + grpCoords.get(gidx));} + + grpStart.put(gidx, s); + grpEnd.put(gidx, e); + } + } + catch (Exception e) {ErrorReport.print(e, ""Make species lits"");} + } + /************************************************* + * Add other geneTag of query; put results from Gene# in groups; + */ + private static void runGeneNum(Vector rows) { + try { + /* Compute group */ + String [] tok = geneNum.split(Q.SDOT); + int genenum = Utilities.getInt(tok[0]); + if (genenum == -1) return; + + HashMap geneTag = new HashMap (); + String key; + + // Compute sz from: Tag:chrIdx:spIdx counts + for (DBdata dd : rows) { + for (int i=0; i<2; i++) { + tok = dd.geneTag[i].split(Q.SDOT); + if (tok.length<2 || tok[1].equals(Q.dash)) continue; + + int num = Utilities.getInt(tok[1]); // chr.tag.[suffix] + + if (num == genenum) { + int j = (i==0) ? 1 : 0; + key = dd.chrIdx[i] + "":"" + dd.spIdx[i] + "":"" + dd.chrIdx[j] + "":"" + dd.spIdx[j]; + if (geneTag.containsKey(key)) geneTag.put(key, geneTag.get(key)+1); + else geneTag.put(key, 1); + } + } + } + + // Assign groups + HashMap grpMap = new HashMap(); // geneTag, grpN + int numFam=1, sz=0; + for (DBdata dd : rows) { + for (int i=0; i<2; i++) { + tok = dd.geneTag[i].split(Q.SDOT); + if (tok.length<2 || tok[1].equals(""-"")) continue; + + int num = Utilities.getInt(tok[1]); // chr.tag.[suffix] + if (num!=genenum) continue; + + int j = (i==0) ? 1 : 0; + key = dd.chrIdx[i] + "":"" + dd.spIdx[i] + "":"" + dd.chrIdx[j] + "":"" + dd.spIdx[j]; + + if (geneTag.containsKey(key)) { + int fn; + if (grpMap.containsKey(key)) fn = grpMap.get(key); + else { + fn = numFam++; + grpMap.put(key, fn); + } + sz = geneTag.get(key); + dd.setGroup(fn,sz); + break; // if i=0, no need to do i=1; if both have genenum, 1st gets used + } + else symap.Globals.eprt(""SyMAP error: No entry for "" + key); + } + } + } + catch (Exception e) {ErrorReport.print(e, ""make Gene# groups"");} + } + + // ComputeMulti; compute does the rows, Clust and PgFSize + private static Vector runMultiGene(Vector rows, HashMap projMap) { + HashSet selGrp = spPanel.getSelectGrpIdxSet(); + ComputeMulti mobj = new ComputeMulti(rows, qPanel, loadStatus, selGrp, spIdxList, projMap); + return mobj.compute(); + } + + //////////////////////////////////////////////////////////////////////////// + // statsProjMap shows in statistics at end of each projects row + private static Vector runClustHits(Vector rows, HashMap statsProjMap ) { + try { + HashMap hitIdx2Grp = new HashMap(); // hitIdx, Clust + HashMap grpSizes = new HashMap(); // Clust, size + + if (!Globals.bQueryPgeneF) + new ComputeClust(rows, qPanel, loadStatus, hitIdx2Grp, grpSizes); + else { + new ComputePgeneF(rows, qPanel, loadStatus, hitIdx2Grp, grpSizes, statsProjMap); + } + + hitIdx2Grp.put(0, 0); // for the annots that didn't go into a group + grpSizes.put(0, 0); + + // Create new set of rows with groups assigned + int rowNum=1; + Vector rowsForDisplay = new Vector (); + for (DBdata dd : rows) { + if (!hitIdx2Grp.containsKey(dd.hitIdx)) continue; + + dd.rowNum = rowNum; + rowNum++; + + int grp = hitIdx2Grp.get(dd.hitIdx); + int sz = grpSizes.containsKey(grp) ? grpSizes.get(grp) : 0; + dd.setGroup(grp, sz); + + rowsForDisplay.add(dd); + + if (rowNum%Q.INC ==0) + loadStatus.setText(""Load "" + rowNum + "" rows...""); + } + rows.clear(); + return rowsForDisplay; + } + catch (Exception e) {ErrorReport.print(e, ""Making cluster table""); return null;} + } + // Create Unique Gene Counts for Stats (see SummaryPanel) + private static void makeSumCnts(HashMap geneCntMap) { // spIdx, num-unique-genes + try { + if (isSelf) { // 2 species only + HashSet anno1 = new HashSet (); + HashSet anno2 = new HashSet (); + for (DBdata dd : rows) { + for (int x=0; x<2; x++) { + if (dd.annotIdx[x]>0 && !dd.geneTag[x].endsWith(Q.pseudo)) { + HashSet anno = (x==0) ? anno1 : anno2; + if (!anno.contains(dd.annotIdx[x])) anno.add(dd.annotIdx[x]); + } + } + } + int spIdx = spIdxList[0]; + geneCntMap.put(spIdx, anno1.size()); + geneCntMap.put(spIdx+1, anno2.size()); //SummaryPanel expects this + return; + } + + // account for >2 species + HashMap numPerGene = new HashMap (); // AIDX, assigned num + HashMap lastNumPerSp = new HashMap (); // SpIdx, lastNum + + for (int spIdx : spIdxList) lastNumPerSp.put(spIdx, 0); + + for (DBdata dd : rows) { + for (int x=0; x<2; x++) { + TreeSet anno = (x==0) ? dd.geneSet0 : dd.geneSet1; + for (int aidx : anno) { + int num=0; + int spx = dd.spIdx[x]; + if (!numPerGene.containsKey(aidx)) { + num = lastNumPerSp.get(spx); // new number + num++; + lastNumPerSp.put(spx, num); + numPerGene.put(aidx, num); // assign number to gene + } + else { + num = numPerGene.get(aidx); + } + } + } + } + for (int spIdx : lastNumPerSp.keySet()) { + geneCntMap.put(spIdx, lastNumPerSp.get(spIdx)); + } + } + catch (Exception e) {ErrorReport.print(e, ""make gene cnt"");} + } + + /**************************************************************** + * XXX DBdata class - one instance per row + */ + private DBdata() {} + + // called from rsMakeRows + private void rsLoadHit(ResultSet rs, int row) { + try { + rowNum = row; + + // from pseudo_hits; values will be the same for either of the hit ends (order does not matter) + hitIdx = rs.getInt(Q.HITIDX); + hitNum = rs.getInt(Q.HITNUM); + + spIdx[0] = rs.getInt(Q.PROJ1IDX); + chrIdx[0] = rs.getInt(Q.GRP1IDX); + hstart[0] = rs.getInt(Q.HIT1START); + hend[0] = rs.getInt(Q.HIT1END); + hlen[0] = Math.abs(hend[0]-hstart[0])+1; + annotIdx[0] = rs.getInt(Q.ANNOT1IDX); + + spIdx[1] = rs.getInt(Q.PROJ2IDX); + chrIdx[1] = rs.getInt(Q.GRP2IDX); + hstart[1] = rs.getInt(Q.HIT2START); + hend[1] = rs.getInt(Q.HIT2END); + hlen[1] = Math.abs(hend[1]-hstart[1])+1; + annotIdx[1] = rs.getInt(Q.ANNOT2IDX); + + runSize = rs.getInt(Q.COSIZE); + runNum = rs.getInt(Q.CONUM); + blockNum = rs.getInt(Q.BNUM); + blockScore = rs.getInt(Q.BSCORE); + pid = rs.getInt(Q.PID); + psim = rs.getInt(Q.PSIM); + hcnt = rs.getInt(Q.HCNT); + + if (hcnt==0) hcnt=1; // makes more sense to be 1 merge instead of empty + String s = rs.getString(Q.HST); + hst = s; // NOTE: use 's' to show the actual value + hscore = rs.getInt(Q.HSCORE); + htype = rs.getString(Q.HTYPE); + + int annoGrpIdx = rs.getInt(Q.AGIDX); // grpIdx, so unique; same as chrIdx[0|1] + if (annoGrpIdx==0) return; // no anno, no pseudo gene num + + // Get anno for one side; either side could come first + // These are from pseudo_annot + int x = (annoGrpIdx==chrIdx[0]) ? 0 : 1; + int annoIdx = rs.getInt(Q.AIDX); + String tag = Utilities.getGenenumFromDBtag(rs.getString(Q.AGENE));// // Remove '2 (9 1306)' or '2.b (9 1306)' + + if (isSelf && chrIdx[0]==chrIdx[1]) { + if (annoIdx==annotIdx[0]) x = 0; + else if (annoIdx==annotIdx[1]) x = 1; + else { + cntMinorFail++; + return; // Can't do minors on same chr + } + } + if (annoIdx!=annotIdx[0] && annoIdx!=annotIdx[1]) { // All annot_idx,hit_idx loaded; make sure best + if (!isIncMinor) return; // is Minor, but not being shown, okay to fill in first part; comes from pseudo_hits + + annotIdx[x] = annoIdx; // this is a new row; see key + htype = ""--""; + tag = tag + "" "" + Q.minor; // will get best in finishAllMinor + } + + gstart[x] = rs.getInt(Q.ASTART); + gend[x] = rs.getInt(Q.AEND); + glen[x] = Math.abs(gend[x]-gstart[x])+1; + gstrand[x] = rs.getString(Q.ASTRAND); + golap[x] = rs.getInt(Q.AOLAP); // from pseudo_hit_annot + + annotStr[x] = rs.getString(Q.ANAME); + geneTag[x] = tag; + + if (!tag.endsWith(Q.pseudo) && annoIdx>0) { + if (x==0) geneSet0.add(annoIdx); // multiple anno's for same hit + else geneSet1.add(annoIdx); + } + } + catch (Exception e) {ErrorReport.die(e, ""Read hit record"");} + } + /*************************************** + * If there is no anno for one side of the hit, there will be no merged record + * called from rsMakeRows + */ + private void rsMergeHit(ResultSet rs) { + try { + int annoGrpIdx = rs.getInt(Q.AGIDX); // will not be zero because no record if anno not on other side + int annoIdx = rs.getInt(Q.AIDX); // PA.idx + String tag = Utilities.getGenenumFromDBtag(rs.getString(Q.AGENE));// convert here for AllGenes + + int x = (annoGrpIdx==chrIdx[0]) ? 0 : 1; // goes with 1st or 2nd half of hit + if (isSelf && chrIdx[0]==chrIdx[1]) { + if (annoIdx==annotIdx[0]) x = 0; + else if (annoIdx==annotIdx[1]) x = 1; + else { + cntMinorFail++; + return; // Can't do minors on same chr; could search for Gene# or Hit# and get no results when there is a minor + } + } + + if (annoIdx!=annotIdx[0] && annoIdx!=annotIdx[1]) { // PH.annot1_idx and PH.annot2_idx + if (!isIncMinor) return; // is Minor, but not being included; ignore + + annotIdx[x] = annoIdx; // should not happen because of key + tag = tag + Q.minor+Q.minor; // hit overlaps at least two genes on both sides + cntPlus2++; + + int y = (x==0) ? 1 : 0; + String chry = (chrIdx[y]>0) ? spPanel.getChrNumFromChrIdx(chrIdx[y]) : ""?""; + Globals.prt(spPanel.getChrNumFromChrIdx(chrIdx[x]) + ""."" + tag + + "" merge "" + spPanel.getChrNumFromChrIdx(chrIdx[x]) + ""."" + geneTag[x] + chry + ""."" + geneTag[y] ); + } + + gstart[x] = rs.getInt(Q.ASTART); + gend[x] = rs.getInt(Q.AEND); + glen[x] = Math.abs(gend[x]-gstart[x])+1; + gstrand[x] = rs.getString(Q.ASTRAND); + golap[x] = rs.getInt(Q.AOLAP); + geneTag[x] = tag; + + int sz = (x==0) ? geneSet0.size() : geneSet1.size(); + if (sz>0) { + annotStr[x] += "";"" + rs.getString(Q.ANAME); + cntDup++; + } + else annotStr[x] = rs.getString(Q.ANAME); + + if (!tag.endsWith(Q.pseudo) && annoIdx>0) { + if (x==0) geneSet0.add(annoIdx); // multiple anno's for same hit + else geneSet1.add(annoIdx); + } + } + catch (Exception e) {ErrorReport.print(e, ""Merge"");} + } + /***************************************************************/ + private void rsLoadSingle(ResultSet rs, int row) { + try { + this.rowNum = row; + + geneSet0.add(rs.getInt(Q.AIDX)); + annotStr[0] = rs.getString(Q.ANAME); + chrIdx[0] = rs.getInt(Q.AGIDX); + gstart[0] = rs.getInt(Q.ASTART); // Gene start to chromosome + gend[0] = rs.getInt(Q.AEND); + glen[0] = Math.abs(gend[0]-gstart[0])+1; + gstrand[0] = rs.getString(Q.ASTRAND); + geneTag[0] = rs.getString(Q.AGENE); + geneTag[0] = Utilities.getGenenumFromDBtag(geneTag[0]); + + numHits[0] = rs.getInt(Q.ANUMHITS); + } + catch (Exception e) {ErrorReport.print(e, ""Read single"");} + } + /***************************************************** + * Get other side of hit. + * In QueryPanel, search for actual genenum or annotation string; that only returns one half of hit + * but is fast and allows the de-activation of a species + ***********************************************************************/ + private boolean loadGeneFromDB(DBconn2 dbc, boolean isAlgo2) { + try { + int idx=-1; + + if (geneTag[0].endsWith(Q.pseudo) || geneTag[0].equals(Q.empty)) idx = 0; + else if (geneTag[1].endsWith(Q.pseudo)|| geneTag[1].equals(Q.empty)) idx = 1; + else return true; + + if (annotIdx[idx]==0) return true; // one side + + String sql = ""SELECT PHA.exlap, PHA.olap, PA.start, PA.end, PA.strand, PA.tag, PA.name "" + + "" from pseudo_hits_annot AS PHA"" + + "" LEFT JOIN pseudo_annot AS PA ON PHA.annot_idx = PA.idx"" + + "" where PHA.hit_idx = "" + hitIdx + "" and PA.idx="" + annotIdx[idx]; + + ResultSet rs = dbc.executeQuery(sql); + if (rs.next() ) { + golap[idx] = isAlgo2 ? rs.getInt(1) : rs.getInt(2); + gstart[idx] = rs.getInt(3); + gend[idx] = rs.getInt(4); + glen[idx] = gend[idx]-gstart[idx] +1; + gstrand[idx] = rs.getString(5); + geneTag[idx] = Utilities.getGenenumFromDBtag(rs.getString(6)); + annotStr[idx] = rs.getString(7); + } + else Globals.tprt(""Cannot parse gene ""); + + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Merge gene""); return false;} + } + + /********************************************* + * Create block string, chromosome strings and make anno keys + */ + private boolean finishRow() { + try { + int n = (isSingle) ? 1 : 2; + + for (int x=0; x1) ? // remove leading 0's + chrNum[x].substring(1) : chrNum[x]; + + if (!geneTag[x].equals(Q.empty)) geneTag[x] = chr + ""."" + geneTag[x]; + else geneTag[x] = chr + ""."" + Q.pseudo; // indicates hit but no gene; parsed in TmpRowData/UtilReport + + if (blockNum>0) { + blockStr = Utilities.blockStr(chrNum[0], chrNum[1], blockNum); + } + if (runSize>0) { + collinearStr = Utilities.blockStr(chrNum[0], chrNum[1], runSize); + if (runNum>0) collinearStr += Q.COSET + runNum; + } + + /******* Anno Keys ******************/ + if (!annoKeys.containsKey(spIdx[x])) { // spIdx, keys in order + continue; // not annotated + } + String [] keyList = annoKeys.get(spIdx[x]); + int cntKey = keyList.length; + + String [] valList = new String [cntKey]; // if n keys, then n values + for (int i=0; i0) { // put here so work for the rest of filters + for (int gidx : grpStart.keySet()) { + int sf = grpStart.get(gidx); + int ef = grpEnd.get(gidx); + + for (int x=0; x<2; x++) { // using hit coords + if (chrIdx[x]==gidx) { + if (sf > 0 && hstart[x] < sf)return false; + if (ef > 0 && hend[x] > ef) return false; + } + } + } + } + if (geneOlap>0) { // Not checked in MySQL because will only return one-half, which looks the same as pseudo + if (qPanel.isGeneOlapOr()) { // CAS579c was checking that it is a gene, where pseudos should be removed to + if (golap[0] 0 && gstart[0] < sf) return false; // note gene start (not hit as used below) + if (ef > 0 && gend[0] > ef) return false; + return true; + } + } + return true; + + } catch (Exception e) {ErrorReport.print(e, ""Reading rows""); return false;} + } + // check isAnno before calling (when doing anno search as query, returned hits without anno if they overlap) + private boolean passFilterAnno() { + String anno = qPanel.getAnnoTxt().toLowerCase(); + boolean b0=true, b1=true; + if (grpIdxForAnno!=null) { // null means all chromosomes, otherwise, hashSet of valid + b0 = grpIdxForAnno.contains(chrIdx[0]); + b1 = grpIdxForAnno.contains(chrIdx[1]); + } + if (b0 && annotStr[0].toLowerCase().contains(anno)) return true; + if (b1 && annotStr[1].toLowerCase().contains(anno)) return true; + + return false; + } + /********************************************************* + * Called if ComputeClust or runGeneGroups + */ + protected void setGroup(int grpN, int grpSz) { + this.grpStr = grpSz + Q.GROUP + grpN; + this.grpN = grpN; // needed for ComputeMulti + } + + /************************************************* + * XXX TableData.addRowsWithProgress: returns row formated for table. + */ + protected Vector formatRowForTbl() { + try { + Vector row = new Vector(); + + // general + row.add(rowNum); + + if (!isSingle) { + if (blockNum<=0) row.add(Q.empty); else row.add(blockStr); + if (blockScore<=0) row.add(Q.empty); else row.add(blockScore); + if (runSize<0) row.add(Q.empty); else row.add(collinearStr); + row.add(grpStr); + + if (hitNum<=0) row.add(hitIdx); else row.add(hitNum); + if (hscore<=0) row.add(Q.empty); else row.add(hscore); + if (pid<=0) row.add(Q.empty); else row.add(pid); + if (psim<=0) row.add(Q.empty); else row.add(psim); + if (hcnt<=0) row.add(Q.empty); else row.add(hcnt); + if (hst.contentEquals("""")) row.add(Q.empty); else row.add(hst); + if (htype.contentEquals("""")) row.add(Q.empty); else row.add(htype); + } + // chr, start, end, strand, geneTag per pair i + int cntCol = TableColumns.getSpColumnCount(isSingle); + for (int i=0; i=0) { + row.add(geneTag[x]); + if (!isSingle) { + if (golap[x]<0) row.add(Q.empty); else row.add(golap[x]); // zero is okay + } + else row.add(numHits[x]); + + row.add(chrNum[x]); + if (gstart[x]<0) row.add(Q.empty); else row.add(gstart[x]); + if (gend[x]<0) row.add(Q.empty); else row.add(gend[x]); + if (glen[x]<=0) row.add(Q.empty); else row.add(glen[x]); + row.add(gstrand[x]); + + if (!isSingle) { + row.add(hstart[x]); + row.add(hend[x]); + row.add(hlen[x]); + } + } + else { + for (int j=0; j=0) { + if (annoVals.containsKey(x)) { + String [] vals = annoVals.get(x); + for (String v : vals) { + if (v==null || v.equals("""")) v=Q.empty; + row.add(v); + } + } + // otherwise no anno, no space holders + } + else { // there are more than 2 species, so this fills in the anno columns as blank + if (annoKeys.containsKey(spIdxList[i])) { // fill in columns as empty from Keys (not Vals) + String [] vals = annoKeys.get(spIdxList[i]); + if (vals!=null) + for (int v=0; v0; + else return geneSet1.size()>0; + } + + protected boolean hasBlock() {return blockNum>0;} + protected boolean hasCollinear() {return !collinearStr.isEmpty() && !collinearStr.equals(Q.empty);} + protected boolean hasGroup() {return !grpStr.isEmpty() && !grpStr.equals(Q.empty);} // for GrpSz.Grp# + + protected Object copyRow() { // ComputeMulti: clone only copies primitive, might as well just copy + DBdata nObj = new DBdata(); + nObj.hitIdx = hitIdx; nObj.hitNum = hitNum; + nObj.pid = pid; nObj.psim = psim; nObj.hcnt=hcnt; + nObj.hst=hst; nObj.hscore = hscore; nObj.htype = htype; + nObj.blockNum = blockNum; nObj.runNum = runNum; + nObj.blockScore=blockScore; nObj.runSize=runSize; + nObj.blockStr = blockStr; nObj.collinearStr = collinearStr; + nObj.grpStr = grpStr; + + nObj.geneSet0 = new TreeSet (); for (int x : this.geneSet0) nObj.geneSet0.add(x); + nObj.geneSet1 = new TreeSet (); for (int x : this.geneSet0) nObj.geneSet1.add(x); + + nObj.annotStr = new String [2]; nObj.annotStr[0] = annotStr[0]; nObj.annotStr[1] = annotStr[1]; + nObj.gstrand = new String [2]; nObj.gstrand[0] = gstrand[0]; nObj.gstrand[1] = gstrand[1]; + nObj.geneTag = new String [2]; nObj.geneTag[0] = geneTag[0]; nObj.geneTag[1] = geneTag[1]; + nObj.spName = new String [2]; nObj.spName[0] = spName[0]; nObj.spName[1] = spName[1]; + nObj.chrNum = new String [2]; nObj.chrNum[0] = chrNum[0]; nObj.chrNum[1] = chrNum[1]; + + nObj.spIdx = new int [2]; nObj.spIdx[0] = spIdx[0]; nObj.spIdx[1] = spIdx[1]; + nObj.chrIdx = new int [2]; nObj.chrIdx[0] = chrIdx[0]; nObj.chrIdx[1] = chrIdx[1]; + nObj.gstart = new int [2]; nObj.gstart[0] = gstart[0]; nObj.gstart[1] = gstart[1]; + nObj.gend = new int [2]; nObj.gend[0] = gend[0]; nObj.gend[1] = gend[1]; + nObj.glen = new int [2]; nObj.glen[0] = glen[0]; nObj.glen[1] = glen[1]; + + nObj.hstart = new int [2]; nObj.hstart[0] = hstart[0]; nObj.hstart[1] = hstart[1]; + nObj.hend = new int [2]; nObj.hend[0] = hend[0]; nObj.hend[1] = hend[1]; + nObj.hlen = new int [2]; nObj.hlen[0] = hlen[0]; nObj.hlen[1] = hlen[1]; + + nObj.golap = new int [2]; nObj.golap[0] = golap[0]; nObj.golap[1] = golap[1]; + nObj.annotIdx = new int [2];nObj.annotIdx[0] = annotIdx[0]; nObj.annotIdx[1] = annotIdx[1]; + nObj.numHits = new int [2]; nObj.numHits[0] = numHits[0]; nObj.numHits[1] = numHits[1]; + + nObj.annoVals = new HashMap (); + for (int i : annoVals.keySet()) { + String [] v = annoVals.get(i); + String [] x = new String [v.length]; + for (int j=0; j annoVals = new HashMap (); // 0,1, values in order + +// not columns in table, needed for filters + protected int hitIdx = -1; + protected int [] annotIdx = {Q.iNoVal, Q.iNoVal}; // is PA.idx when isMinor + protected int [] spIdx = {Q.iNoVal, Q.iNoVal}; + protected int [] chrIdx = {Q.iNoVal, Q.iNoVal}; + + private TreeSet geneSet0 = new TreeSet (); // not same order as annotStr + private TreeSet geneSet1 = new TreeSet (); // used to count genes and concat annos, i.e. multi annos per hit + + private String [] annotStr = {"""", """"}; // broken down into annoVals columns + protected int grpN = -1; // used in ComputeMulti +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/UtilExport.java",".java","13348","395","package symapQuery; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.Vector; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; + +import database.DBconn2; +import symap.Globals; +import symap.closeup.AlignPool; +import symap.manager.Mproject; +import util.ErrorReport; +import util.Jcomp; +import util.Popup; +import util.Utilities; + +/*************************************************** + * Export file methods for Table, called by TableDataPanel.exportPopup + */ +public class UtilExport extends JDialog { + private static final long serialVersionUID = 1L; + private static String filePrefix = ""tableExport""; + protected final int ex_csv = 0, ex_html = 1, ex_fasta= 2, ex_cancel= 3; // Referenced in TableDataPanel + + private TableMainPanel tPanel; + private String title, projs=""""; + private JRadioButton btnYes; + private int nMode = -1; + + protected UtilExport(TableMainPanel tdp, String title) { + this.tPanel = tdp; + this.title = title; + + Vector projVec = tdp.qFrame.getProjects(); + for (Mproject mp : projVec) projs += mp.getDisplayName() + "" ("" + mp.getdbAbbrev() + ""); ""; + projs = projs.substring(0, projs.length()-2); + + setModal(true); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setTitle(""Export Table Rows""); + + createDialog(); + + pack(); + this.setResizable(false); + setLocationRelativeTo(null); + } + private void createDialog() { + // Files + JRadioButton btnCSV = new JRadioButton(""CSV""); btnCSV.setBackground(Color.white); + btnCSV.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + nMode = ex_csv; + } + }); + JRadioButton btnHTML = new JRadioButton(""HTML"");btnHTML.setBackground(Color.white); // white for linux + btnHTML.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + nMode = ex_html; + } + }); + + JPanel rowPanel = Jcomp.createRowPanel(); + rowPanel.add(Box.createHorizontalStrut(15)); + rowPanel.add(new JLabel(""Include Row column:"")); rowPanel.add(Box.createHorizontalStrut(5)); + + btnYes = new JRadioButton(""Yes""); btnYes.setBackground(Color.white); + JRadioButton btnNo = new JRadioButton(""No"");btnNo.setBackground(Color.white); + ButtonGroup inc = new ButtonGroup(); + inc.add(btnYes); + inc.add(btnNo); + btnNo.setSelected(true); + rowPanel.add(btnYes); rowPanel.add(Box.createHorizontalStrut(5)); + rowPanel.add(btnNo); + + JRadioButton btnFASTA = new JRadioButton(""FASTA"");btnFASTA.setBackground(Color.white); + btnFASTA.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + nMode = ex_fasta; + } + }); + if (tPanel.isSingle) btnFASTA.setEnabled(false); + + ButtonGroup grp = new ButtonGroup(); + grp.add(btnCSV); + grp.add(btnHTML); + grp.add(btnFASTA); + btnCSV.setSelected(true); + nMode = ex_csv; + + JPanel selectPanel = Jcomp.createPagePanel(); + selectPanel.add(new JLabel(""Table rows and columns"")); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(btnCSV); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(btnHTML); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(rowPanel); + + selectPanel.add(new JSeparator()); + selectPanel.add(new JLabel(""Table sequence"")); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(btnFASTA); + + // buttons + JButton btnOK = Jcomp.createButton(""Export"", ""Perform export""); + btnOK.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setVisible(false); + } + }); + JButton btnCancel = Jcomp.createButton(Jcomp.cancel, ""Cancel export""); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + nMode = ex_cancel; + setVisible(false); + } + }); + + JPanel buttonPanel = Jcomp.createRowPanel(); + buttonPanel.add(Box.createHorizontalStrut(20)); + buttonPanel.add(btnOK); buttonPanel.add(Box.createHorizontalStrut(5)); + buttonPanel.add(btnCancel); + + // Finish + JPanel mainPanel = Jcomp.createPagePanel(); + mainPanel.add(selectPanel); mainPanel.add(Box.createVerticalStrut(5)); + mainPanel.add(new JSeparator()); + mainPanel.add(buttonPanel); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + add(mainPanel); + + } + protected int getSelection() { return nMode; } + + /********************************************************* + * Write CSV - + */ + protected void writeCSV() { + try { + boolean reset = false; + int nSelRows = tPanel.theTable.getSelectedRowCount(); + if (nSelRows>0) { + if (!Popup.showConfirm2(""Selected rows"",""Export "" + nSelRows + "" selected rows?"" )) return ; + } + PrintWriter outFH = getFileHandle(ex_csv, filePrefix + "".csv"", true); + if (outFH==null) return; + + if(nSelRows == 0) { + tPanel.theTable.selectAll(); + reset = true; + } + int [] selRows = tPanel.theTable.getSelectedRows(); + + outFH.println(""### "" + title); + outFH.println(""### "" + projs); + outFH.println(""### Filter: "" + tPanel.theSummary); + boolean incRow = btnYes.isSelected(); + tPanel.setPanelEnabled(false); + + // Columns names + for(int x=0; x0) { + if (!Popup.showConfirm2(""Selected rows"",""Export "" + nSelRows + "" selected rows?"" )) return ; + } + + PrintWriter outFH = getFileHandle(ex_html, filePrefix + "".html"", false); + if (outFH==null) return; + + boolean incRow = btnYes.isSelected(); + + tPanel.setPanelEnabled(false); + boolean reset = false; + if(nSelRows == 0) { + tPanel.theTable.selectAll(); + reset = true; + } + int [] selRows = tPanel.theTable.getSelectedRows(); + + // html header + outFH.print(""\n\n"" + + ""SyMAP Query Table Results\n"" + + ""\n\n\n"" + + ""\n""); + + outFH.println(""

"" + title + ""
\n""); + outFH.println(""
"" + projs + ""
\n""); + outFH.println(""
Filter: "" + tPanel.theSummary + ""
\n""); + outFH.print(""

\n""); + + // Columns names + for(int x=0; x""); + outFH.print(""
"" + col + ""
""); + } + + // rows + for(int x=0; x""); + for(int y=0; y"" + reloadCleanString(tPanel.theTable.getValueAt(selRows[x], y))); + } + outFH.flush(); + } + outFH.print(""\n
\n""); + if (selRows.length>100) outFH.print(""

Go to top\n""); + outFH.print(""\n""); + symap.Globals.prt(""Wrote "" + selRows.length + "" rows ""); + outFH.close(); + + if(reset) + tPanel.theTable.getSelectionModel().clearSelection(); + tPanel.setPanelEnabled(true); + } catch(Exception e) {ErrorReport.print(e, ""Write delim file"");} + } + + /****************************************************************** + * Write fasta + */ + protected void writeFASTA() { + try { + int nSelRows = tPanel.theTable.getSelectedRowCount(); + if (nSelRows>0) { + if (!Popup.showConfirm2(""Selected rows"",""Export "" + nSelRows + "" selected rows?"" )) return ; + } + PrintWriter outFH = getFileHandle(ex_fasta, filePrefix + "".fa"", true); + if (outFH==null) return; + + Thread inThread = new Thread(new Runnable() { + public void run() { + try { + TmpRowData rd = new TmpRowData(tPanel); + tPanel.setPanelEnabled(false); + + DBconn2 dbc = tPanel.qPanel.getDBC(); + AlignPool aPool = new AlignPool(dbc); + + boolean reset = false; + if(tPanel.theTable.getSelectedRowCount() == 0) { + tPanel.theTable.selectAll(); + reset = true; + } + long startTime = Utilities.getNanoTime(); + int [] selRows = tPanel.theTable.getSelectedRows(); + int selNum = selRows.length; + if (selNum>500) { + if (!Popup.showContinue(""Export FASTA"", + ""Selected "" + selNum + "" row to export. This is a slow function. \n"" + + ""It may take over a minute to export each 500 rows of sequences."")) + { + if (reset)tPanel.theTable.getSelectionModel().clearSelection(); + tPanel.setPanelEnabled(true); + return; + } + } + int seqNum = 1, pairNum=1; + + outFH.println(""### "" + title); + for(int x=0; xSEQ"" + String.format(""%06d "", seqNum) + + rd.spName[i] + "" Chr "" + rd.chrNum[i] + + "" Start "" + rd.start[i] + "" End "" + rd.end[i]; + outString += "" Pair#"" + pairNum; + outFH.println(outString); + outFH.println(seq); + outFH.flush(); + seqNum++; + } + pairNum++; + Globals.rprt(""Wrote: "" + ((int)((((float)x)/selRows.length) * 100)) + ""%""); + } + outFH.close(); + + Utilities.printElapsedNanoTime(""Wrote "" + (seqNum-1) + "" sequences"", startTime); + + if(reset) + tPanel.theTable.getSelectionModel().clearSelection(); + tPanel.setPanelEnabled(true); + } catch(Exception e) {ErrorReport.print(e, ""Write fasta"");} + }}); + inThread.start(); + } + catch(Exception e) {ErrorReport.print(e, ""Save as fasta"");} + } + //////////////////////////////////////////////////////////////////////// + // these two methods repeated in UtilReport + private PrintWriter getFileHandle(int type, String fname, boolean bAppend) { + String saveDir = Globals.getExport(); + + JFileChooser chooser = new JFileChooser(saveDir); + chooser.setSelectedFile(new File(fname)); + if(chooser.showSaveDialog(tPanel.qFrame) != JFileChooser.APPROVE_OPTION) return null; + if(chooser.getSelectedFile() == null) return null; + + String saveFileName = chooser.getSelectedFile().getAbsolutePath(); + if (type==ex_csv) { + if(!saveFileName.endsWith("".csv"")) saveFileName += "".csv""; + symap.Globals.prt(""Exporting CSV to "" + saveFileName); + } + else if (type==ex_html) { + if(!saveFileName.endsWith("".html"")) saveFileName += "".html""; + symap.Globals.prt(""Exporting HTML to "" + saveFileName); + } + else { + if(!saveFileName.endsWith("".fasta"") && !saveFileName.endsWith("".fa"")) saveFileName += "".fa""; + symap.Globals.prt(""Exporting Fasta to "" + saveFileName); + } + boolean append=true; + if (new File(saveFileName).exists()) { + if (bAppend) { + int rc = Popup.showConfirmFile(saveFileName); + if (rc==0) return null; + if (rc==1) append=false; + } + else { + if (!Popup.showConfirm2(""File exists"",""File '"" + saveFileName + ""' exists.\nOverwrite?"")) return null; + append=false; + } + } + + PrintWriter out=null; + try { + out = new PrintWriter(new FileOutputStream(saveFileName, append)); + } + catch (Exception e) {ErrorReport.print(e, ""Cannot open file - "" + saveFileName);} + return out; + } + private String reloadCleanString(Object obj) { + if(obj != null) { + String val = obj.toString().trim(); + if (val.equals("""")) return ""''""; + + val = val.replaceAll(""[\'\""]"", """"); + val = val.replaceAll(""\\n"", "" ""); + val = val.replaceAll("","", "";""); + return val; + } + else return ""''""; + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/TableMainPanel.java",".java","53514","1378","package symapQuery; + +import java.awt.Color; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.Point; +import java.awt.Rectangle; +import java.io.BufferedReader; +import java.io.FileWriter; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.StringReader; +import java.sql.ResultSet; +import java.util.Iterator; +import java.util.Vector; +import java.util.HashMap; +import java.util.Enumeration; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSeparator; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListCellRenderer; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +import database.DBconn2; +import util.ErrorReport; +import util.Jcomp; +import util.Jhtml; +import util.Popup; +import symap.Globals; + +/************************************************** + * Perform query and display results in table + * QueryFrame calls QueryPanel which call this on ""Run Query"" passing it the query. + * The loadDataFromDatabase runs the Query, and DBdata creates the rows. + */ +public class TableMainPanel extends JPanel { + private static final long serialVersionUID = -3827610586702639105L; + private static final int ANNO_COLUMN_WIDTH = 100, ANNO_PANEL_WIDTH = 900; + private static final int GEN_COLUMN_WIDTH = 100; + protected static final int showREGION=0, showSET=1, showBLOCK=2, showGRP=3; + + static protected TableSort theLastTable = null; // keep using last order of columns for session + private int abbrWidth, abbrSp=7; + + // called by QueryFrame + protected TableMainPanel(QueryFrame parentFrame, String tabName, boolean [] selCols, + String query, String sum, boolean isSingle) { + this.qFrame = parentFrame; + this.theTabName = tabName; + + qPanel = qFrame.getQueryPanel(); + this.isAllNoAnno = qFrame.isAllNoAnno(); + this.isNoPseudo = qFrame.cntUsePseudo==0; + this.isSingle = isSingle; + this.theQuery = query; + this.theSummary = sum; + this.isBlock = qPanel.isBlock() || qPanel.isBlockNum(); + this.isCollinear = qPanel.isCollinear() || qPanel.isCollinearNum(); + this.isMultiN = qPanel.isMultiN(); + this.isClustN = qPanel.isClustN(); + this.isGroup = qPanel.isGroup(); + this.isSelf = qPanel.isSelf(); + + String ab=""""; for (int i=0; i geneCntMap = new HashMap (); + HashMap projMap = new HashMap (); // ComputePgeneF & ComputeMulti + + String [] annoColumns = theAnnoKeys.getColumns(false); // T Abbrev, F display + Vector rowsFromDB = DBdata.rowsLoadFromDB(getInstance(), rs, qFrame.getProjects(), + qFrame.getQueryPanel(), annoColumns, loadStatus, + geneCntMap, projMap); // Inputs for Summary + + bDone=true; // make sure the timing does not let them Stop now (unless too late) + + if (bStopped) {if (rowsFromDB!=null) rowsFromDB.clear(); return;} // may be too late + + theTableData.addRowsWithProgress(rowsFromDB, loadStatus); + + SummaryPanel sp = new SummaryPanel(rowsFromDB, qPanel, projMap, geneCntMap); + statsPanel = sp.getPanel(); + + rowsFromDB.clear(); // NOTE: IF want to use later, then the Stats need to be removed from DBdata + } + if (bStopped) return; + + theTableData.setColumnHeaders(qFrame.getAbbrevNames(), theAnnoKeys.getColumns(true /*abbrev*/), isSingle); + theTableData.finalizeX(); + + String [] columns = getSelColsUnordered(); + TableData tData = TableData.createData(columns, theTableData, this); + theTable = new TableSort(tData); + theTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + theTable.autofitColumns(); + + ColumnHeaderToolTip header = new ColumnHeaderToolTip(theTable.getColumnModel()); + TableColumns theFields = TableColumns.getFields(true, true); // flags do not matter here + header.setToolTips(theFields.getDBFieldDescriptions()); + theTable.setTableHeader(header); + + selListener = new ListSelectionListener() { + public void valueChanged(ListSelectionEvent arg0) { + setRowSelected(); + } + }; + theTable.getSelectionModel().addListSelectionListener(selListener); + + MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer(); + Enumeration en = theTable.getColumnModel().getColumns(); + while (en.hasMoreElements()) { + ((TableColumn)en.nextElement()).setHeaderRenderer(renderer); + } + } + /**********************************************************************/ + private void displayTable(int rowIndex) { + removeAll(); + repaint(); + loadStatus = null; + sPane = new JScrollPane(); + sPane.setViewportView(theTable); + theTable.getTableHeader().setBackground(Color.WHITE); + sPane.setColumnHeaderView(theTable.getTableHeader()); + + sPane.getViewport().setBackground(Color.WHITE); + sPane.getHorizontalScrollBar().setBackground(Color.WHITE); + sPane.getVerticalScrollBar().setBackground(Color.WHITE); + sPane.getHorizontalScrollBar().setForeground(Color.WHITE); + sPane.getVerticalScrollBar().setForeground(Color.WHITE); + + if (statsPanel == null) statsPanel = new JPanel(); + + add(tableButtonPanel); add(Box.createVerticalStrut(10)); + add(tableStatusPanel); + add(sPane); add(Box.createVerticalStrut(10)); + add(statsPanel); add(Box.createVerticalStrut(10)); + add(columnPanel); add(Box.createVerticalStrut(10)); + add(columnButtonPanel); + + if (theTable.getRowCount() > 0) + updateTableStatus(theTabName + "": "" + theTable.getRowCount() + "" rows Filter: "" + theSummary); + else + updateTableStatus(theTabName + "": No results Filter: "" + theSummary); + + if (rowIndex>0) {// retain table position + Rectangle cellRect = theTable.getCellRect(rowIndex, 0, true); + theTable.scrollRectToVisible(cellRect); + } + invalidate(); + validateTable(); + } + + private TableMainPanel getInstance() { return this; } + + private JPanel createTopButtonPanel() { + JPanel buttonPanel = Jcomp.createPagePanel(); + + // Top row + JPanel topRow = Jcomp.createRowPanel(); + topRow.add(Jcomp.createLabel(""Selected: "")); topRow.add(Box.createHorizontalStrut(4)); + + btnShowRow = Jcomp.createButton(""Show"", ""Popup with every value listed""); // view data in row + btnShowRow.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + showRow(); + } + }); + topRow.add(btnShowRow); topRow.add(Box.createHorizontalStrut(3)); + + btnShowMSA = Jcomp.createButton(""MSA... "", ""Align selected sequences using MUSCLE or MAFFT""); // setMsaButton + btnShowMSA.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + showMSA(); + } + }); + topRow.add(btnShowMSA); topRow.add(Box.createHorizontalStrut(8)); + + // View 2D + topRow.add(new JSeparator(JSeparator.VERTICAL)); topRow.add(Box.createHorizontalStrut(2)); // Needs box on Linux + btnShow2D = Jcomp.createButton(""View 2D"", ""View in 2D display""); + btnShow2D.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + showView2D(); + } + }); + lbl2Das = Jcomp.createLabel(""as"", ""Drop-box defines coordinates shown"", false); + + cmb2Dopts = new JComboBox (); cmb2Dopts.setBackground(Color.WHITE); + cmb2Dopts.addItem(""Region""); // showREGION=0 + cmb2Dopts.addItem(""Collinear""); // showSET=1 + cmb2Dopts.addItem(""Block""); // showBLOCK=2 + cmb2Dopts.addItem(""Group-chr""); // showGRP=3 + cmb2Dopts.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { // CAS579c add + boolean b = (cmb2Dopts.getSelectedIndex()==showREGION); + txt2Dregion.setEnabled(b); lbl2Dkb.setEnabled(b); + } + }); + txt2Dregion = Jcomp.createTextField((Globals.MAX_2D_DISPLAY/1000)+"""",""Distance on both sides of selected hit"", 3); + lbl2Dkb = Jcomp.createLabel(""kb"", ""Number * 1000"", false); + + chk2Dhigh = Jcomp.createCheckBox(""High"", ""If checked, highlight hit on 2D"", true); + chk2Dgene = Jcomp.createCheckBox(""Gene#"", ""If checked, show Gene#, else show Annotation"", true); + + topRow.add(btnShow2D); topRow.add(Box.createHorizontalStrut(1)); + topRow.add(lbl2Das); topRow.add(Box.createHorizontalStrut(1)); + topRow.add(cmb2Dopts); topRow.add(Box.createHorizontalStrut(1)); + topRow.add(txt2Dregion);topRow.add(Box.createHorizontalStrut(1)); + topRow.add(lbl2Dkb); topRow.add(Box.createHorizontalStrut(2)); + topRow.add(chk2Dhigh); topRow.add(Box.createHorizontalStrut(1)); + if (!(isAllNoAnno && isNoPseudo)) {topRow.add(chk2Dgene); topRow.add(Box.createHorizontalStrut(3));} + + // set opt based on query + if (isCollinear) cmb2Dopts.setSelectedIndex(showSET); + else if (isGroup && !isSelf) cmb2Dopts.setSelectedIndex(showGRP); // CAS579c does not work for Groups + else if (isBlock) cmb2Dopts.setSelectedIndex(showBLOCK); + else cmb2Dopts.setSelectedIndex(showREGION); + + // false until something is selected; see setRowSelected + btnShowRow.setEnabled(false); btnShowMSA.setEnabled(false); btnShow2D.setEnabled(false); + cmb2Dopts.setEnabled(false); txt2Dregion.setEnabled(false); chk2Dhigh.setEnabled(false); chk2Dgene.setEnabled(false); + + // Help + topRow.add(new JSeparator(JSeparator.VERTICAL)); topRow.add(Box.createHorizontalStrut(15)); + btnHelp = Jhtml.createHelpIconQuery(Jhtml.result); + topRow.add(btnHelp); + + topRow.setAlignmentX(LEFT_ALIGNMENT); + topRow.setMaximumSize(topRow.getPreferredSize()); + + // 2nd row + JPanel botRow = Jcomp.createRowPanel(); + botRow.add(Jcomp.createLabel(""Table (or selected): "")); botRow.add(Box.createHorizontalStrut(2)); + + btnExport = Jcomp.createButton(""Export..."", ""Export selected rows or all rows""); + btnExport.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + showExport(); + } + }); + btnUnSelectAll = Jcomp.createButton(""Unselect All"", ""Unselect all selected rows""); + btnUnSelectAll.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + theTable.getSelectionModel().clearSelection(); + setRowSelected(); + } + }); + + // title repeated in setBtnReport + if (isCollinear) btnReport = Jcomp.createButton(""Collinear Report..."", ""Create a collinear gene report from the rows. Display a popup or write to file.""); + else if (isMultiN) btnReport = Jcomp.createButton(""Multi-hit Report..."", ""Create a multi-hit gene report from the rows. Display a popup or write to file.""); + else if (isClustN) btnReport = Jcomp.createButton(""Cluster Report..."", ""Create a cluster gene report from the rows. Display a popup or write to file.""); + else btnReport = Jcomp.createButton(""Gene Report..."", ""Create a gene pair report from the rows. Display a popup or write to file.""); + btnReport.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + showReport(); + } + }); + if (isSingle) btnReport.setEnabled(false); + + btnSearch = Jcomp.createButton(""Search..."", ""Search for string and go to that row.""); + btnSearch.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + showSearch(); + } + }); + JButton btnInfo = Jcomp.createBorderIconButton(""/images/info.png"", ""Quick Help"" ); + btnInfo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + popupHelp(); + } + }); + botRow.add(btnExport); botRow.add(Box.createHorizontalStrut(5)); + botRow.add(btnUnSelectAll); botRow.add(Box.createHorizontalStrut(70)); + if (!(isAllNoAnno && isNoPseudo)) {botRow.add(btnReport); botRow.add(Box.createHorizontalStrut(8));} + botRow.add(btnSearch); botRow.add(Box.createHorizontalStrut(20)); + botRow.add(Box.createHorizontalGlue()); + botRow.add(btnInfo); + + buttonPanel.add(topRow); + buttonPanel.add(Box.createVerticalStrut(10)); + buttonPanel.add(botRow); + buttonPanel.setMaximumSize(buttonPanel.getPreferredSize()); + + return buttonPanel; + } + private JPanel createColumnsPanel() { + columnPanel = Jcomp.createPagePanel(); + columnPanel.setVisible(false); + + generalColSelectPanel = createGeneralSelectPanel(); + spLocColSelectPanel = createSpLocSelectPanel(); + spAnnoColSelectPanel = createSpAnnoSelectPanel(); + + columnPanel.add(generalColSelectPanel); columnPanel.add(Box.createVerticalStrut(10)); + columnPanel.add(spLocColSelectPanel); columnPanel.add(Box.createVerticalStrut(10)); + columnPanel.add(spAnnoColSelectPanel); + + columnPanel.setBorder(BorderFactory.createTitledBorder(""Columns"")); + columnPanel.setMaximumSize(columnPanel.getPreferredSize()); + + return columnPanel; + } + /*********************************************** + * General columns pertaining to hits and blocks + */ + private JPanel createGeneralSelectPanel() { + JPanel retVal = Jcomp.createPagePanel(); + + String [] genCols = TableColumns.getGeneralColHead(); + boolean [] genColDef = TableColumns.getGeneralColDefaults(); + String [] genDesc = TableColumns.getGeneralColDesc(); + int nCol = TableColumns.getGenColumnCount(isSingle); + int newRow = (nCol>1) ? genCols.length-TableColumns.N_GEN_HIT : 1; + + JPanel row=null; + chkGeneralFields = new JCheckBox[nCol]; + for(int x=0; x 0) row.add(Box.createHorizontalStrut(width)); + row.add(Box.createHorizontalStrut(3)); + } + chkGeneralFields[x] = Jcomp.createCheckBox(genCols[x], genDesc[x], genColDef[x]); + chkGeneralFields[x].addActionListener(colSelectChange); + if (x==0) { + chkGeneralFields[x].setSelected(true); + chkGeneralFields[x].setEnabled(false); // cannot remove because doesn't work to + } + row.add(chkGeneralFields[x]); + } + retVal.add(row); + + retVal.setBorder(BorderFactory.createTitledBorder(""General"")); + retVal.setMaximumSize(retVal.getPreferredSize()); + + return retVal; + } + /************************************************** + * Species: + * Single: Chr Gstart Gend Glen GStrand Gene# + * Pair: Chr Gstart Gend Glen GStrand Gene# Hstart Hend Hlen + */ + private JPanel createSpLocSelectPanel() { + JPanel page = Jcomp.createPagePanel(); + + String [] species = qFrame.getAbbrevNames(); + String [] colHeads = TableColumns.getSpeciesColHead(isSingle); + + String [] colDesc= TableColumns.getSpeciesColDesc(isSingle); + int cntCol = TableColumns.getSpColumnCount(isSingle); // single/pairs do not have the same #columns + + chkSpeciesFields = new JCheckBox[species.length][cntCol]; + boolean [] colDefs = TableColumns.getSpeciesColDefaults(isSingle); + + for(int x=0; x> (); + + int [] spPos = theAnnoKeys.getSpPosList(); + + if (spPos.length==0) { // When no project has annotation; CAS579c + retVal.add(Jcomp.createLabel(""No annotation columns"")); + retVal.setBorder(BorderFactory.createTitledBorder(""Gene Annotation"")); + retVal.setMaximumSize(retVal.getPreferredSize()); + return retVal; + } + + // Check selected + for(int x=0; x annoCol = new Vector (); + + for(int y=0; y> spIter = chkAnnoFields.iterator(); + int pos = 0; + while (spIter.hasNext()) { + JPanel row = Jcomp.createRowPanel(); + + // Species name + String abbrev = theAnnoKeys.getSpeciesAbbrev(spPos[pos]); + JLabel spLabel = Jcomp.createMonoLabel(abbrev, 11); + row.add(spLabel); + row.add(Box.createHorizontalStrut(Jcomp.getWidth(abbrWidth, spLabel) + abbrSp)); + + int curWidth = ANNO_COLUMN_WIDTH; + Iterator annoIter = spIter.next().iterator(); + while (annoIter.hasNext()) { + JCheckBox chkTemp = annoIter.next(); + + if(curWidth + ANNO_COLUMN_WIDTH > ANNO_PANEL_WIDTH) { + colPanel.add(row); + row = Jcomp.createRowPanel(); + + row.add(Box.createHorizontalStrut(ANNO_COLUMN_WIDTH + 10)); + curWidth = ANNO_COLUMN_WIDTH + 10; + } + row.add(chkTemp); + + curWidth += ANNO_COLUMN_WIDTH; + row.add(Box.createHorizontalStrut(5)); + } + colPanel.add(row); + if(spIter.hasNext()) colPanel.add(new JSeparator()); + pos++; + } + retVal.add(colPanel); + + retVal.setBorder(BorderFactory.createTitledBorder(""Gene Annotation"")); + retVal.setMaximumSize(retVal.getPreferredSize()); + return retVal; + } + private JPanel createColumnButtonPanel() { + buttonPanel = Jcomp.createRowPanel(); + + btnShowCols = Jcomp.createButton(""Select Columns"", ""Displays panel of columns to select""); + btnShowCols.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if(columnPanel.isVisible()) { + btnShowCols.setText(""Select Columns""); + columnPanel.setVisible(false); + btnClearCols.setVisible(false); + btnDefaultCols.setVisible(false); + btnGroupCols.setVisible(false); + btnShowStats.setVisible(true); + } + else { + btnShowCols.setText(""Hide Columns""); + columnPanel.setVisible(true); + btnClearCols.setVisible(true); + btnDefaultCols.setVisible(true); + btnGroupCols.setVisible(true); + btnShowStats.setVisible(false); + } + displayTable(-1); + }}); + + btnClearCols = Jcomp.createButton(""Clear"", ""Clear all selections""); + btnClearCols.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + searchPanel=null; + clearColumns(); + }}); + btnClearCols.setVisible(false); + + btnDefaultCols = Jcomp.createButton(""Defaults"", ""Set default columns""); + btnDefaultCols.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + searchPanel=null; + defaultColumns(); + }}); + btnDefaultCols.setVisible(false); + + btnGroupCols = Jcomp.createButton(""Arrange"", ""Arrange similar columns together with gene columns first""); + btnGroupCols.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + searchPanel=null; + groupColumns(); + }}); + btnGroupCols.setVisible(false); + + btnShowStats = Jcomp.createButton(""Hide Stats"", ""Do not show statistics panel""); + btnShowStats.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if(statsPanel.isVisible()) { + statsPanel.setVisible(false); + btnShowStats.setText(""Show Stats""); + } + else { + statsPanel.setVisible(true); + btnShowStats.setText(""Hide Stats""); + } + }}); + + txtStatus = new JTextField(400); + txtStatus.setEditable(false); + txtStatus.setBorder(BorderFactory.createEmptyBorder()); + txtStatus.setBackground(Color.WHITE); + + buttonPanel.add(btnShowCols); buttonPanel.add(Box.createHorizontalStrut(5)); + buttonPanel.add(btnClearCols); buttonPanel.add(Box.createHorizontalStrut(5)); + buttonPanel.add(btnDefaultCols); buttonPanel.add(Box.createHorizontalStrut(5)); + buttonPanel.add(btnGroupCols); buttonPanel.add(Box.createHorizontalStrut(10)); + buttonPanel.add(btnShowStats); buttonPanel.add(Box.createHorizontalStrut(10)); //So the resized button doesn't get clipped + buttonPanel.add(txtStatus); + + buttonPanel.setMaximumSize(buttonPanel.getPreferredSize()); + return buttonPanel; + } + //private void setStatus(String desc) {txtStatus.setText(desc);} + + private JPanel createTableStatusPanel() { + JPanel thePanel = Jcomp.createRowPanel(); + + rowCount = new JTextField(400); + rowCount.setBackground(Color.WHITE); + rowCount.setBorder(BorderFactory.createEmptyBorder()); + rowCount.setEditable(false); + rowCount.setMaximumSize(rowCount.getPreferredSize()); + rowCount.setAlignmentX(LEFT_ALIGNMENT); + + thePanel.add(rowCount); + thePanel.setMaximumSize(thePanel.getPreferredSize()); + + return thePanel; + } + private void createLoadStatus() { + removeAll(); + repaint(); + setBackground(Color.WHITE); + loadStatus = new JTextField(60); // CAS579 was 40 + loadStatus.setBackground(Color.WHITE); + loadStatus.setMaximumSize(loadStatus.getPreferredSize()); + loadStatus.setEditable(false); + loadStatus.setBorder(BorderFactory.createEmptyBorder()); + JButton btnStop = new JButton(""Stop""); + btnStop.setBackground(Color.WHITE); + btnStop.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + buildStop(); + } + }); + add(loadStatus); + add(btnStop); + validateTable(); + } + + private void validateTable() { + validate(); + } + private void updateTableStatus(String status) { + rowCount.setText(status); + } + + /*********************************************************** + * Column + */ + private void clearColumns() { + for (int i=1; i en = theTable.getColumnModel().getColumns(); + while (en.hasMoreElements()) { + ((TableColumn)en.nextElement()).setHeaderRenderer(renderer); + } + if (!isSingle) theLastTable = theTable; // saving the single order is not worth it as the species could change, etc + } + + private String [] getSelColsUnordered() { + Vector retVal = new Vector (); + + for(int x=0; x> spIter = chkAnnoFields.iterator(); + + while (spIter.hasNext()) { + Vector spAnnoCol = spIter.next(); + + if (spAnnoCol.size() <= pos) pos -= spAnnoCol.size(); + else return spAnnoCol.get(pos); + } + return null; + } + + private int getNumAnnoCheckBoxes() { + int total = 0; + Iterator> spIter = chkAnnoFields.iterator(); + + while(spIter.hasNext()) { + total += spIter.next().size(); + } + return total; + } + // This disables buttons while something is running; MsaAlign, Export, Report, + protected void setPanelEnabled(boolean enable) { + theTable.setEnabled(enable); // does not disabled sorting columns + rowCount.setEnabled(enable); + + btnShowCols.setEnabled(enable); + btnShowRow.setEnabled(enable); + btnExport.setEnabled(enable); + btnUnSelectAll.setEnabled(enable); + btnHelp.setEnabled(enable); + + for(int x=0; x= 1) ? true : false; + if (!bMSArun) btnShowMSA.setEnabled(bn); + + if (b1 && !bn) return; + + // can work for 2 or 3 species + boolean b2 = (theTable.getSelectedRowCount() == 2) ? true : false; + if (!b2) return; + if (getSharedRef(true)==null) return; + + btnShow2D.setEnabled(b2); + cmb2Dopts.setEnabled(b2); lbl2Das.setEnabled(b2); + txt2Dregion.setEnabled(b2); lbl2Dkb.setEnabled(b2); + chk2Dhigh.setEnabled(b2); chk2Dgene.setEnabled(b2); + } + + /**************************************** + * Buttons functions and associated methods; + **********************************/ + /************************************************************** + * Show Row in popup + */ + private void showRow() { + try{ + if (theTable.getSelectedRowCount() != 1) return; + + int row = theTable.getSelectedRows()[0]; + TmpRowData rd = new TmpRowData(getInstance()); + String outLine = rd.loadRowAsString(row); + + util.Popup.displayInfoMonoSpace(this, ""Row#"" + (row+1), outLine, false); + } + catch(Exception e) {ErrorReport.print(e, ""Show row"");} + } + /*************************************************************** + * Show MSA - threaded; calls setPanelEnabled(false) before comp and setPanelEnabled(true) after; + */ + private void showMSA() { + if (isSingle) return; + if (theTable.getSelectedRowCount() == 0) return; + + new UtilSelect(this).msaAlign(); + } + public void setMsaButton(boolean b) {// stops 2 from running at once; set F in UtilSelect, set T in MsaMainPanel.buildFinish + if (b) {btnShowMSA.setText(""MSA... ""); bMSArun=false; btnShowMSA.setEnabled(true);} + else {btnShowMSA.setText(""Running""); bMSArun=true; btnShowMSA.setEnabled(false);} + } + /************************************************************** + * Show 2D + */ + private void showView2D() { + try{ + hitNum1 = hitNum2 = 0; + grpIdxVec.clear();// for the get statements + + if (isSingle) return; + + int numRows = theTable.getSelectedRowCount(); + if (numRows==0 || numRows>2) return; + + btnShow2D.setEnabled(false); + + int selIndex = cmb2Dopts.getSelectedIndex(); + int pad = (selIndex==showREGION) ? (int) Double.parseDouble(txt2Dregion.getText()) * 1000 : 500; + + UtilSelect uObj = new UtilSelect(this); + boolean bGene = chk2Dgene.isSelected(); + uObj.synteny2D(numRows, selIndex, pad, bGene, isSelf, grpIdxVec); // hitNum1, hitNum2 get set + + btnShow2D.setEnabled(true); + } + catch(Exception e) {ErrorReport.print(e, ""Create 2D Synteny"");} + } + /* can 2d-3col be used? if so, what columns; */ + protected int [] getSharedRef(boolean bCheck) { // bCheck=T in setRowSelected; bCheck=F in UtilSelect.2D + TmpRowData row0 = new TmpRowData(getInstance()); + if (!row0.loadRow(theTable.getSelectedRows()[0])) return null; + + TmpRowData row1 = new TmpRowData(getInstance()); + if (!row1.loadRow(theTable.getSelectedRows()[1])) return null; + + String r0tag0 = row0.geneTag[0], r0tag1 = row0.geneTag[1]; // Chr.tag or Chr.- + String r1tag0 = row1.geneTag[0], r1tag1 = row1.geneTag[1]; + + if ((r0tag0.endsWith(Q.dash) || r1tag0.endsWith(Q.dash)) && + (r0tag1.endsWith(Q.dash) || r1tag1.endsWith(Q.dash))) return null; + + int r0sp0 = row0.spIdx[0], r0sp1 = row0.spIdx[1]; // tags are not unique, spIdx is + int r1sp0 = row1.spIdx[0], r1sp1 = row1.spIdx[1]; + + int ref=0; + if (r0sp0==r1sp0 && r0tag0.equals(r1tag0)) {ref=1;} + else if (r0sp1==r1sp1 && r0tag1.equals(r1tag1)) {ref=2;} + else if (r0sp0==r1sp1 && r0tag0.equals(r1tag1)) {ref=3;} + else if (r0sp1==r1sp0 && r0tag1.equals(r1tag0)) {ref=4;} + + if (ref==0) return null; + if (bCheck) return new int[1]; // check first + + String tag=""""; + int [] c = {0,0, 0,0}; + if (ref==1) {c[0]=1; c[1]=0; c[2]=0; c[3]=1; tag=r0tag0;} + else if (ref==2) {c[0]=0; c[1]=1; c[2]=1; c[3]=0; tag=r0tag1;} + else if (ref==3) {c[0]=1; c[1]=0; c[2]=1; c[3]=0; tag=r0tag0;} + else if (ref==4) {c[0]=0; c[1]=1; c[2]=0; c[3]=1; tag=r0tag1;} + Globals.tprt(""Share ref "" + tag); + return c; + } + /* For highlighting View2D hit */ + public boolean isHitSelected(int idx, boolean bHit1) { + if (!chk2Dhigh.isSelected()) return false; + + if (grpIdxVec.contains(idx)) return true; // highlight all group; + + if (bHit1 && idx==hitNum1) return true; + if (!bHit1 && idx==hitNum2) return true; + + return false; + } + /*********************************************************************** + ** Export file; + * calls setPanelEnabled(false) before comp and setPanelEnabled(true) after; FASTA is threaded + *********************************************************************/ + private void showExport() { + final UtilExport ex = new UtilExport(this, qFrame.title ); // add title for 1st line of export + ex.setVisible(true); + final int mode = ex.getSelection(); + + if (mode != ex.ex_cancel) { + if (mode==ex.ex_csv) ex.writeCSV(); + else if (mode==ex.ex_html) ex.writeHTML(); + else if (mode==ex.ex_fasta) ex.writeFASTA(); + } + } + + /******************************************************** + * Report popup and files; re-use last allows using last parameters + * calls setBtnReport before/after threaded computation + */ + private void showReport() { + if (isSingle) return; + + if (isClustN) { + if (reportNoRefPanel==null) reportNoRefPanel = new UtilReportNR(getInstance()); + reportNoRefPanel.setVisible(true); + } + else { + if (reportRefPanel==null) reportRefPanel = new UtilReport(getInstance()); // Saves last values + reportRefPanel.setVisible(true); + } + + } + protected void setBtnReport(boolean done) {// Called from UtilReport when computation starts/stops + if (!done) { + Jcomp.setCursorBusy(this, true); + btnReport.setText(""Computing...""); + setPanelEnabled(false); + } + else {// titles repeated in createTopButtons + String title = ""Gene Report...""; + if (isCollinear) title = ""Collinear Report...""; + else if (isMultiN) title = ""Multi-hit Report...""; + else if (isClustN) title = ""Cluster Report...""; + btnReport.setText(title); + setPanelEnabled(true); + Jcomp.setCursorBusy(this, false); + } + } + + /********************************************************** + * Search visible columns for a string + */ + private void showSearch() { + btnSearch.setEnabled(false); + + String [] cols = getSelColsUnordered(); + if (searchPanel==null) searchPanel = new UtilSearch(this, cols, theAnnoKeys); // set null if any column changes + searchPanel.setVisible(true); + + btnSearch.setEnabled(true); + } + protected void showSearch(int rowIndex) { // Search stays open and set next row here; CAS579b + if (rowIndex>=0 && rowIndex0) n = n.substring(0, i); + } else n=""--""; + + w.write(cnt + ""\t"" + rs.getString(Q.ASTART) + ""\t"" + rs.getString(Q.AIDX) + ""\t"" + n + + ""\t"" + rs.getInt(Q.ANUMHITS) + ""\n""); + cnt++; + } + w.close(); + System.out.println(""MySQL Results to zTest_orphan_results.log "" + cnt); + } catch(Exception e){ErrorReport.print(e, ""results to file""); }; + } + else { + try { + BufferedWriter w = new BufferedWriter(new FileWriter(""zTest_results.log"")); + w.write(theSummary + ""\n""); + String x1 = String.format(""%4s %5s (%5s) %2s,%2s %2s,%2s %2s %6s,%6s %6s %8s\n"", + ""Row"",""Hnum"", ""Hidx"", ""p1"", ""p2"", ""g1"", ""g2"", ""ga"", ""Hanno1"", ""Hanno2"", ""Anno"", ""Gene""); + w.write(x1); + int cnt=0; + while (rs.next()) { + String tag = rs.getString(Q.AGENE); + if (tag==null) tag = ""none""; + else if (tag.contains(""("")) tag = tag.substring(0, tag.indexOf(""("")); + + String block = rs.getString(Q.BNUM); + if (block==null) block=""0""; + + int a1=rs.getInt(Q.ANNOT1IDX), a2=rs.getInt(Q.ANNOT2IDX), a=rs.getInt(Q.AIDX); + String star = (a1!=a && a2!=a) ? ""* "" : "" ""; + + int grp1 = rs.getInt(Q.GRP1IDX), grp2 = rs.getInt(Q.GRP2IDX), grp = rs.getInt(Q.AGIDX); + int side = (grp1==grp) ? 1 : 2; + + String x = String.format(""%4d %5d (%5d) %2d,%2d %2d,%2d %2d %6d,%6d %6d %8s %s%d"", + cnt, rs.getInt(Q.HITNUM), rs.getInt(Q.HITIDX), rs.getInt(Q.PROJ1IDX), rs.getInt(Q.PROJ2IDX), + grp1, grp2, grp, a1, a2, a, tag, star, side); + String y = String.format("" %,10d %,10d"", rs.getInt(Q.HIT1START), rs.getInt(Q.HIT1END)) + + String.format("" %,10d %,10d"", rs.getInt(Q.HIT2START), rs.getInt(Q.HIT2END)); + w.write(x + y + ""\n""); + cnt++; + } + w.close(); + + System.out.println(""MySQL Results to zTest_results.log "" + cnt); + } catch(Exception e){ErrorReport.print(e, ""results to file""); }; + } + } + + /**************************************************************** + * Public + */ + protected void sortMasterColumn(String columnName) { + int index = theTableData.getColHeadIdx(columnName); + theTableData.sortByColumn(index, !theTableData.isAscending(index)); + } + + protected String getTabName(){return theTabName; } + protected int getNSpecies() {return qPanel.nSpecies;} + protected boolean isSingle() {return isSingle;} + protected boolean [] getColumnSelections() { + try { + if (chkSpeciesFields==null) return null; // linux query crash caused this to crash too + + int genColCnt = TableColumns.getGenColumnCount(isSingle); + int spColCnt = TableColumns.getSpColumnCount(isSingle); + int numCols = genColCnt + (chkSpeciesFields.length * spColCnt); + for(int x=0; x column && column >= 0) + return toolTips[column]; + else + return super.getToolTipText(); + } + } + + private class MultiLineHeaderRenderer extends JList implements TableCellRenderer { + private static final long serialVersionUID = 3118619652018757230L; + + public MultiLineHeaderRenderer() { + setOpaque(true); + setBorder(BorderFactory.createLineBorder(Color.BLACK)); + setBackground(Color.WHITE); + ListCellRenderer renderer = getCellRenderer(); + ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER); + setCellRenderer(renderer); + } + // called repeatedly; when column is moved, changed, etc; once for each column + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + + setFont(table.getFont()); + String str = (value == null) ? """" : value.toString(); + BufferedReader br = new BufferedReader(new StringReader(str)); + + String line; + Vector v = new Vector(); + try { + while ((line = br.readLine()) != null) { + v.addElement(line); + } + } catch (IOException ex) {ErrorReport.print(ex, ""Render table"");} + setListData(v); + return this; + } + } + private void popupHelp() { + String msg = ""Suffix * is minor gene. \n"" + + "" i.e. a hit overlaps it, but the hit is assigned to another gene.\n\n""; + + msg += ""Suffix ~ is un-annotated pseudo gene.\n"" + + "" Numbered Pseudo: Is preceeded by a number.\n"" + + "" It can be searched for in Search..., and used in Report...\n"" + + "" Columns:\n"" + + "" Not numbered: %Olap, Gstart, Gend, Glen and Gst are blank.\n"" + + "" Numbered: Gstart=Hstart, Gend=Hend, Glen=Hlen.\n\n""; + + msg += ""In the Select Columns panel, hover the mouse over a column name for a description.\n"" + + "" Columns can be moved be dragging the header, and sorted by clicking the header.\n\n""; + + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + /************************************************************** + * Private variable + */ + protected QueryFrame qFrame = null; + protected QueryPanel qPanel = null; + + private UtilReport reportRefPanel = null; + private UtilReportNR reportNoRefPanel = null; + private UtilSearch searchPanel = null; + + protected TableSort theTable = null; + protected TableData theTableData = null; + private JScrollPane sPane = null; + private JTextField rowCount = null; + private JTextField loadStatus = null; + + private JLabel lbl2Das=null, lbl2Dkb=null; + private JTextField txt2Dregion = null; + private JCheckBox chk2Dhigh = null, chk2Dgene = null; + private JButton btnShow2D = null, btnShowMSA = null, btnShowRow = null; + private JButton btnUnSelectAll = null, btnExport = null, btnReport = null, btnSearch = null; + private JComboBox cmb2Dopts = null; + + private ListSelectionListener selListener = null; + private Thread buildThread = null; + + private JCheckBox [] chkGeneralFields = null; + private JCheckBox [][] chkSpeciesFields = null; + private Vector> chkAnnoFields = null; + + private ActionListener colSelectChange = null; + private boolean [] theOldSelCols = null; + + private JPanel tableButtonPanel = null, tableStatusPanel = null; + private JPanel generalColSelectPanel = null, spLocColSelectPanel = null; + private JPanel spAnnoColSelectPanel = null, statsPanel = null; + private JPanel buttonPanel = null; + + private JPanel columnPanel = null, columnButtonPanel = null; + private JButton btnShowCols = null, btnClearCols=null, btnDefaultCols=null, btnGroupCols=null; + private JButton btnShowStats = null, btnHelp = null; + private JTextField txtStatus = null; + + private AnnoData theAnnoKeys = null; + + protected String theSummary = """"; + private String theTabName = """", theQuery = """"; + protected boolean isSingle = false; // Cannot use theQueryPanel.isOrphan because only good for last query + + private static int nTableID = 0; + + protected int hitNum1=0, hitNum2=0; // Highlight 2D; set in UtilSelect; + private Vector grpIdxVec = new Vector (); // to highlight groups + protected boolean isCollinear=false, isMultiN=false, isClustN=false; // for UtilReport; the QueryPanel can change, so need to save this + protected boolean isBlock=false, isGroup=false; // set 2d pull-down based on query; CAS577 + protected boolean isSelf=false, isAllNoAnno=true, isNoPseudo=false; + + // for Stop + private boolean bMSArun=false; // MSA can be running, and the rest of the buttons enabled. + protected boolean bStopped=false; // used locally and DBdata; others search loadStatus.equals(Q.stop) + protected boolean bDone=false; // Will not Stop if bDone +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/UtilSelect.java",".java","26749","695","package symapQuery; + +import java.util.Vector; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JTextField; + +import database.DBconn2; +import symap.Globals; +import symap.Ext; +import symap.closeup.AlignPool; +import symap.closeup.SeqData; +import symap.drawingpanel.SyMAP2d; +import symap.mapper.HfilterData; +import symap.sequence.Sequence; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.sql.ResultSet; +import java.util.HashMap; + +import util.ErrorReport; +import util.Jcomp; +import util.Popup; +import util.Utilities; + +/********************************************************** + * Selected row(s): Contains the MSA align and 2D display + */ +public class UtilSelect { + private TableMainPanel tPanel; + + protected UtilSelect(TableMainPanel tdp) { + this.tPanel = tdp; + } + protected void msaAlign() { + new MsaAlign(); + } + protected void synteny2D(int numRows, int selIndex, int pad, boolean isChkNum, boolean isSelf, Vector grpIdxVec) { + new Synteny2D(numRows, selIndex, pad, isChkNum, isSelf, grpIdxVec); + } + /*******************************************************************************************/ + protected class Synteny2D { + private int selIndex; // REGION, SET, BLOCK, GROUP + private int pad; // how much to pad from the selected hit + private boolean isChkGene; // display geneNum, else annotation + private Vector grpIdxVec; // the group hits to highlight; returns the values + private boolean isSelf=false; + + protected int [] hitNums = {-1, -1}; + + private Synteny2D(int numRows, int selIndex, int pad, boolean isChkNum, boolean isSelf, Vector grpIdxVec) { + this.selIndex = selIndex; + this.pad = pad; + this.isChkGene = isChkNum; + this.grpIdxVec = grpIdxVec; + this.isSelf = isSelf; + + if (numRows==2 && isSelf) { + Popup.showWarning(""Only one row can be selected for self-synteny."");// CAS579c add + return; + } + + if (numRows==2) showSyntenyfor3(); + else showSynteny(); + } + /***************************************/ + private void showSynteny() { + try{ + TmpRowData rd = new TmpRowData(tPanel); + if (!rd.loadRow(tPanel.theTable.getSelectedRows()[0])) return; + + int track1Start=0, track2Start=0, track2End=0, track1End=0; + int [] coords; + HfilterData hd = new HfilterData (); + + if (selIndex==TableMainPanel.showSET) { + if (rd.collinearN==0) { + Popup.showWarning(""The selected row does not belong to a collinear set.""); + return; + } + coords = loadCollinearCoords(rd.collinearN, rd.chrIdx[0], rd.chrIdx[1]); + if (coords==null) return; + + hd.setForQuery(0, true, false); // block, set, region; + } + else if (selIndex==TableMainPanel.showBLOCK) { + if (rd.blockN==0) { + Popup.showWarning(""The selected row does not belong to a synteny block.""); + return; + } + coords = loadBlockCoords(rd.blockN, rd.chrIdx[0], rd.chrIdx[1]); + hd.setForQuery(rd.blockN, false, false); // block, set, region; + } + else if (selIndex==TableMainPanel.showGRP) { + if (rd.groupN==0) { + Popup.showWarning(""The selected row does not belong to a group.""); + return; + } + if (isSelf) {// CAS579c add + Popup.showWarning(""Group-chr does not work for self-synteny; change to Region.""); + return; + } + coords = rd.loadGroup(grpIdxVec); // assigns hits to grpIdxVec + hd.setForQuery(0, false, false); // block, set, region; CAS578 make block=F + } + else { + coords = new int [4]; + coords[0] = rd.start[0]; coords[1] = rd.end[0]; + coords[2] = rd.start[1]; coords[3] = rd.end[1]; + hd.setForQuery(0, false, true); // block, set, region + + if (isSelf && rd.chrIdx[0]==rd.chrIdx[1]) { // hit-wires do not show if this is not done + coords[0] = rd.start[1]; coords[1] = rd.end[1]; + coords[2] = rd.start[0]; coords[3] = rd.end[0]; + } + } + track1Start = coords[0] - pad; if (track1Start<0) track1Start=0; + track1End = coords[1] + pad; + track2Start = coords[2] - pad; if (track2Start<0) track2Start=0; + track2End = coords[3] + pad; + + tPanel.hitNum1 = rd.hitnum; + + int p1Idx = rd.spIdx[0]; + int p2Idx = rd.spIdx[1]; + + int grp1Idx = rd.chrIdx[0]; + int grp2Idx = rd.chrIdx[1]; + + // create new drawing panel; + SyMAP2d symap = new SyMAP2d(tPanel.qFrame.getDBC(), tPanel); + symap.getDrawingPanel().setTracks(2); + symap.getDrawingPanel().setHitFilter(1,hd); + + Sequence s1 = symap.getDrawingPanel().setSequenceTrack(1, p2Idx, grp2Idx, Color.CYAN); + Sequence s2 = symap.getDrawingPanel().setSequenceTrack(2, p1Idx, grp1Idx, Color.GREEN); + if (isChkGene){s1.setGeneNum(); s2.setGeneNum();} + else {s1.setAnnotation(); s2.setAnnotation();} + + symap.getDrawingPanel().setTrackEnds(1, track2Start, track2End); + symap.getDrawingPanel().setTrackEnds(2, track1Start, track1End); + symap.getFrame().showX(); + } + catch(Exception e) {ErrorReport.print(e, ""Create 2D Synteny"");} + } + /***********************************************************/ + private void showSyntenyfor3() {// this is partially redundant with above, but easier... + try{ + int [] col = tPanel.getSharedRef(false); + if (col == null) return; + + TmpRowData [] rd = new TmpRowData [2]; + + rd[0] = new TmpRowData(tPanel); + if (!rd[0].loadRow(tPanel.theTable.getSelectedRows()[0])) {Globals.tprt(""No load 0"");return;} + rd[1] = new TmpRowData(tPanel); + if (!rd[1].loadRow(tPanel.theTable.getSelectedRows()[1])) {Globals.tprt(""No load 1"");return;} + + int r0t1 = col[0], r0t2 = col[1], + r1t2 = col[2], r1t3 = col[3]; + + int sL=0, eL=1, sR=2, eR=3; + int [] coordsRow0 = new int [4]; + int [] coordsRow1 = new int [4]; + HfilterData hd0 = new HfilterData (); + HfilterData hd1 = new HfilterData (); + + if (selIndex==TableMainPanel.showSET) { + if (rd[0].collinearN==0 || rd[1].collinearN==0) { + Popup.showWarning(""The selected rows do not belong to a collinear set.""); + return; + } + int [] coords0 = loadCollinearCoords(rd[0].collinearN, rd[0].chrIdx[0], rd[0].chrIdx[1]);// ret sL,eL,sR,eR + int [] coords1 = loadCollinearCoords(rd[1].collinearN, rd[1].chrIdx[0], rd[1].chrIdx[1]); + hd0.setForQuery(0, true, false); // block, set, region + hd1.setForQuery(0, true, false); // block, set, region + + if (r0t1==0 && r0t2==1) { + coordsRow0[sL] = coords0[0]; coordsRow0[eL] = coords0[1]; // row0 + coordsRow0[sR] = coords0[2]; coordsRow0[eR] = coords0[3]; + } + else { + coordsRow0[sL] = coords0[2]; coordsRow0[eL] = coords0[3]; + coordsRow0[sR] = coords0[0]; coordsRow0[eR] = coords0[1]; + } + if (r1t2==0 && r1t3==1) { + coordsRow1[sL] = coords1[0]; coordsRow1[eL] = coords1[1]; // row1 + coordsRow1[sR] = coords1[2]; coordsRow1[eR] = coords1[3]; + } + else { + coordsRow1[sL] = coords1[2]; coordsRow1[eL] = coords1[3]; + coordsRow1[sR] = coords1[0]; coordsRow1[eR] = coords1[1]; + } + } + else if (selIndex==TableMainPanel.showREGION) { + coordsRow0[sL] = rd[0].start[r0t1]; coordsRow0[eL] = rd[0].end[r0t1]; // row0 + coordsRow0[sR] = rd[0].start[r0t2]; coordsRow0[eR] = rd[0].end[r0t2]; + coordsRow1[sL] = rd[1].start[r1t2]; coordsRow1[eL] = rd[1].end[r1t2]; + coordsRow1[sR] = rd[1].start[r1t3]; coordsRow1[eR] = rd[1].end[r1t3]; + + hd0.setForQuery(0, false, true); // block, set, region + hd1.setForQuery(0, false, true); + } + else { + JOptionPane.showMessageDialog(null, ""3-track display only works with Region or Collinear Set."", + ""Warning"", JOptionPane.WARNING_MESSAGE); + return; + } + int [] tStart = new int [3]; int [] tEnd = new int [3]; + int [] spIdx = new int [3]; int [] chrIdx = new int [3]; + + spIdx[0] = rd[0].spIdx[r0t1]; chrIdx[0] = rd[0].chrIdx[r0t1]; + spIdx[1] = rd[0].spIdx[r0t2]; chrIdx[1] = rd[0].chrIdx[r0t2]; // ref + spIdx[2] = rd[1].spIdx[r1t3]; chrIdx[2] = rd[1].chrIdx[r1t3]; + + tStart[0] = coordsRow0[sL] - pad; if (tStart[0]<0) tStart[0]=0; + tEnd[0] = coordsRow0[eL] + pad; + + int startRef = (coordsRow0[sR]coordsRow1[eL]) ? coordsRow0[eR] : coordsRow1[eL]; + tStart[1] = startRef - pad; if (tStart[1]<0) tStart[1]=0; + tEnd[1] = endRef + pad; + + tStart[2] = coordsRow1[sR] - pad; if (tStart[2]<0) tStart[2]=0; + tEnd[2] = coordsRow1[eR] + pad; + + tPanel.hitNum1 = rd[0].hitnum; tPanel.hitNum2 = rd[1].hitnum; + + // create new drawing panel; + SyMAP2d symap = new SyMAP2d(tPanel.qFrame.getDBC(), tPanel); + symap.getDrawingPanel().setTracks(3); + symap.getDrawingPanel().setHitFilter(1,hd0); // template for Mapper HfilterData, which is already created + symap.getDrawingPanel().setHitFilter(2,hd1); + + Sequence s1 = symap.getDrawingPanel().setSequenceTrack(1, spIdx[0], chrIdx[0], Color.CYAN); + Sequence s2 = symap.getDrawingPanel().setSequenceTrack(2, spIdx[1], chrIdx[1], Color.GREEN); // ref + Sequence s3 = symap.getDrawingPanel().setSequenceTrack(3, spIdx[2], chrIdx[2], Color.GREEN); + if (isChkGene){s1.setGeneNum(); s2.setGeneNum();s3.setGeneNum();} + else {s1.setAnnotation(); s2.setAnnotation(); s3.setAnnotation();} + + symap.getDrawingPanel().setTrackEnds(1, tStart[0], tEnd[0]); + symap.getDrawingPanel().setTrackEnds(2, tStart[1], tEnd[1]); // ref + symap.getDrawingPanel().setTrackEnds(3, tStart[2], tEnd[2]); + symap.getFrame().showX(); + } + catch(Exception e) {ErrorReport.print(e, ""Create 2D Synteny"");} + } + /***********************************************************/ + private int [] loadCollinearCoords(int set, int grpIdx1, int grpIdx2) { + int [] coords = null; + try { + int start1=Integer.MAX_VALUE, end1=-1, start2=Integer.MAX_VALUE, end2=-1, d; + + DBconn2 dbc2 = tPanel.qFrame.getDBC(); + String sql = ""select start1, end1, start2, end2 from pseudo_hits where runnum="" + set; + if (isSelf && grpIdx1==grpIdx2) sql += "" and start1start2; but not here... + + ResultSet rs = dbc2.executeQuery(sql + "" and grp1_idx="" + grpIdx1 + "" and grp2_idx="" + grpIdx2); + while (rs.next()) { + d = rs.getInt(1); if (dend1) end1 = d; + + d = rs.getInt(3); if (dend2) end2 = d; + } + if (start1==Integer.MAX_VALUE) { // try flipping idx1 and idx2 + rs = dbc2.executeQuery(sql + "" and grp1_idx="" + grpIdx2 + "" and grp2_idx="" + grpIdx1); + while (rs.next()) { + d = rs.getInt(1); if (dend2) end2 = d; + + d = rs.getInt(3); if (dend1) end1 = d; + } + } + rs.close(); + if (start1==Integer.MAX_VALUE) { + Globals.eprt(""Could not find collinear set "" + set); + return null; + } + + coords = new int [4]; + coords[0]=start1; + coords[1]=end1; + coords[2]=start2; + coords[3]=end2; + + return coords; + } + catch(Exception e) {ErrorReport.print(e, ""get collinear coords""); return null;} + } + /***********************************************************/ + private int [] loadBlockCoords(int block, int idx1, int idx2) { + int [] coords = null; + try { + DBconn2 dbc2 = tPanel.qFrame.getDBC(); + + String sql = ""select start1, end1, start2, end2 from blocks where blocknum=""+block; + if (isSelf && idx1==idx2) sql += "" and start1 hitVec = new Vector (); + private int numRows=0; + private long alignBase=0; + private boolean bOkay=false; + private boolean bSuccess=true; + private AlignPool aPool = null; + + private MsaAlign() { + try { + DBconn2 dbc = tPanel.qPanel.getDBC(); + aPool = new AlignPool(dbc); + + tPanel.setPanelEnabled(false); + createMenu(); + if (bOkay) { + tPanel.setMsaButton(false); + + buildHitVec(); if (!bSuccess) return; + loadSeq(); if (!bSuccess) return; + buildTableAndAlign(); + } + tPanel.setPanelEnabled(true); + } + catch(Exception e) {ErrorReport.print(e, ""Show alignment"");} + } + private void popupHelp() { + String msg = """"; + msg += ""Merge overlap hits: this greatly reduces bases aligned by removing redundant sequence""; + msg += ""\nUse gapless hits: this is good for genes with long introns (e.g. homo sapiens), "" + + ""\n where the subhits are separatedly by long intronic regions. ""; + msg += ""\n\nSee ? for details.\n""; + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + + /********************************************************/ + private void createMenu() { + setModal(true); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setTitle(""MSA options""); + + JPanel selectPanel = Jcomp.createPagePanel(); + + ButtonGroup bg = new ButtonGroup(); + JPanel row1 = Jcomp.createRowPanel(); + JRadioButton mafft = Jcomp.createRadio(""MAFFT"", ""Align with MAFFT (Katoh 2013 MBA:30""); + mafft.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bMAFFT = mafft.isSelected(); + } + }); + row1.add(mafft); row1.add(Box.createHorizontalStrut(3)); + bg.add(mafft); + + JCheckBox chkAuto = Jcomp.createCheckBox(""Auto"", ""Use the MAFFT --auto option, which finds best method"", bAuto); + chkAuto.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bAuto = chkAuto.isSelected(); + } + }); + row1.add(chkAuto); row1.add(Box.createHorizontalStrut(3)); + + txtCPUs = new JTextField(2); + txtCPUs.setMaximumSize(txtCPUs.getPreferredSize()); + txtCPUs.setMinimumSize(txtCPUs.getPreferredSize()); + txtCPUs.setText(nCPU+""""); + row1.add(Jcomp.createLabel(""CPUs: "")); row1.add(txtCPUs); + selectPanel.add(row1);selectPanel.add(Box.createVerticalStrut(5)); + + JPanel row2 = Jcomp.createRowPanel(); + JRadioButton muscle = Jcomp.createRadio(""MUSCLE"", ""Align with MUSCLE (Edgar 2004 NAR:32)""); + muscle.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bMAFFT = !muscle.isSelected(); + } + }); + if (!Ext.isMacM4()) {// no MUSCLE for M4 (executable had hard-link and could not compile easily) + row2.add(muscle); bg.add(muscle); + } + selectPanel.add(row2); selectPanel.add(Box.createVerticalStrut(5)); + if (bMAFFT) mafft.setSelected(true); else muscle.setSelected(true); + + selectPanel.add(new JSeparator()); + + JRadioButton radMerge = Jcomp.createRadio(""Merge overlapping seqs"", ""Merge overlapping sequences""); + radMerge.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bGapLess = false; + bMerge = radMerge.isSelected(); + } + }); + JRadioButton radGapLess = Jcomp.createRadio(""Use gapless hits"", ""For cluster hits, remove gaps""); + radGapLess.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bMerge = false; + bGapLess = radGapLess.isSelected(); + } + }); + JRadioButton radNone = Jcomp.createRadio(""None of the above"", ""Align all hits ends as is""); + radNone.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bMerge = bGapLess = false; + } + }); + ButtonGroup rg = new ButtonGroup(); + rg.add(radMerge); rg.add(radGapLess); rg.add(radNone); + + if (bMerge) radMerge.setSelected(true); + else if (bGapLess) radGapLess.setSelected(true); + else radNone.setSelected(true); + + JCheckBox chkTrim = Jcomp.createCheckBox(""Trim"", ""Trim ends that has no match"", bTrim); + chkTrim.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bTrim = chkTrim.isSelected(); + } + }); + selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(radMerge); selectPanel.add(Box.createVerticalStrut(3)); + selectPanel.add(radGapLess); selectPanel.add(Box.createVerticalStrut(3)); + selectPanel.add(radNone); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(new JSeparator()); + selectPanel.add(chkTrim); selectPanel.add(Box.createVerticalStrut(5)); + selectPanel.add(new JSeparator()); + + JPanel row = Jcomp.createRowPanel(); row.add(Box.createHorizontalStrut(5)); + JButton btnOK = Jcomp.createButton(""Align"", ""Run MSA align""); + btnOK.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bOkay=true; + setVisible(false); + } + }); + row.add(Box.createHorizontalStrut(5)); + row.add(btnOK); row.add(Box.createHorizontalStrut(5)); + + JButton btnCancel = Jcomp.createButton(Jcomp.cancel, ""Cancel align""); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + bOkay=false; + setVisible(false); + } + }); + row.add(btnCancel); row.add(Box.createHorizontalStrut(5)); + + JButton btnInfo = Jcomp.createBorderIconButton(""/images/info.png"", ""Quick Help Popup""); + btnInfo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + popupHelp(); + } + }); + row.add(btnInfo); row.add(Box.createHorizontalStrut(5)); + + selectPanel.add(row); + selectPanel.add(Box.createVerticalStrut(5)); + + selectPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + add(selectPanel); + + pack(); + this.setResizable(false); + setLocationRelativeTo(null); + setVisible(true); + } + /*************************************************************** + * Create hitVec for alignment; perform bMerge + ***************************************************************/ + private void buildHitVec() { + try { + if (bMAFFT) { + if (Ext.getMafftCmd()==null) {bSuccess=false; return;} + } + else { + if (Ext.getMafftCmd()==null) {bSuccess=false; return;} + } + alignBase=0; + int [] selRows = tPanel.theTable.getSelectedRows(); + numRows = selRows.length; + HashMap tagMap = new HashMap (); + + TmpRowData rd = new TmpRowData(tPanel); + if (!bMerge) { + for(int x=0; x20) { + ht.updateCoords(rd.start[i], rd.end[i], rd.hitnum); + merged=true; + break; + } + } + } + } + if (!merged) { + String gapLess = (!bGapLess) ? """" : rd.hitnum + "";"" + rd.chrIdx[0] + "";"" + rd.spIdx[0]+ "";"" + rd.chrIdx[1]+ "";"" + rd.spIdx[1]; + HitEnd h = new HitEnd(i, rd.hitnum, rd.start[i], rd.end[i], rd.chrIdx[i], rd.spAbbr[i], + rd.chrNum[i], rd.geneTag[i], hitSt[i], gapLess); + hitVec.add(h); + if (key!=null) tagMap.put(key, h); + } + } + } // end merge + for (HitEnd ht : hitVec) alignBase += (ht.end-ht.start)+1; // need to wait until after merges + } + + catch (Exception e) {ErrorReport.print(e, ""Building gene vec for muscle""); bSuccess=false;} + } + /***************************************************** + * Load full sequence or gapless + */ + private void loadSeq() { + try { + for (HitEnd ht : hitVec) { + ht.theSeq = aPool.loadSeq(ht.pos, ht.start + "":"" + ht.end, ht.chrIdx, ht.gapLess); // needed for gapLess + if (ht.strand.equals(""-"")) ht.theSeq = SeqData.revComplement(ht.theSeq); + } + } + catch (Exception e) {ErrorReport.print(e, ""Load sequences""); bSuccess=false;} + } + /******************************************************** + * Create the vectors of names and sequence, lower table, and calls tdp.queryFrame.addAlignmentTab + ******************************************************/ + private void buildTableAndAlign() { + Vector theTable = new Vector (); // Table at bottom giving more info + Vector theNames = new Vector (); // Names go beside sequence alignment + Vector theSeqs = new Vector (); // Actual sequences + + String [] fields = { """" , ""Gene#"", ""Start"", ""End"", ""St"", ""Length"", ""Hit#""}; + int [] justify = { 1, 1, 0, 0, 0, 0, 1}; // 1 left justify + int nRow = hitVec.size(); + int nCol= fields.length; + String [][] rows = new String[nRow][nCol]; + int r=0, maxLen=0; + + for (HitEnd ht : hitVec) { + String name = String.format(""%2d. %s.%s"", (r+1), ht.spAbbr, ht.chrNum); + theNames.add(name); + theSeqs.add(ht.theSeq); + + int len = ht.theSeq.length(); + maxLen = Math.max(maxLen, len); + + int c=0; + rows[r][c++]=String.format(""%2d. %s.%s"", r+1, ht.spAbbr, ht.chrNum); + rows[r][c++]=ht.geneTag.substring(ht.geneTag.indexOf(""."")+1); + rows[r][c++]=String.format(""%,d"",ht.start); + rows[r][c++]=String.format(""%,d"",ht.end); + rows[r][c++]=String.format(""%s"",ht.strand); + rows[r][c++]=String.format(""%,d"",len); + rows[r][c++]=ht.hitNumStr; + r++; + } + + Utilities.makeTable(theTable, nCol, nRow, fields, justify, rows); + + nCPU = Utilities.getInt(txtCPUs.getText()); + if (nCPU<=0) nCPU=1; + + String tabAdd = ""#"" + hitVec.get(0).hitNum + "" ("" + r + "")""; // left hand tab; append after MSA N: + String pgm = (bMAFFT) ? ""MAFFT"" : ""MUSCLE""; // MsaMainPanel reads for MUS!! + String progress = String.format("" Run %s in directory /%s. Align %s (max hit %s bases)....\n"", + pgm, Globals.alignDir, Utilities.kMText(alignBase), Utilities.kMText(maxLen)); // If progress line is too long, it blanks panel + + String params = pgm; + if (bMAFFT && bAuto) params += "" Auto""; + if (bMerge) params += "" Merge""; + if (bGapLess) params += "" GapLess""; + String msaSum = params; // for MSA panel (trim # is added in AlignRun) + + String resultSum = pgm; // for result table + if (bTrim) resultSum += "" Trim""; + resultSum += ""; Hit#"" + hitVec.get(0).hitNum + "" plus "" + (r-1) + "" more""; + + /*-------------- ALIGN -------------------*/ + // msaSum must start with 'MUS' for muscle, else it will run mafft + String [] names = theNames.toArray(new String[0]); + String [] seqs = theSeqs.toArray(new String[0]); + String [] tabLines = theTable.toArray(new String[0]); + + // Add tab and align - QueryFrame calls MsaMainPanel, which is treaded + tPanel.qFrame.makeTabMSA(tPanel, names, seqs, tabLines, + progress, tabAdd, resultSum, msaSum, bTrim, bAuto, nCPU); + + theNames.clear(); theTable.clear(); theSeqs.clear(); + } + /*--- HitEnd class --*/ + private class HitEnd { + private int pos, start, end, chrIdx, hitNum; + private String strand; + private String spAbbr, chrNum, geneTag; + private boolean bIsGene=false; + private String theSeq=""""; + private String hitNumStr=""""; + private String gapLess=""""; + + private HitEnd(int pos, int hitNum, int start, int end, int chrIdx, String spAbbr, String chrNum, String geneTag, String strand, String gapLess) { + this.pos=pos; this.start=start; this.end=end; this.chrIdx=chrIdx; + this.spAbbr=spAbbr; this.chrNum=chrNum; + this.geneTag=geneTag; + this.strand=strand; + bIsGene = !geneTag.endsWith(Q.dash); + this.hitNum=hitNum; hitNumStr = hitNum+""""; + this.gapLess = gapLess; + } + private void updateCoords(int start, int end, int hitNum) { + if (this.start>start) this.start=start; + if (this.end columns = new Vector (); + for (int x=selCols.length-1; x>=0; x--) columns.add(selCols[x]); + + int targetIndex = 0; + for (int x=0; x= 0) { + retVal[targetIndex] = colName; + targetIndex++; + columns.remove(colIdx); + } + } + while (columns.size() > 0) { + retVal[targetIndex] = columns.get(columns.size()-1); + columns.remove(columns.size()-1); + targetIndex++; + } + return retVal; + } + /**************************************************************** + * Arrange columns: + * Group all gene columns with same second part, e.g. Gene#. + * Group Hit columns, then rest of General + */ + protected static String [] arrangeColumns(String [] selColList, boolean isSingle, AnnoData theAnno) { + try { + // Group selected columns into sp, hit or general + final String HIT = Q.hitPrefix, GEN = ""Gen""; + + HashMap selColMap = new HashMap (); + selColMap.put(HIT, new ArrCol()); + selColMap.put(GEN, new ArrCol()); + + TreeSet spSet = theAnno.getSpeciesAbbrList(); // abbrev for selected set + for (String sp : spSet) selColMap.put(sp, new ArrCol()); + + for (String col : selColList) { + String prefix="""", root=""""; + if (col.contains(""\n"")) { + String [] tok = col.split(""\n""); + prefix = tok[0]; root = tok[1]; + } + else root = col; + + if (!prefix.isEmpty() && spSet.contains(prefix)) { + selColMap.get(prefix).cols.put(root, false); // prefix removed + } + else if (root.equals(Q.hitCol) || prefix.equals(HIT)) { + selColMap.get(HIT).cols.put(col, false); // may have ""\n"" + } + else { + selColMap.get(GEN).cols.put(col, false); // may have ""\n"" + } + } + + // Build return array from selColMap + String [] retColList = new String[selColList.length]; + int ix=0; + retColList[ix++] = Q.rowCol; + + // 1. species 1st; add static gene set in Field order but all selected species together + String [] spFcolList = TableColumns.getSpeciesColHead(isSingle); // static gene columns + + for (String col : spFcolList) { + for (String sp : spSet) { + ArrCol spColObj = selColMap.get(sp); + if (spColObj.cols.containsKey(col)) { + retColList[ix++] = sp + ""\n"" + col; // prefix put back on + spColObj.cols.put(col, true); + } + } + } + + // 2. put in GFF species column + for (int i=0; i<2; i++) { // 1st ID, 2nd desc, product (1. Only if these not in order. 2. Exact match) + String [] kcolList = (i==0) ? AnnoData.key1 : AnnoData.key2; + + for (String sp : spSet) { // by species order first + ArrCol spColObj = selColMap.get(sp); + + for (String kcol : kcolList) { + if (spColObj.cols.containsKey(kcol)) { + retColList[ix++] = sp + ""\n"" + kcol; + spColObj.cols.put(kcol, true); + } + } + } + } + // rest of GFF species columns in order found + for (String sp1 : spSet) { + ArrCol spColObj1 = selColMap.get(sp1); + for (String scol : spColObj1.cols.keySet()) { + if (spColObj1.cols.get(scol)) continue; // already added + + retColList[ix++] = sp1 + ""\n"" + scol; + spColObj1.cols.put(scol, true); + + for (String sp2 : spSet) { // see if other species have same column + if (sp1.equals(sp2)) continue; + + ArrCol spColObj2 = selColMap.get(sp2); + if (spColObj2.cols.containsKey(scol) && !spColObj2.cols.get(scol)) { + retColList[ix++] = sp2 + ""\n"" + scol; + spColObj2.cols.put(scol, true); + } + } + } + } + + // 3. hit columns in Fields order + String [] genFcolList = TableColumns.getGeneralColHead(); // e.g. Block, Grp#, Hit#, Hit %id, etc + + ArrCol hitColObj = selColMap.get(HIT); + for (String col : genFcolList) { + if (col.startsWith(Q.hitPrefix)) + if (hitColObj.cols.containsKey(col)) retColList[ix++] = col; + } + + // 4. general in Fields order + ArrCol genColObj = selColMap.get(GEN); + for (String col : genFcolList) { + if (!col.equals(Q.rowCol) && !col.startsWith(Q.hitPrefix)) + if (genColObj.cols.containsKey(col)) retColList[ix++] = col; + } + + if (ix==selColList.length) return retColList; + + Globals.tprt(""Error Length "" + ix + "" "" + selColList.length); + for (String s : retColList) if (s!=null) Globals.tprt(s.replace(""\n"", "" "")); + return selColList; // problem with building new list + } + catch (Exception e) {ErrorReport.print(e,""Arrange columns""); return selColList;} + } + static private class ArrCol { // selColMap.key = SP, HIT, GEN + private HashMap cols = new HashMap (); // Column name, true if gene put in colMap + } + /*****************************************************************/ + /*************************************** + * XXX Constructors + */ + protected TableData(String tblID, TableMainPanel parent) { // called from TableDataPanel.buildTable + this.tblId = tblID; + vData = new Vector>(); + vHeaders = new Vector(); + tPanel = parent; + } + + /********************************************************/ + protected void sortMasterList(String columnName) { + tPanel.sortMasterColumn(columnName); + } + + protected void setColumnHeaders( String [] species, String [] annoKeys, boolean isSingle) { + vHeaders.clear(); + + // General + String [] genColNames = TableColumns.getGeneralColHead(); + Class [] genColType = TableColumns.getGeneralColType(); + int genColCnt = TableColumns.getGenColumnCount(isSingle); + + for(int x=0; x [] spColType = TableColumns.getSpeciesColType(isSingle); + int spColCnt = TableColumns.getSpColumnCount(isSingle); // less columns for single + + for(int x=0; x < species.length; x++) { + String sp = species[x]+ Q.delim ; + for (int c=0; c< spColCnt; c++) + addColumnHeader(sp + spColNames[c], spColType[c]); + } + // array of species+Q.delim+keywords in correct order + for (int x=0; x type) { + try { + vHeaders.add(new TableDataHeader(columnName, type)); + } + catch(Exception e) {ErrorReport.print(e, "" Add column header "" + columnName);} + } + + protected int getColHeadIdx(String columnName) { + int retVal = -1; + + for (int x=0;x rowsFromDB, JTextField progress) { + try { + boolean cancelled = false; + + for (DBdata dd : rowsFromDB) { + if (cancelled) { + System.err.println(""Cancel adding rows to table""); + return; + } + + Vector row = dd.formatRowForTbl(); + vData.add(row); + + if (progress != null && (vData.size() % DISPLAY_INTERVAL == 0)) { + if(progress.getText().equals(""Cancelled"")) cancelled = true; + else progress.setText(""Displaying "" + vData.size() + "" rows""); + } + } + progress.setText(""""); + } + catch (Exception e) {ErrorReport.print(e, ""add Rows With Progress"");} + } + + // it was using iteration and copyInfo; copyInfo would not work with the self, which I never figured out why; CAS575 + protected void finalizeX() { // X so not deprecated + int ncol = vHeaders.size(); + arrHeaders = new TableDataHeader[ncol]; + + for (int i=0; i row = vData.get(i); + + for (int j=0; j< arrHeaders.length; j++) { + if (j>=row.size()) break; // for isSelf + arrData[i][j] = row.get(j); + } + } + vData.clear(); + } + + protected Object getValueAt(int row, int column) { + try { + return arrData[row][column]; + } + catch(Exception e) {ErrorReport.print(e, ""get value at row "" + row + "" col "" + column); return null;} + } + protected String getColumnName(int column) { + try { + if (column==-1) return """"; + return arrHeaders[column].getColumnName(); + } catch(Exception e) {ErrorReport.print(e, ""get column name at "" + column); return null;} + } + protected Class getColumnType(int column) { + try { + return arrHeaders[column].getColumnClass(); + } + catch(Exception e) {ErrorReport.print(e, ""get column type at "" + column);return null;} + } + protected boolean isAscending(int column) { + try { + if (column==-1) return true; + return arrHeaders[column].isAscending(); + } + catch(Exception e) {ErrorReport.print(e, ""sort ascending"");return false;} + } + + protected int getNumColumns() { + if(arrHeaders!=null) return arrHeaders.length; + if (vHeaders!=null) return vHeaders.size(); + return 0; + } + + protected int getNumRows() { + if (arrData!=null) return arrData.length; + if (vData!=null) return vData.size(); + return 0; + } + protected void clear() { + arrHeaders = null; + if(arrData != null) { + for(int x=0; x { + protected ColumnComparator(int column) { + nColumn = column; + } + public int compare(Object [] o1, Object [] o2) { + try { + if (nColumn == -1) return 0; + + String colHeader = arrHeaders[nColumn].getColumnName(); + + if (colHeader.equals(Q.rowCol)) { + return 0; + } + if(o1[nColumn] == null || o2[nColumn] == null) { // DBdata checks, there should be no null + System.out.println(arrHeaders[nColumn].getColumnName() + "" Incorrect null value, not expected for sort""); + return 0; + } + + int retval = 0; + + if (colHeader.endsWith(Q.gStrandCol)) { // was separate since strand can be '-', and empty was '-', but now '.' + retval = ((String)o1[nColumn]).compareTo((String)o2[nColumn]); + } + else if (o1[nColumn] instanceof String && ((String)o1[nColumn]).equals(Q.empty) && + o2[nColumn] instanceof String && ((String)o2[nColumn]).equals(Q.empty)) { + return 0; + } + else if (o1[nColumn] instanceof String && ((String)o1[nColumn]).equals(Q.empty)) { + if(arrHeaders[nColumn].isAscending()) retval = 1; + else retval = -1; + } + else if (o2[nColumn] instanceof String && ((String)o2[nColumn]).equals(Q.empty)) { + if(arrHeaders[nColumn].isAscending()) retval = -1; + else retval = 1; + } + else if (colHeader.equals(Q.grpCol)) { // sort on grp# instead of sz; is Sz-Grp (no chr); change here, change in DBdata.sortRows + String [] vals1 = ((String)o1[nColumn]).split(Q.GROUP); + String [] vals2 = ((String)o2[nColumn]).split(Q.GROUP); + int n = Math.min(vals1.length, vals2.length); + + for(int x=n-1; x>0 && retval == 0; x--) { + boolean valid = true; + Integer leftVal = null, rightVal = null; + + try { + leftVal = Integer.parseInt(vals1[x]); + rightVal = Integer.parseInt(vals2[x]); + } + catch(Exception e) {valid = false; Globals.prt(""not valid "" + vals1[x] + "" "" + vals2[x]);} + + if (valid) retval = leftVal.compareTo(rightVal); + else retval = vals1[x].compareTo(vals2[x]); + } + } + else if (colHeader.endsWith(Q.gNCol)) { // Sorts left to right (chr.genenum.suffix); + String [] vals1 = ((String)o1[nColumn]).split(Q.SDOT); + String [] vals2 = ((String)o2[nColumn]).split(Q.SDOT); + + boolean t1 = (vals1[vals1.length-1].equals(Q.pseudo)); + boolean t2 = (vals2[vals2.length-1].equals(Q.pseudo)); + if (t1 && !t2) return 1; + if (!t1 && t2) return -1; + + int n = Math.min(vals1.length, vals2.length); + + for(int x=0; x0 && nColumn getRowLocData(int row) { // For Group + HashMap headVal = new HashMap (); + for (int i=0; i colNames, Vector colVals) { + for (int i=0; i getAllAnno(int row) { + HashMap rowMap = new HashMap (); + for (int i=0; i vHeaders = null; + private Vector> vData = null; + private TableMainPanel tPanel = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/TableDataHeader.java",".java","818","29","package symapQuery; + +public class TableDataHeader { + protected TableDataHeader() {} + + protected TableDataHeader(String label, Class type) { + strName = label; + columnType = type; + } + + protected TableDataHeader(String label) { + strName = label; + columnType = Object.class; + } + + protected String getColumnName() { return strName; } + + protected Class getColumnClass() { return columnType; } + + protected boolean isAscending() { return bAscending; } + protected void flipAscending() { bAscending = !bAscending; } + protected void setAscending(boolean ascending) { bAscending = ascending; } + + public String toString() { return strName; } + + private String strName = null; + private Class columnType = null; + private boolean bAscending = false; +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/ComputeClust.java",".java","11481","337","package symapQuery; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Vector; +import javax.swing.JTextField; + +import symap.Globals; +import util.ErrorReport; +import util.Popup; + +/************************************************************* + * Cluster genes that share hits + * Only g2 and g1 as gene based; g1 used if Pseudo + */ +public class ComputeClust { + private boolean TRC = Globals.TRACE; + private boolean bSaveLgClust = Globals.bQuerySaveLgClust; + private int MAX_CL=20000; // stop if clusters get too large + + // Output structures; row is not removed in DBdata if no hitIdx2Grp entry + private HashMap hitIdx2Grp; // hitID to Cluster# + private HashMap grpSizes; // group sizes + + // Input: + private QueryPanel qPanel; + private Vector inRows; // Rows will be removed in DBdata if no hitIdx2Grp entry + private JTextField loadStatus; + private boolean bPerSpecies=true; + private int cutoff=0; + + //From query panel + private HashMap idxSpMap = new HashMap (); // spIdx, Species + private HashMap geneClMap = new HashMap (); // annotIdx, Cluster; used for Merge + private HashMap hitClMap = new HashMap (); // hitIdx, Cluster + private Vector clVec = new Vector (); + + private HashMap idxGeneMap = new HashMap (); + + private int clNum=0; + private boolean bSuccess=true; + + protected ComputeClust( + Vector rowsFromDB, + QueryPanel queryPanel,JTextField progress, + HashMap hitIdx2Grp, HashMap grpSizes) { // output structures + + this.inRows = rowsFromDB; + this.qPanel = queryPanel; + this.loadStatus = progress; + // Output structures: + this.hitIdx2Grp = hitIdx2Grp; // identify hits in clusters; only these will be kept as rows with the assigned cluster + this.grpSizes = grpSizes; // to save grp sizes with each hit to can show sz.cl# + + try { + initFilters(); if (!bSuccess) return; + + computeClust(); if (!bSuccess) return; + + filterClust(); if (!bSuccess) return; + + rmLgClust(); if (!bSuccess) return; + + makeOutput(); + } + catch (Exception e) {ErrorReport.print(e, ""Compute Cluster""); } + } + + /**************************************************************** + * If either end is in cluster, add hit + ***************************************************************/ + private void computeClust() { + try { + int rowNum=0, numMerge=0, numRow=inRows.size(); + for (DBdata dd : inRows) { + rowNum++; + if (rowNum % Q.INC == 0) { + if (loadStatus.getText().equals(Q.stop)) {bSuccess=false; return;} + int i = (int) (((double)rowNum/(double)numRow) * 100.0); + loadStatus.setText(""Cluster "" + i + ""% of rows into "" + clVec.size() + "" ("" + numMerge + "" merged)...""); + System.gc(); + } + if (dd.annotIdx[0]<=0 || dd.annotIdx[1]<=0) continue; // pseudo_genes have annotIdx + + Cluster clObj0 = geneClMap.containsKey(dd.annotIdx[0]) ? geneClMap.get(dd.annotIdx[0]) : null; // idx->geneClMap in addHit + Cluster clObj1 = geneClMap.containsKey(dd.annotIdx[1]) ? geneClMap.get(dd.annotIdx[1]) : null; + Cluster clObj=null; + + if (clObj0!=null && clObj1!=null) { + if (clObj0==clObj1) clObj = clObj0; + else { + clObj0.mergeCluster(clObj1); // Merge + clObj = clObj0; + + numMerge++; + } + } + else if (clObj0!=null) clObj=clObj0; + else if (clObj1!=null) clObj=clObj1; + else { + clObj = new Cluster(clNum++); + clVec.add(clObj); + } + clObj.addHit(dd); // update geneClMap, hitClMap + } + + if (TRC) { + String msg = String.format(""Clusters: %,4d Merge : %,4d Genes: %,5d Hits%,6d"", clNum, numMerge, geneClMap.size(), hitClMap.size()); + Globals.prt(msg); + } + } + catch (Exception e) {ErrorReport.print(e, ""Compute Cluster""); bSuccess=false; } + catch (OutOfMemoryError e) {ErrorReport.print(e, ""Out of memory creating clusters"");} + } + + /*********************************************************** + * Exc: if there is any link to an excluded, it excludes the whole group; + * this means that gene pairs can occur when %sim, etc set that do not appear otherwise + ***********************************************************/ + private void filterClust() { // set filtered cl.clNum to 0 + try { + int nFilter=0; + for (Cluster clObj : clVec) { + int n = (bPerSpecies) ? clObj.geneSet.size() : clObj.hitMap.size(); + if (n0) { + clObj.clear(); + break; // break out of species loop + } + } + else if (spObj.bInc) { + if (geneSpCnt==0 || (bPerSpecies && geneSpCnt newClVec = new Vector (); + if (bSaveLgClust) { // remove dead clusters + for (Cluster clObj : clVec) if (clObj.clNum>0) newClVec.add(clObj); + clVec = newClVec; + return; + } + + int cntRm=0; + for (Cluster clObj : clVec) { + if (clObj.clNum>0 && clObj.numHit<=MAX_CL) { + newClVec.add(clObj); + } + else if (clObj.numHit>MAX_CL) { + clObj.clear(); + cntRm++; + } + } + clVec = newClVec; + + if (cntRm>0) { + String msg = String.format(""Removed %,d clusters that have >%,d hits.\nSet stricter filters and try again."", cntRm, MAX_CL); + Popup.showWarningMessage(msg); + } + } + catch (Exception e) {ErrorReport.print(e, ""Remove large clusters""); bSuccess=false;} + } + /*********************************************************** + * Populate output structures, renumber + * private HashMap hitIdx2Grp; // all hits: hitID to clNum + * private HashMap grpSizes; // all Clust: clNum to size + * private HashMap projMap; // all species: species name to summary + */ + private void makeOutput() { + try { + // The output is sorted in DBdata.sortRows, but the grpNum can change based on order of species input. + // Hence, sort here first for deterministic numbering. CAS578 add sort + loadStatus.setText(""Sort "" + clVec.size() + "" cluster...""); + + try { + Collections.sort(clVec, new Comparator () { + public int compare(Cluster c1, Cluster c2) { + if (c2.numHit!=c1.numHit) return c2.numHit-c1.numHit; + + int cmpNum0 = c1.chrNum[0].compareTo(c2.chrNum[0]); + if (cmpNum0!=0) return cmpNum0; + + int cmpNum1 = c1.chrNum[1].compareTo(c2.chrNum[1]); + if (cmpNum1!=0) return cmpNum1; + + return 0; + } + } ); + } catch (Exception e) {} // in case it violates + + if (loadStatus.getText().equals(Q.stop)) {bSuccess=false; return;} // uses Stopped + + // new cluster number + // The clusters use the hit number, even if the perGene option was used; otherwise, it is confusing to view + int nGrpNum=1; + for (Cluster clObj : clVec) { + if (clObj.clNum==0) continue; // clNum=0 filtered; + + clObj.clNum = nGrpNum++; // reassign new number + + grpSizes.put(clObj.clNum, clObj.hitMap.size()); // For rows in DBdata: cl#->size + } + // add cluster to hit + for (int hitIdx : hitClMap.keySet()) { + Cluster clObj = hitClMap.get(hitIdx); + if (clObj.clNum!=0) + hitIdx2Grp.put(hitIdx, clObj.clNum); // To create rows in DBdata: hit->Cl# + } + if (TRC) Globals.prt(String.format(""hitidx2Grp: %,d grpSizes: %,d"", hitIdx2Grp.size(), grpSizes.size())); + } + catch (Exception e) {ErrorReport.print(e, ""Make output""); bSuccess=false;} + } + /*********************************************************** + * Get filters from queryPanel; Create idxChrMap with inc/exc info + **************************************************/ + private void initFilters() { + try { + cutoff = qPanel.getClustN(); + bPerSpecies = qPanel.isClPerSp(); + + SpeciesPanel spPanel = qPanel.getSpeciesPanel(); + + for (int pos = 0; pos < spPanel.getNumSpecies(); pos++){ + Species sObj = new Species(); + sObj.spIdx = spPanel.getSpIdx(pos); + sObj.bExc = qPanel.isClExclude(pos); // either include/exclude/whatever + sObj.bInc = qPanel.isClInclude(pos); + idxSpMap.put(sObj.spIdx, sObj); + + for (String idxstr : spPanel.getChrIdxList(pos)){ + if(idxstr != null && idxstr.length() > 0) { + int idx = Integer.parseInt(idxstr); + sObj.chrIdx.add(idx); + } + } + } + } + catch (Exception e) {ErrorReport.print(e, ""FilterInit""); bSuccess=false;} + } + + /*****************************************************************/ + private class Cluster { + int clNum = 0; // assigned while building, then reassigned in makeOutput + String [] chrNum = {"""",""""}; + + HashMap hitMap = new HashMap (); + int numHit = 0; + + HashMap spCntMap = new HashMap (); // spIdx, count unique genes + HashSet geneSet = new HashSet (); // all genes; no count dups + + private Cluster(int num) { + clNum = num; + for (int idx : idxSpMap.keySet()) spCntMap.put(idx, 0); + } + private void addHit(DBdata dd) { + hitMap.put(dd.hitIdx, dd); + numHit++; + + for (int x=0; x<2; x++) { + if (chrNum[x]=="""" || dd.getChrNum(x).compareTo(chrNum[x])<0) + chrNum[x] = dd.getChrNum(x); // use smallest for sort + + // filters + int spkey = dd.spIdx[x]; + int gnKey = dd.annotIdx[x]; + if (!geneSet.contains(gnKey)) { // only count non-dups + spCntMap.put(spkey, spCntMap.get(spkey)+1); + geneSet.add(gnKey); + + if (!idxGeneMap.containsKey(gnKey)) idxGeneMap.put(gnKey, dd.geneTag[x]); + } + + } + // the following may replace another cluster during mergeCluster + geneClMap.put(dd.annotIdx[0], this); + geneClMap.put(dd.annotIdx[1], this); + hitClMap.put(dd.hitIdx, this); + } + private void mergeCluster(Cluster rmObj) { + for (DBdata dd : rmObj.hitMap.values()) addHit(dd); // move hits from cObj to this cluster; CAS579 bug wasn't moving + clVec.remove(rmObj); + } + private void clear() { + clNum=0; + numHit=0; + hitMap.clear(); + spCntMap.clear(); + geneSet.clear(); + } + public String toString() { + String msg = String.format(""%4d. #Hits %3d #Genes %3d Species: "", clNum, hitMap.size(), geneSet.size()); + for (int x : spCntMap.keySet()) { + Species sp = idxSpMap.get(x); + msg += sp.getDN() + "" "" + spCntMap.get(x) + "" "" + Globals.toTF(sp.bExc) + "" ""; + } + String x=""""; + for (int idx : geneSet) {x += "" "" + idxGeneMap.get(idx);} + msg += ""\n "" + x; + return msg; + } + } + private class Species { // in idxChrMap + int spIdx=0; + boolean bExc=false, bInc=false; + Vector chrIdx = new Vector (); + + private String getDN() { + return qPanel.spPanel.getSpNameFromSpIdx(spIdx); + } + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/TmpRowData.java",".java","8425","241","package symapQuery; + +import java.util.HashMap; +import java.util.Vector; + +import symap.Globals; +import util.ErrorReport; + +/*************************************************** + * Translates a row from a vector of objects to the correct data types for easy access, + * plus adds the species and chromosome index + * used in UtilReport, UtilExport writeFasta, and TableMainPanel.showAlignment, showRow, showSynteny + */ +public class TmpRowData { + private TableMainPanel tPanel; + + protected TmpRowData (TableMainPanel tdp) { + this.tPanel = tdp; + } + + protected String loadRowAsString(int row) {// show row + try { + String outLine = tPanel.theTableData.getRowData(row); // colName, value + return outLine; + } catch (Exception e) {ErrorReport.print(e, ""Getting row data""); return ""error"";} + } + + /* LoadRow; if add column, add to getRowLocData also */ + protected boolean loadRow(int row) {// showAlign, showSynteny, writeFasta, UtilReport + try { + nRow = row; + + Vector colNames = new Vector (); // for new 2D-3track + Vector colVals = new Vector (); + + tPanel.theTableData.getRowLocData(row, colNames, colVals); // only needed columns are returned + + HashMap sp2x = new HashMap (); + int isp=0; + + for (int i=0; i2 species, ignores ones w/o values, so only get 2 + String str = (String) colVal; + if (str.equals("""") || str.equals(Q.empty)) continue; // the blanks species + } + if (colHead.contentEquals(Q.blockCol)) { + String x = (String) colVal; + x = (x.contains(""."")) ? x.substring(x.lastIndexOf(""."")+1) : ""0""; + blockN = Integer.parseInt(x); + continue; + } + if (colHead.contentEquals(Q.cosetCol)) { // chr.chr.size.N + String x = (String) colVal; + String [] tok = x.split(Q.SDOT); + if (tok.length==4) { + collinearSz = Integer.parseInt(tok[2]); + collinearN = Integer.parseInt(tok[3]); + } + else Globals.dprt(""collinear "" + x + "" "" + tok.length); + continue; + } + if (colHead.contentEquals(Q.hitCol)) { + String x = String.valueOf(colVal); + hitnum = Integer.parseInt(x); + continue; + } + if (colHead.contentEquals(Q.hitSt)) { + hitSt = String.valueOf(colVal); + continue; + } + if (colHead.contentEquals(Q.grpCol)) { // ends with grpSz-grpN; + String x = (String) colVal; + String [] tok = x.split(Q.GROUP); + int len = tok.length-1; + if (tok.length>=2) { + groupSz = Integer.parseInt(tok[len-1]); + groupN = Integer.parseInt(tok[len]); + } + else Globals.dprt(""group "" + x + "" "" + tok.length); + continue; + } + + // Species columns + String [] field = colHead.split(Q.delim); // speciesName\nChr or Start or End + if (field.length!=2) continue; + String species=field[0]; + String col=field[1]; + + String sVal=""""; + int iVal=0; + if (col.equals(Q.chrCol)) { + if (colVal instanceof Integer) sVal = String.valueOf(colVal); + else sVal = (String) colVal; + } + else if (colVal instanceof Integer) { iVal = (Integer) colVal; } + else if (colVal instanceof String) { sVal = (String) colVal; } + else { + Globals.eprt(""Row Data "" + colHead + "" "" + colVal + "" is not type string or integer""); + return false; + } + + int i0or1=0; // only two species, none blank + if (sp2x.containsKey(species)) + i0or1 = sp2x.get(species); + else { + sp2x.put(species, isp); + spAbbr[isp] = species; + i0or1 = isp; + isp++; + if (isp>2) {Globals.eprt(""species "" + isp); break;} // should not happen + } + if (col.equals(Q.chrCol)) chrNum[i0or1] = sVal; + else if (col.equals(Q.hStartCol)) start[i0or1] = iVal; + else if (col.equals(Q.hEndCol)) end[i0or1] = iVal; + else if (col.equals(Q.gNCol)) geneTag[i0or1] = sVal; // this will be N.N.[b] or N.- + } + + // get supporting values + if (spAbbr[1]==null || spAbbr[1]=="""") { + util.Popup.showWarningMessage(""The abbrev_names are the same, cannot continue...""); + return false; + } + spName[0] = tPanel.qFrame.getDisplayFromAbbrev(spAbbr[0]); + spName[1] = tPanel.qFrame.getDisplayFromAbbrev(spAbbr[1]); + + SpeciesPanel spPanel = tPanel.qPanel.getSpeciesPanel(); + for (isp=0; isp<2; isp++) { + spIdx[isp] = spPanel.getSpIdxFromSpName(spName[isp]); + chrIdx[isp] = spPanel.getChrIdxFromChrNumSpIdx(chrNum[isp], spIdx[isp]); + } + return true; + } catch (Exception e) {ErrorReport.print(e, ""Getting row data""); return false;} + } + // Show Group + // loadRow occurs before this, so the selected row values are known for each row. + // If the group, chr[0], chr[1] are the same, get min start and max end + // grpIdxVec is hitNums to highlight for Groups in Show Synteny + protected int [] loadGroup(Vector grpIdxVec) { + try { + int [] coords = {0,0,0,0}; + coords[0] = start[0]; coords[1] = end[0]; coords[2] = start[1]; coords[3] = end[1]; + + for (int r=0; r colHeadVal = tPanel.theTableData.getRowLocData(r); + + String val = (String) colHeadVal.get(Q.grpCol); + String [] tok = val.split(Q.GROUP); + int grp = util.Utilities.getInt(tok[tok.length-1]); + if (grp!=groupN) continue; // only rows with this groupN (selected row) + + int hitNum=0; + int [] s = {0,0}; + int [] e = {0,0}; + boolean bGoodChr=true; + + for (String colHead : colHeadVal.keySet()) { + Object colVal = colHeadVal.get(colHead); + + if (colVal instanceof String) { + String str = (String) colVal; + if (str.equals("""") || str.equals(Q.empty)) continue; // ignore blank species + } + if (colHead.equals(Q.hitCol)) { // see isHitSelected + hitNum = (Integer) colVal; + continue; + } + + String [] field = colHead.split(Q.delim); // speciesName\nChr or Start or End + if (field.length!=2) continue; + + String species=field[0]; + String col=field[1]; + int x = (species.equals(spAbbr[0])) ? 0 : 1; + + if (col.equals(Q.chrCol)) { // if SameChr is not checked, make sure on same chrs as selected + String sVal; + if (colVal instanceof Integer) sVal = String.valueOf(colVal); + else sVal = (String) colVal; + if (!sVal.equals(chrNum[x])) { + bGoodChr = false; + break; // skip rest of row + } + } + else if (colVal instanceof Integer) { + if (col.equals(Q.hStartCol)) s[x] = (Integer) colVal; + else if (col.equals(Q.hEndCol)) e[x] = (Integer) colVal; + } + } // finish row + if (bGoodChr) { + grpIdxVec.add(hitNum); + coords[0] = Math.min(coords[0], s[0]); + coords[1] = Math.max(coords[1], e[0]); + coords[2] = Math.min(coords[2], s[1]); + coords[3] = Math.max(coords[3], e[1]); + } + } // finish all rows + return coords; + } catch (Exception e) {ErrorReport.print(e, ""Getting row data""); return null;} + } + /* UtilReport **/ + protected String getAnnoFromKey(String spAbbr, int row) { + try { + HashMap annoMap = tPanel.theTableData.getAllAnno(row); + + for (String colHead : annoMap.keySet()) { // All_Anno for all species in query + if (colHead.startsWith(spAbbr) && colHead.endsWith(Q.All_Anno)) + return annoMap.get(colHead); + } + return ""***"" + spAbbr + row; + } catch (Exception e) {ErrorReport.print(e, ""Getting row data""); return null;} + } + + // get gene coordinates; not used + protected Object [] getGeneCoords(String spAbbr, int row) { + return tPanel.theTableData.getGeneCoords(spAbbr, row); + } + public String toString() { + return String.format(""%4s %4s %10s %10s %5s %5s "", spAbbr[0], spAbbr[1], geneTag[0], geneTag[1], chrNum[0], chrNum[1]); + } + // Values for selected row; if add column, ADD in TableData TOO! + protected int nRow=0; + protected String [] spName = {"""",""""}; + protected String [] spAbbr = {"""",""""}; + protected int [] spIdx = {0,0}; + + protected int [] chrIdx = {0,0}; + protected String [] chrNum = {"""",""""}; + + protected int [] start = {0,0}; + protected int [] end = {0,0}; + + protected String [] geneTag = {"""",""""}; + + protected String hitSt=""""; + protected int hitnum=0, blockN=0; + protected int collinearN=0, collinearSz=0; + protected int groupN=0, groupSz=0; // for Show Group; set in loadRow, used in loadGroup +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/TableSort.java",".java","6558","167","package symapQuery; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.SwingConstants; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableModel; + +/******************************************************* + * Called from buildTable and setTable (change to columns) + * Referred to as 'theTable' in TableDataPanel + * + * prepareRenderer allows last minutes changes for display + * TableData.java ColumnComparator does actual sort + */ +public class TableSort extends JTable implements ListSelectionListener { + private static final long serialVersionUID = 5088980428070407729L; + + protected TableSort(TableData tData) { + theModel = new SortTableModel(tData); + + setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + setAutoCreateColumnsFromModel( true ); + setColumnSelectionAllowed( false ); + setCellSelectionEnabled( false ); + setRowSelectionAllowed( true ); + setShowHorizontalLines( false ); + setShowVerticalLines( true ); + setIntercellSpacing ( new Dimension ( 1, 0 ) ); + setOpaque(true); + + setModel(theModel); + } + + protected void sortAtColumn(int column) { + theModel.sortAtColumn(column); + } + protected void autofitColumns() { + TableModel model = getModel(); + TableColumn column; + Component comp; + + int cellWidth, maxDef; + TableCellRenderer headerRenderer = getTableHeader().getDefaultRenderer(); + + for (int i = 0; i < getModel().getColumnCount(); i++) { // for each column; default order + column = getColumnModel().getColumn(i); + + comp = headerRenderer.getTableCellRendererComponent(this, column.getHeaderValue(), false, false, 0, i); + cellWidth = comp.getPreferredSize().width; // header width + + for (int j = 0; j < getModel().getRowCount(); j++) { // for each row + comp = getDefaultRenderer(model.getColumnClass(i)). + getTableCellRendererComponent(this, model.getValueAt(j, i), false, false, j, i); + + cellWidth = Math.max(cellWidth, comp.getPreferredSize().width); + + if (j > 1001) break; // only check beginning rows, for performance reasons + } + + String head = (String) column.getHeaderValue(); + if (head.contains(Q.chrCol)) maxDef = MAX_AUTOFIT_COLUMN_CHR_WIDTH; + else if (theModel.getColumnClass(i) == String.class) + maxDef = MAX_AUTOFIT_COLUMN_STR_WIDTH; + else maxDef = MAX_AUTOFIT_COLUMN_INT_WIDTH; + column.setPreferredWidth(Math.min(cellWidth, maxDef)+5); + } + } + /* required */ + public Component prepareRenderer(TableCellRenderer renderer,int Index_row, int Index_col) { + Component comp = super.prepareRenderer(renderer, Index_row, Index_col); + if (comp instanceof JLabel) { + JLabel compLbl = (JLabel)comp; + Class cl = getColumnClass(Index_col); + + //even index, selected or not selected + if (isRowSelected(Index_row)) { + compLbl.setBackground(bgColorHighlight); + compLbl.setForeground(bgColor); + } + else if (Index_row % 2 == 0) { + compLbl.setBackground(bgColorAlt); + compLbl.setForeground(txtColor); + } + else { + compLbl.setBackground(bgColor); + compLbl.setForeground(txtColor); + } + if (cl == Integer.class) { + compLbl.setText(addCommas(compLbl.getText())); + } + else if (cl == Long.class) { + compLbl.setText(addCommas(compLbl.getText())); + } + if (compLbl.getText().contains(""/"")) { // For hit sign; cannot change earlier because MSA needs actual signs + String txt = compLbl.getText(); + if (txt.equals(""-/-"") || txt.equals(""+/+"")) compLbl.setText(""==""); + else if (txt.equals(""-/+"") || txt.equals(""+/-"")) compLbl.setText(""!=""); + } + compLbl.setHorizontalAlignment(SwingConstants.LEFT); + if (compLbl.getText().length() == 0) + compLbl.setText(""-""); + return compLbl; + } + return comp; + } + + private static String addCommas(String val) { + return val.replaceAll(""(\\d)(?=(\\d{3})+$)"", ""$1,""); + } + + /**********************************************************/ + private SortTableModel theModel = null; + + private final Color bgColor = Color.WHITE; + private final Color bgColorAlt = new Color(240,240,255); + private final Color bgColorHighlight = Color.GRAY; + private final Color txtColor = Color.BLACK; + + private final int MAX_AUTOFIT_COLUMN_STR_WIDTH = 120; // in pixels + private final int MAX_AUTOFIT_COLUMN_INT_WIDTH = 90; // in pixels + private final int MAX_AUTOFIT_COLUMN_CHR_WIDTH = 60; // in pixels + + /******************************************************************************* + * TableData ColumnComparator does actual sort + */ + protected class SortTableModel extends AbstractTableModel { + private static final long serialVersionUID = -2360668369025795459L; + + protected SortTableModel(TableData values) { + theData = values; + } + + protected void sortAtColumn(final int columnIndex) { + Thread t = new Thread(new Runnable() { + public void run() { + setCursor(new Cursor(Cursor.WAIT_CURSOR)); + theData.sortByColumn(columnIndex); + fireTableDataChanged(); + theData.sortMasterList(theModel.getColumnName(columnIndex)); + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + }); + t.setPriority(Thread.MIN_PRIORITY); + t.start(); + } + /* required */ + public boolean isCellEditable(int row, int column) { return false; } + public Class getColumnClass(int columnIndex) { return theData.getColumnType(columnIndex); } + public String getColumnName(int columnIndex) { return theData.getColumnName(columnIndex); } + public int getColumnCount() { return theData.getNumColumns(); } + public int getRowCount() { return theData.getNumRows(); } + public Object getValueAt(int rowIndex, int columnIndex) { return theData.getValueAt(rowIndex, columnIndex); } + + /* data */ + private TableData theData = null; + } +}","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/UtilSearch.java",".java","12906","366","package symapQuery; + +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JTextField; + +import symap.Globals; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.TreeSet; + +import util.ErrorReport; +import util.Jcomp; + +/***************************************************** + * Search button: select column to search and search for the entered gene + */ +public class UtilSearch extends JDialog{ + private static final long serialVersionUID = 1L; + + private TableMainPanel tPanel; + private String [] displayedCols; + private AnnoData annoObj; + private int rowIndex=-1, colIndex=-1, nextCnt=0, totalCnt=0; + private int curType=0; // 1 last 2 exact 3 substring - only used to see if value has changed + private String curVal="""", curCol; + private boolean isLast=false, isExact=false, isSubstring=false, isGene=false, isHit=false; + + private String [] skipCol = {Q.gEndCol, Q.gStartCol, Q.gLenCol, Q.gStrandCol, Q.hEndCol, Q.hStartCol, Q.hLenCol, Q.gOlap};// CAS578 add + + protected UtilSearch(TableMainPanel tpd, String [] cols, AnnoData spAnno) { + this.tPanel = tpd; + this.displayedCols = cols; + this.annoObj = spAnno; + + setModal(true); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); // uses upper left icons + setTitle(""Search""); + + createPanel(); + + pack(); + this.setResizable(false); + setLocationRelativeTo(null); // setVisible in calling routine so can reuse this panel with defaults + } + + /*****************************************************/ + private void createPanel() { + try { + JPanel selectPanel = Jcomp.createPagePanel(); + + // Search columns + TreeSet speciesSet = annoObj.getSpeciesAbbrList(); + ArrayList searchCols = new ArrayList (); + for (String col : displayedCols) { + + if (col.equals(Q.cosetCol) || col.equals(Q.hitCol) || col.equals(Q.blockCol) || col.equals(Q.grpCol)) { + searchCols.add(col); + } + else if (col.endsWith(Q.gNCol)) { // gene + searchCols.add(col.replace(""\n"","" "")); + } + else if (col.contains(""\n"")) { // annotation only + String [] tok = col.split(""\n""); + if (!speciesSet.contains(tok[0])) continue; // would only fail on ""Hit"" columns; Hitx could be spAbbr + + if (tok.length<2) continue; + + String n = tok[1]; // only want any annotation fields + for (int i=0; i0); + + JButton btnCancel = Jcomp.createButton(Jcomp.close, ""Close window""); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setVisible(false); + } + }); + row.add(btnCancel); row.add(Box.createHorizontalStrut(5)); + + JButton btnClear = Jcomp.createButton(""Restart"", ""Restarts the search from the first row""); + btnClear.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + restart(); + } + }); + row.add(btnClear); row.add(Box.createHorizontalStrut(5)); + + JButton btnInfo = Jcomp.createBorderIconButton(""/images/info.png"", ""Quick Help Popup""); + btnInfo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + popupHelp(); + } + }); + row.add(btnInfo); row.add(Box.createHorizontalStrut(5)); + + selectPanel.add(row); + selectPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + selectPanel.setMinimumSize(selectPanel.getPreferredSize()); + selectPanel.setMaximumSize(selectPanel.getPreferredSize()); + + add(selectPanel); + } + catch (Exception e) {ErrorReport.print(e, ""Creating search panel"");} + } + /***********************************************************/ + private void restart() { + curVal = curCol = """"; + curType = -1; + rowIndex = -1; + nextCnt = totalCnt = 0; + setStatus(""New search""); + } + /** See if anything has changed **/ + private void setChgVal() { + String val = txtSearch.getText().trim(); + + isLast=isExact=isSubstring=false; + int valType; + if (radLast.isSelected()) {valType=1; isLast=true;} + else if (radExact.isSelected()) {valType=2; isExact=true;} + else {valType=3; isSubstring=true;} + + String valCol = """"; + for (int i=0; i=0) totalCnt++; + else { + rowIndex = -1; // starts over in search using same values + break; + } + } + } + if (totalCnt==0) { + String op = ""Last#""; + if (isExact) op = ""Exact""; + else if (isSubstring) op = ""Substring""; + String msg = String.format(""No %s value of '%s' in %s"", op, txtSearch.getText().trim(), curCol); + setStatus(msg); + return; + } + // get the next + int index = getRowIndex(nrows, findStr); + + if (index == -1 && rowIndex == -1) { + setStatus(""Should not happen""); + } + else if (index == -1) { + String msg = String.format(""Found all %,d values"", nextCnt); + setStatus(msg); + } + else { + rowIndex = index; + nextCnt++; + setStatus(""Found "" + nextCnt + "" of "" + totalCnt); + tPanel.showSearch(rowIndex); // set results from here; CAS579b + } + } + catch (Exception e) {ErrorReport.print(e, ""Performing search""); return;} + } + /************************************************************** + * Find next curVal + */ + private int getRowIndex(int nrows, String findStr) { + int index= -1; + + for (int x=rowIndex+1; x0) ? tok[tok.length-1] : colVal; + } + else { // special processing in case of character at end + modColVal = colVal.substring(colVal.indexOf(""."")+1); // chr.N.{suf} - remove chr + } + if (modColVal.equals(findStr)) { + index=x; + break; + } + } + else { // CAS579c make case-insensitive + colVal = colVal.toLowerCase(); + findStr = findStr.toLowerCase(); + if (isExact) { + if (colVal.equals(findStr)) { + index=x; + break; + } + } + else { // Substring + if (colVal.contains(findStr)) { + index=x; + break; + } + } + } + } + return index; + } + private void setStatus(String msg) { + txtStatus.setText(msg); + } + /****************************************/ + private void popupHelp() { + String msg = """"; + msg += ""Select column to search. Enter search string. Select search type:""; + msg += ""\n Last#: Enter the last number of a '.' or '-' delimited string, e.g. for 10-33, enter '33'."" + + ""\n For Gene#, if the gene has a suffix, it must be in the search string, e.g. '1.a'."" + + ""\n Exact: Enter the exact string. "" + + ""\n Substring: The substring can be anywhere in the column value."" + + ""\n\nNext: If found, the table will redisplay the next row containing the value. "" + + ""\n\nRestart: Will restart the search. "" + + ""\n Changing any value on the panel will also restart the search. ""; + msg += ""\n\nSee ? for details.\n""; + util.Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + private int numCols=0; + private JRadioButton radExact, radLast, radSubstring; + private JTextField txtSearch = null; + private JRadioButton [] radColArr; + private JTextField txtStatus = null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/OverviewPanel.java",".java","6669","167","package symapQuery; + +import java.util.Vector; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JLabel; + +import symap.Globals; +import symap.manager.Mpair; +import symap.manager.Mproject; +import util.Jcomp; + +/****************************************************** + * The Instruction panel on the right side of the query frame + */ +public class OverviewPanel extends JPanel { + private static final long serialVersionUID = 6074102283606563987L; + private Vector projVec; + + protected OverviewPanel(QueryFrame parentFrame) { + qFrame = parentFrame; + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + + buildOverview(qFrame.isSelf); + add(mainPanel); + } + + private void buildOverview(boolean isSelf) { + mainPanel = Jcomp.createPagePanel(); + mainPanel.add(Box.createVerticalStrut(30)); + + // Project table + mainPanel.add(Jcomp.createItalicsBoldLabel(""Selected projects:"", 12)); mainPanel.add(Box.createVerticalStrut(2)); + projVec = qFrame.getProjects(); + + int w=5, cntHasGenes=0; + for (Mproject p : projVec) w = Math.max(w, p.getDisplayName().length()); + String fmt = "" %-"" + w + ""s %-"" + Globals.abbrevLen + ""s %7s %s""; // add Globals.abbrevLen CAS578 + + String headings = String.format(fmt, ""Name"" , ""Abbr"", ""#Genes"", ""Description""); + JLabel lblHead = Jcomp.createItalicsLabel(headings, 12); + mainPanel.add(lblHead); mainPanel.add(Box.createVerticalStrut(2)); + + for (Mproject mp : projVec) { + String gc = String.format(""%,d"", mp.getGeneCnt()); + String line = String.format(fmt, mp.getDisplayName(), mp.getdbAbbrev() , gc, mp.getdbDesc()); + mainPanel.add(Jcomp.createMonoLabel(line, 12)); // font size + mainPanel.add(Box.createVerticalStrut(5)); + + if (mp.getGeneCnt()>0) cntHasGenes++; + } + int w1=20, w2=8; // section, items within section + mainPanel.add(Box.createVerticalStrut(w1)); + + String head = """"; + String tail = """"; + String indent = ""     ""; + head += indent; + + // Notes: either gene or no gene + + mainPanel.add(Jcomp.createItalicsBoldLabel(""Notes:"", 12)); mainPanel.add(Box.createVerticalStrut(5)); + + if (isSelf) { + String self = ""Self-synteny: Project name ending with '"" + Globals.SS_X + + ""' is duplicate project to show homologous hits.""; + mainPanel.add(Jcomp.createLabel(head + self + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + } + if (cntHasGenes>0) { // Algo + if (cntHasGenes==1 && projVec.size()==2) { + String gene = ""Only one of two species has genes. Some filters are not relevant.""; + mainPanel.add(Jcomp.createLabel(head + gene + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + } + String algo = qFrame.isAlgo2() ? ""Algo2:  "" : ""Algo1:  ""; + algo += ""The Olap column is ""; + if (qFrame.isAlgo2() && Globals.bQueryOlap==false) + algo += ""exon overlap; Olap may be 0 if hits only overlap intron.""; + else { + if (Globals.bQueryOlap) algo += ""gene overlap; flag -go was used.""; + else algo += ""gene overlap; at least one project used Algo1 or has no genes.""; + } + mainPanel.add(Jcomp.createLabel(head + algo + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + } + else { + String gene = ""No genes in any species. There are limited filters. Some columns are not relevant.""; + mainPanel.add(Jcomp.createLabel(head + gene + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + } + // Pseudo - can belong to projects w/o genes + int cntPseudo = qFrame.cntUsePseudo; + int cntSynteny = qFrame.cntSynteny; + + String pseudo = ""Pseudo: ""; + String pg = "" numbered pseudo for un-annotated. ""; + if (projVec.size()==2) pseudo += (cntPseudo==1) ? ""Pair has "" + pg : ""Pair does not have "" + pg; + else { + if (cntPseudo>0 && cntPseudo!=cntSynteny) { + if (cntPseudo==1) pseudo += cntPseudo + "" pair of "" + cntSynteny + "" has "" + pg; + else pseudo += cntPseudo + "" pairs of "" + cntSynteny + "" have "" + pg; + pseudo += getNoPseudo(); + } + else if (cntPseudo>0) pseudo += ""All pairs have "" + pg; + else pseudo += ""No pairs have "" + pg; + } + mainPanel.add(Jcomp.createLabel(head + pseudo + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + + // Synteny + if (projVec.size()!=2) { + int nProjSyn = (projVec.size()*(projVec.size()-1))/2; + if (nProjSyn!=cntSynteny) { + String syn = ""Synteny: ""; + if (cntSynteny==1) syn += cntSynteny + "" pair of "" + nProjSyn + "" has synteny""; + else syn += cntSynteny + "" pairs of "" + nProjSyn + "" have synteny""; + syn += getNoSynteny(); + mainPanel.add(Jcomp.createLabel(head + syn + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + } + } + + mainPanel.add(Box.createVerticalStrut(w1)); + + // instructions + mainPanel.add(Jcomp.createItalicsBoldLabel(""Instructions:"", 12)); mainPanel.add(Box.createVerticalStrut(w2)); + + String instruct = ""> Query Setup: click to set filters, followed by search, producing a table of results.""; + mainPanel.add(Jcomp.createLabel(head + instruct + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + + instruct = ""> Results: click to view the list of query results, and to remove results.""; + mainPanel.add(Jcomp.createLabel(head + instruct + tail)); mainPanel.add(Box.createVerticalStrut(w2)); + + instruct = ""The query results are listed under the Results tab, and can be viewed by selecting one.0) { + if (!msg.equals("""")) msg += "", ""; + msg += pair; + cnt++; + } + } + } + return "" ("" + cnt + "": "" + msg + "")""; + } + private String getNoSynteny() { + String msg=""""; + int cnt=0; + for (int i=0; i [] GENERAL_TYPES = + {Integer.class, Integer.class, Integer.class, String.class, String.class, + Integer.class, Integer.class, Integer.class, Integer.class, + Integer.class, String.class, String.class}; + + private static final boolean [] GENERAL_COLUMN_DEF = + {true, true, false, false, false, false, false, false, false, false, false, false}; + + private static final String [] GENERAL_COLUMN_DESC = + {""Row number"", + ""Block: chr.chr.Block#"", + ""Block Hits: Number of hits in the synteny block"", + ""Collinear: chr.chr.#hits.CollinearSet#"", + ""Group: #hits-Group# (#genes- for Cluster N genes)"", // see ComputeMulti, ComputePgeneF, or Gene# + ""Hit#: Number representing the hit"", + + ""Hit Cov: The largest summed merged subhit lengths of the two species"", // Descriptions are in QueryPanel too + ""Hit %Id: Approximate percent identity of subhits"", + ""Hit %Sim: Approximate percent similarity of subhits"", + + ""Hit #Sub: Number of subhits in the cluster, where 1 is a single hit"", + ""Hit St: The strands separated by a '/'"", + ""Algo1: g2, g1, g0; Algo2: E is exon, I is intron, n is neither."" + }; + +/* Prefixed with Species */ +// If change here, change in DBdata.makeRow + private static final String [] SPECIES_COLUMNS = + {Q.gNCol, Q.gOlap, Q.chrCol, + Q.gStartCol, Q.gEndCol, Q.gLenCol, Q.gStrandCol, + Q.hStartCol, Q.hEndCol, Q.hLenCol}; + + private static final Class [] SPECIES_TYPES = + {String.class, Integer.class, String.class, + Integer.class,Integer.class, Integer.class, String.class, + Integer.class, Integer.class, Integer.class}; + + private static final boolean [] SPECIES_COLUMN_DEF = + { true, false, false, false, false , false, false, false, false, false}; + + private static int OLAP_COL=1; // changed based on Algo + private static String [] SPECIES_COLUMN_DESC = { + ""Gene#: Sequential. Overlap genes have same number (chr.#.{a-z})"", + ""Olap: Algo1 percent gene overlap, Algo2 percent exon overlap"", + ""Chr: Chromosome (or Scaffold, etc)"", + ""Gstart: Start coordinate of gene"", + ""Gend: End coordinate of gene"", + ""Glen: Length of gene"", + ""Gst: Gene strand"", + ""Hstart: Start coordinate of clustered hits"", + ""Hend: End coordinate of clustered hits"", + ""Hlen: Hend-Hstart+1"" + }; + + // single columns separate so can add NumHits + private static final String [] SSPECIES_COLUMNS = + { Q.gNCol, Q.gHitNumCol, Q.chrCol, Q.gStartCol, Q.gEndCol, Q.gLenCol, Q.gStrandCol}; + + private static final Class [] SSPECIES_TYPES = + {Integer.class, Integer.class, String.class, Integer.class,Integer.class, Integer.class, String.class}; + + private static final boolean [] SSPECIES_COLUMN_DEF = + { true, false, false, false, false , false, false}; + + private static String [] SSPECIES_COLUMN_DESC = { + ""Gene#: Sequential. Overlap genes have same number (chr.#.{a-z})"", + ""NumHits: Number of hits to the gene in the entire database."", + ""Chr: Chromosome (or Scaffold, etc)"", + ""Gstart: Start coordinate of gene"", + ""Gend: End coordinate of gene"", + ""Glen: Length of gene"", + ""Gst: Gene strand"" + }; + + //**************************************************************************** + //* Static methods + //**************************************************************************** + protected static String [] getGeneralColHead() {return GENERAL_COLUMNS; } + protected static Class [] getGeneralColType(){return GENERAL_TYPES; } + protected static String [] getGeneralColDesc() {return GENERAL_COLUMN_DESC; } + protected static boolean [] getGeneralColDefaults() {return GENERAL_COLUMN_DEF; } + + protected static String [] getSpeciesColHead(boolean s) {if (s) return SSPECIES_COLUMNS; else return SPECIES_COLUMNS;} + protected static Class [] getSpeciesColType(boolean s) {if (s) return SSPECIES_TYPES; else return SPECIES_TYPES;} + protected static String [] getSpeciesColDesc(boolean s) {if (s) return SSPECIES_COLUMN_DESC; else return SPECIES_COLUMN_DESC;} + protected static boolean [] getSpeciesColDefaults(boolean s){if (s) return SSPECIES_COLUMN_DEF; else return SPECIES_COLUMN_DEF;} + + // XXX If change this, change number in Q.java, as they are the numeric index into ResultSet + // Columns loaded from database, do not correspond to query table columns + + protected static int getSpColumnCount(boolean isSingle) { + if (isSingle) return SSPECIES_COLUMNS.length; + else return SPECIES_COLUMNS.length; + } + protected static int getGenColumnCount(boolean isSingle) { + if (isSingle) return 1; // row number only + else return GENERAL_COLUMNS.length; + } + + // MySQL fields to load; this is for pairs; order must be same as Q numbers + protected static TableColumns getFields(boolean isIncludeMinor, boolean isAlgo2) { + TableColumns fd = new TableColumns(); + // type not used, see above sql.table.field order# Descriptions are not used; see COLUMN_DESC + fd.addField(String.class, Q.PA, ""idx"", Q.AIDX, ""Annotation index""); + fd.addField(String.class, Q.PA, ""grp_idx"", Q.AGIDX, ""Annotation chromosome idx""); + fd.addField(String.class, Q.PA, ""start"", Q.ASTART, ""Annotation start""); + fd.addField(String.class, Q.PA, ""end"", Q.AEND, ""Annotation end""); + fd.addField(String.class, Q.PA, ""strand"", Q.ASTRAND, ""Annotation strand""); + fd.addField(String.class, Q.PA, ""name"", Q.ANAME, ""Annotation attributes""); // Split for ""Gene Annotation"" + fd.addField(String.class, Q.PA, ""tag"", Q.AGENE, ""Annotation gene#""); // tag is needed to suffix + fd.addField(String.class, Q.PA, ""numhits"", Q.ANUMHITS, ""Annotation numHits""); // Singles only, ignored for Hits + + fd.addField(Integer.class,Q.PH, ""idx"", Q.HITIDX, ""Hit index""); + fd.addField(Integer.class,Q.PH, ""hitnum"", Q.HITNUM, ""Hit number""); + fd.addField(Integer.class,Q.PH, ""proj1_idx"",Q.PROJ1IDX, ""1st species index""); + fd.addField(Integer.class,Q.PH, ""proj2_idx"",Q.PROJ2IDX, ""2nd species index""); + fd.addField(Integer.class,Q.PH, ""grp1_idx"", Q.GRP1IDX, ""1st chromosome index""); + fd.addField(Integer.class,Q.PH, ""grp2_idx"", Q.GRP2IDX, ""2nd chromosome index""); + fd.addField(Integer.class,Q.PH, ""start1"", Q.HIT1START, ""1st hit start""); + fd.addField(Integer.class,Q.PH, ""start2"", Q.HIT2START, ""2nd hit start""); + fd.addField(Integer.class,Q.PH, ""end1"", Q.HIT1END, ""1st hit end""); + fd.addField(Integer.class,Q.PH, ""end2"", Q.HIT2END, ""2nd hit end""); + fd.addField(String.class, Q.PH, ""pctid"", Q.PID, ""Hit Average %Identity""); + fd.addField(String.class, Q.PH, ""cvgpct"", Q.PSIM, ""Hit Average %Similarity""); + fd.addField(String.class, Q.PH, ""countpct"", Q.HCNT, ""Clustered hits""); + fd.addField(String.class, Q.PH, ""strand"", Q.HST, ""Strand +/-, /-, etc""); + fd.addField(String.class, Q.PH, ""score"", Q.HSCORE, ""Summed clustered hits""); + fd.addField(String.class, Q.PH, ""htype"", Q.HTYPE, ""Type of Exon (E), Intron(I), neither(n)""); + fd.addField(String.class, Q.PH, ""runsize"", Q.COSIZE, ""Collinear run size""); + fd.addField(String.class, Q.PH, ""runnum"", Q.CONUM, ""Collinear number""); + + fd.addField(String.class, Q.B, ""blocknum"", Q.BNUM, ""Block Number""); + fd.addField(String.class, Q.B, ""score"", Q.BSCORE, ""Block Score (#Anchors)""); + + if (isAlgo2 && Globals.bQueryOlap==false) { + fd.addField(Integer.class,Q.PHA, ""exlap"", Q.AOLAP, ""Exon overlap""); + SPECIES_COLUMN_DESC[OLAP_COL] = ""Percent exon overlap""; // CAS578 make specific + } + else { + fd.addField(Integer.class,Q.PHA, ""olap"", Q.AOLAP, ""Gene overlap""); + SPECIES_COLUMN_DESC[OLAP_COL] = ""Percent gene overlap""; + } + fd.addField(Integer.class,Q.PH, ""annot1_idx"",Q.ANNOT1IDX,""Index of 1st anno""); // Not for display + fd.addField(Integer.class,Q.PH, ""annot2_idx"",Q.ANNOT2IDX,""Index of 2nd anno""); // matched with PA.idx in DBdata + + fd.addLeftJoin(""pseudo_hits_annot"", ""PH.idx = PHA.hit_idx"", Q.PHA); + fd.addLeftJoin(""pseudo_annot"", ""PHA.annot_idx = PA.idx"", Q.PA); + fd.addLeftJoin(""pseudo_block_hits"", ""PBH.hit_idx = PH.idx"", Q.PBH); + fd.addLeftJoin(""blocks"", ""B.idx = PBH.block_idx"", Q.B); + + return fd; + } + + //**************************************************************************** + //* Constructors + //**************************************************************************** + + protected TableColumns() { + theFields = new Vector (); + theJoins = new Vector (); + } + + //**************************************************************************** + //* Public methods + //**************************************************************************** + + protected int getNumFields() { return theFields.size(); } + + protected String [] getDBFieldDescriptions() { + if(theFields.size() == 0) return null; + + String [] retVal = new String[getNumFields()]; + Iterator iter = theFields.iterator(); + int x = 0; + FieldItem item = null; + + while(iter.hasNext()) { + item = iter.next(); + retVal[x++] = item.getDescription(); + } + return retVal; + } + // Used in Select getDBFieldList() from .... + protected String getDBFieldList(boolean isOrphan) { + Iterator iter = theFields.iterator(); + FieldItem item = null; + + if (iter.hasNext()) item = iter.next(); // first one + String sqlCols = item.getDBTable() + ""."" + item.getDBFieldName(); + int cnt=1; + + while(iter.hasNext()) { + item = iter.next(); + sqlCols += "", "" + item.getDBTable() + ""."" + item.getDBFieldName(); + + cnt++; + if (isOrphan && cnt>SSPECIES_COLUMNS.length) break; + } + return sqlCols; + } + protected String getJoins() { + Iterator iter = theJoins.iterator(); + String retVal = """"; + while(iter.hasNext()) { + if(retVal.length() == 0) retVal = iter.next().getJoin(); + else retVal += "" "" + iter.next().getJoin(); + } + return retVal; + } + + /**************************************************** + * private + */ + private void addField(Class type, String dbTable, String dbField, int num, String description) { + FieldItem fd = new FieldItem(type, description); + fd.setQuery(dbTable, dbField, num); + theFields.add(fd); + } + private void addLeftJoin(String table, String condition, String strSymbol) { + theJoins.add(new JoinItem(table, condition, strSymbol,true)); + } + + private Vector theFields = null; + private Vector theJoins = null; + + private class JoinItem { + protected JoinItem(String table, String condition, String symbol, boolean left) { + strTable = table; + strCondition = condition; + strSymbol = symbol; + bleft = left; + } + protected String getJoin() { + String retVal = (bleft ? ""\nLEFT JOIN "" : ""\nJOIN "") + strTable; + if(strSymbol.length() > 0) + retVal += "" AS "" + strSymbol; + retVal += "" ON "" + strCondition; + return retVal; + } + + private String strTable = """"; + private String strCondition = """"; + private String strSymbol = """"; + private boolean bleft = false; + } + + private class FieldItem { + protected FieldItem(Class type, String description) { + // cType = type; + strDescription = description; + } + + protected void setQuery(String table, String field, int num) { + strDBTable = table; + strDBField = field; + // dbNum = num; index into rs.get; see Q.java + } + protected String getDBTable() { return strDBTable; } + protected String getDBFieldName() { return strDBField; } + protected String getDescription() { return strDescription; } + + private String strDBTable; //Source table for the value + private String strDBField; //Source field in the named DB table + private String strDescription; //Description of the field + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/AnnoData.java",".java","5582","175","package symapQuery; + +import java.sql.ResultSet; +import java.util.Collections; +import java.util.Iterator; +import java.util.Vector; +import java.util.TreeSet; + +import database.DBconn2; +import symap.manager.Mproject; +import util.ErrorReport; + +/********************************************************** + * Return AnnoData which has a AnnoSp object for each species containing its annotation keywords. + * Used by TableDataPanel + * CAS575 change from looking up species by spIdx to using the position in array; this is for self-synteny which has idx repeated + */ +public class AnnoData { + protected static final String [] key1 = {""ID""}; // GFF should have an ID, if so, put 1st; used by TableData too + protected static final String [] key2 = {""product"", ""desc"", ""Desc"", ""description""}; // GFF NCBI/Ensembl, put 2nd + + protected static AnnoData loadProjAnnoKeywords(QueryFrame qFrame) { + return new AnnoData(qFrame.getProjects(), qFrame.getDBC()); + } + /*****************************************************************/ + private AnnoData(Vector projs, DBconn2 dbc2) { + try { + spAnnoVec = new Vector (); + int pos=0; + + for (Mproject p : projs) { + if (!p.hasGenes()) continue; + + AnnoSp ap = new AnnoSp(p.getDisplayName(), p.getdbAbbrev(), p.getIdx(), pos); + spAnnoVec.add(ap); + + Mproject tProj = new Mproject(); + int annot_kw_mincount=0; + ResultSet rset = dbc2.executeQuery(""select value from proj_props "" + + ""where proj_idx="" + p.getIdx() + "" and name='"" + tProj.getKey(tProj.sANkeyCnt) + ""'""); + + if (rset.next()) { + String val = rset.getString(1); + try {annot_kw_mincount=Integer.parseInt(val); } + catch (Exception e) {} // ok to default to 0 if blank + } + + // use count in query + String query = ""SELECT keyname FROM annot_key "" + + "" WHERE proj_idx = "" + p.getIdx() + "" and count>="" + annot_kw_mincount + + "" ORDER BY keyname ASC""; + + rset = dbc2.executeQuery(query); + while(rset.next()) { + ap.addAnnoKey(rset.getString(1)); + } + ap.addAnnoKey(Q.All_Anno); + rset.close(); + pos++; + } + + Collections.sort(spAnnoVec); + pos=0; + for (AnnoSp sp : spAnnoVec) { + sp.spPos= pos++; + sp.orderKeys(); + } + } + catch(Exception e) {ErrorReport.print(e, ""set project annotations""); } + } + + /* methods called by TableDataPanel */ + protected int getNumberAnnosForSpecies(int pos) { // was speciesID, with lookup; CAS575 + return spAnnoVec.get(pos).getNumAnnoIDs(); + } + + protected String getAnnoIDforSpeciesAt(int pos, int annoPos) { + return spAnnoVec.get(pos).getAnnoAt(annoPos); + } + protected int [] getSpPosList() { // concatenates 0,..n where n is number of species + int [] retVal = new int[spAnnoVec.size()]; + for (int i=0; i getSpeciesAbbrList() {// for TableData.arrangeColumns and UtilSearch + TreeSet retSet = new TreeSet (); + + Iterator iter = spAnnoVec.iterator(); + while(iter.hasNext()) { + retSet.add(iter.next().getAbbrevName()); + } + return retSet; + } + protected String getSpeciesAbbrev(int pos) {// was speciesID, with lookup; CAS575 + return spAnnoVec.get(pos).getAbbrevName(); + } + + //returns list of all Species::keyword; used in DBdata (species) and to create the column headers (abbrev) + protected String [] getColumns(boolean bAbbrev) { + Vector annoKeyList = new Vector (); + + Iterator speciesIter = spAnnoVec.iterator(); + while(speciesIter.hasNext()) { + AnnoSp key = speciesIter.next(); + String species = (bAbbrev) ? key.getAbbrevName() : key.getSpeciesName(); + for(int x=0; x { + private AnnoSp(String speciesName, String abbvName, int speciesID, int pos) { + spKeys = new Vector (); + spName = speciesName; + spAbbrev = abbvName; + spPos = pos; + } + + private void addAnnoKey(String annoID) { + spKeys.add(annoID); + } + + private int getNumAnnoIDs() { return spKeys.size(); } + private String getAnnoAt(int pos) { return spKeys.get(pos); } + private String getSpeciesName() { return spName;} + private String getAbbrevName() { return spAbbrev;} + public int compareTo(AnnoSp arg0) { + return spName.compareTo(arg0.spName); + } + private void orderKeys() { + String [] tmpKeys = new String [spKeys.size()]; + int idx=0; + + String [] keySet; + for (int x=0; x<2; x++) { + keySet = (x==0) ? key1 : key2; + boolean found=false; + for (String desc : keySet) { + for (int i=0; i spKeys = null; + } // end AnnoSp class + + /* AnnoData private variable */ + private Vector spAnnoVec = null; // renamed CAS575 +} // end AnnotData class + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/ResultsPanel.java",".java","5355","183","package symapQuery; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.ListSelectionModel; +import javax.swing.table.AbstractTableModel; +import java.util.Vector; + +import util.Jcomp; + +/********************************************** + * Table of results + */ + +public class ResultsPanel extends JPanel { + private static final long serialVersionUID = -4532933089334778200L; + + protected ResultsPanel(QueryFrame parentFrame) { + qFrame = parentFrame; + setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBackground(Color.WHITE); + + rows = new Vector(); + + theTable = new JTable(); + theTable.getTableHeader().setBackground(Color.WHITE); + theTable.setColumnSelectionAllowed( false ); + theTable.setCellSelectionEnabled( false ); + theTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + theTable.setRowSelectionAllowed( true ); + theTable.setShowHorizontalLines( false ); + theTable.setShowVerticalLines( true ); + theTable.setIntercellSpacing ( new Dimension ( 1, 0 ) ); + + theTable.setModel(new ResultsTableModel()); + + theTable.addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + updateButtons(); + if (e.getClickCount() == 2) { + int row = theTable.getSelectedRow(); + qFrame.selectResult(row); // + } + } + }); + + scroll = new JScrollPane(theTable); + scroll.setBorder( null ); + scroll.setPreferredSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize()); // force table to use all space + scroll.setAlignmentX(Component.LEFT_ALIGNMENT); + scroll.getViewport().setBackground(Color.WHITE); + + add(addButtonPanel()); + add(Box.createVerticalStrut(10)); + add(addLabelPanel()); + add(scroll); + } + + protected void addResultText(String [] summary) { + rows.add(summary); + theTable.revalidate(); + updateButtons(); + } + + private void removeSelectedSummaries(int [] selections) { + for(int x=selections.length-1; x>=0; x--) { + qFrame.removeResult(selections[x]); + rows.remove(selections[x]); + } + theTable.clearSelection(); + theTable.revalidate(); + updateButtons(); + + if (rows.size()==0) qFrame.resetCounter(); + } + + private void removeAllSummaries() { + int numResults = rows.size(); + + for(int x=0; x < numResults; x++) + qFrame.removeResult(0); + rows.clear(); + + theTable.clearSelection(); + theTable.revalidate(); + updateButtons(); + + qFrame.resetCounter(); + } + + private void updateButtons() { + boolean b = (theTable.getSelectedRows().length > 0); + btnRemoveSelQueries.setEnabled(b); + + b = (theTable.getRowCount() > 0); + btnRemoveAllQueries.setEnabled(b); + } + + private JPanel addButtonPanel() { + JPanel thePanel = Jcomp.createRowPanel(); + + btnRemoveSelQueries = Jcomp.createButton(""Remove Selected"", false); + btnRemoveSelQueries.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + removeSelectedSummaries(theTable.getSelectedRows()); + } + }); + btnRemoveAllQueries = Jcomp.createButton(""Remove All"", false); + btnRemoveAllQueries.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + removeAllSummaries(); + } + }); + thePanel.add(btnRemoveSelQueries); thePanel.add(Box.createHorizontalStrut(20)); + thePanel.add(btnRemoveAllQueries); thePanel.add(Box.createHorizontalStrut(20)); + + thePanel.setMaximumSize(thePanel.getPreferredSize()); + thePanel.setAlignmentX(LEFT_ALIGNMENT); + + return thePanel; + } + + private JPanel addLabelPanel() { + JPanel thePanel = Jcomp.createPagePanel(); + + JTextArea instructions = new JTextArea( + ""Select one or more rows, then 'Remove Selected'; this removes the result from the left panel."" + + ""\nDouble click a row to view the result.""); + instructions.setEditable(false); + instructions.setBackground(getBackground()); + instructions.setAlignmentX(LEFT_ALIGNMENT); + + thePanel.add(instructions); + thePanel.setMaximumSize(thePanel.getPreferredSize()); + thePanel.setAlignmentX(LEFT_ALIGNMENT); + thePanel.add(Box.createVerticalStrut(10)); + + return thePanel; + } + + private class ResultsTableModel extends AbstractTableModel { + private static final long serialVersionUID = 774460555629612058L; + + public int getColumnCount() { + return colNames.length; + } + public int getRowCount() { + return rows.size(); + } + public Object getValueAt(int row, int col) { + String [] r = rows.elementAt(row); + return r[col]; + } + public String getColumnName(int col) { + return colNames[col]; + } + } + + private JButton btnRemoveSelQueries = null; + private JButton btnRemoveAllQueries = null; + + private JTable theTable = null; + private JScrollPane scroll = null; + private Vector rows = null; + private String [] colNames = { ""Result"", ""Filters"" }; + + private QueryFrame qFrame = null; +} + +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/QueryFrame.java",".java","13507","401","package symapQuery; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Arrays; +import java.util.Vector; + +import javax.swing.BoxLayout; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; + +import database.DBconn2; +import database.Version; +import props.PersistentProps; +import util.Popup; +import util.Utilities; +import util.ErrorReport; +import symap.closeup.MsaMainPanel; +import symap.manager.ManagerFrame; +import symap.manager.Mpair; +import symap.manager.Mproject; + +/************************************************** + * The main query frame: + * this build static tabs on the left (MenuPanel), runs query and msa, and add their tabs on the left + * updateView responds to a tab being click, and it replaces the right panel with the clicked tab panel + * Called by ManagerFrame + * Calls QueryPanel, which performs database call, sends to DBdata, then TableMainPanel + */ +public class QueryFrame extends JFrame { + private final int MIN_WIDTH = 1000, MIN_HEIGHT = 720; + private final int MIN_DIVIDER_LOC = 200; + + private static final String [] MENU_ITEMS = { ""> Overview"", ""> Query Setup"", ""> Results"" }; + static private String propNameAll = ""SyMapColumns1""; // 0&1's; use if match number of columns in current DB + static private String propNameSingle = ""SyMapColumns2""; + + protected String title=""""; // for Export + /****************************************************** + * ManagerFrame creates this object, add the projects, then calls build. + */ + public QueryFrame(ManagerFrame mFrame, String title, DBconn2 dbc2, Vector mProjVec, + boolean useAlgo2, int cntUsePseudo, int cntSynteny, boolean isSelf) { + setTitle(""Query "" + title); // title has: SyMAP vN.N.N - dbName + + this.mFrame = mFrame; // for getMpair + this.title = title; + this.tdbc2= new DBconn2(""Query-"" + DBconn2.getNumConn(), dbc2); + + mProjs = new Vector (); + for (Mproject p: mProjVec) mProjs.add(p); + + String [] ab = getAbbrevNames(); + for (int i=0; i (); + + qPanel = new QueryPanel(this); + overviewPanel = new OverviewPanel(this); + resultsPanel = new ResultsPanel(this); + + mainPanel.add(overviewPanel); + localQueryPane = new JScrollPane(qPanel); + mainPanel.add(localQueryPane); + mainPanel.add(resultsPanel); + + updateView(); + } + /************************************************ + * Make table and add tab: called from queryPanel on Run Query + */ + protected void makeTabTable(String query, String sum, boolean isSingle) { + boolean [] saveLastColumns = getLastColumns(isSingle); + + String tabName = ""Result "" + (++resultCounter); // DO NOT CHANGE, same as in TableMainPanel.tableFinish + TableMainPanel tablePanel = new TableMainPanel(getInstance(), tabName, + saveLastColumns, query, sum, isSingle); + + menuPanel.addLeftTab(tabName+"":""); + mainPanel.add(tablePanel); + allPanelVec.add(tablePanel); + + updateView(); // shows the table with Stop + } + + /************************************************ + * MSA Align; called from UtilSelect/Table MSA...; + */ + protected void makeTabMSA(TableMainPanel tablePanel, String [] names, String [] seqs, String [] tabLines, + String progress, String tabAdd, String resultSum, String msaSum, + boolean bTrim, boolean bAuto, int cpus) + { + String tabName = ""MSA "" + (++msaCounter) + "":""; + MsaMainPanel msaPanel = new MsaMainPanel(tablePanel, getInstance(), names, seqs, tabLines, + progress, msaSum, tabName, tabAdd, resultSum, bTrim, bAuto, cpus); + + menuPanel.addLeftTab(tabName+"":""); + mainPanel.add(msaPanel); // set Visible when tab clicked + allPanelVec.add(msaPanel); + + updateView(); + } + + // Called from TableMainPanel and closeup.MsaMainPanel to finish + public void updateTabText(String oldTab, String newTab, String [] resultsRow) { + menuPanel.updateLeftTab(oldTab, newTab); + + resultsPanel.addResultText(resultsRow); + } + private QueryFrame getInstance() { return this; } + + /*********************************************** + * Column defaults - Called for makeTable and shutdown + * the ColumnSelection is a boolean vector, with no knowledge of species anno's + * Read/write from PersistentProps cookies + */ + // Only knows selections from FieldData, does not know order + private boolean [] getLastColumns(boolean bSingle) { + try { + boolean [] saveLastColumns = null; + for(int x=allPanelVec.size()-1; x>=0 && saveLastColumns == null; x--) { + if (allPanelVec.get(x) instanceof TableMainPanel) { + if (((TableMainPanel)allPanelVec.get(x)).isSingle()==bSingle) { + saveLastColumns = ((TableMainPanel)allPanelVec.get(x)).getColumnSelections(); // from FieldData + break; + } + } + } + if (saveLastColumns==null) saveLastColumns = makeColumnDefaults(bSingle); + + return saveLastColumns; // if this is null, TableDataPanel will use defaults + } catch (Exception e) {ErrorReport.print(e, ""get last columns""); return null;} + } + // will be called when first table is created; + // If made for a different database, only the General and Species will be set + private boolean [] makeColumnDefaults(boolean bSingle) { + try { + PersistentProps cookies = new PersistentProps(); + String which = (bSingle) ? propNameSingle : propNameAll; + String propSaved = cookies.copy(which).getProp(); + if (propSaved==null || propSaved.length()<5) return null; + + String [] tok = propSaved.split("":""); + if (tok.length!=2) return null; + int nSaveSp = Utilities.getInt(tok[0]); + if (nSaveSp<=1) return null; + + String saveCols = tok[1]; + int nCol = saveCols.length(); + int nGenCol = TableColumns.getGenColumnCount(bSingle); + int nChrCol = TableColumns.getSpColumnCount(bSingle); + if (nCol < (nGenCol+nChrCol)) return null; + if (saveCols.charAt(0)=='0') return null; // indicates a problem if row# not 1 + + int nThisSp=mProjs.size(); + + // same number of species: the anno counts could be wrong, but TableDataPanel.setColumnSelection checks + if (nSaveSp==nThisSp) { + boolean [] bcols = new boolean [nCol]; + + for (int i=0; iallPanelVec.size()) return; // can happen on Stop + + JPanel tPanel = allPanelVec.get(pos); + + mainPanel.remove(tPanel); // remove panel from queryFrame + + allPanelVec.remove(pos); // remove panel from list of panels + + menuPanel.removeResult(pos); // remove from left panel + + updateView(); + } + public void removeResult(JPanel rmPanel) { // closeup.MsaMainPanel Stop; + for (int pos=0; pos getProjects() {return mProjs;} + protected boolean isAlgo2() {return bUseAlgo2;}; + protected boolean isSelf() {return isSelf;} + + protected Mpair getMpair(int idx1, int idx2) { + return mFrame.getMpair(idx1, idx2); + } + protected boolean isOneHasAnno() { // CAS579b + int cnt=0; + for (Mproject mp : mProjs) { + if (mp.hasGenes()) cnt++; + } + return (cnt==1); + } + protected boolean isAllNoAnno() { // CAS579b + int cnt=0; + for (Mproject mp : mProjs) { + if (mp.hasGenes()) cnt++; + } + return (cnt==0); + } + /**********************************************************/ + private DBconn2 tdbc2 = null; + private ManagerFrame mFrame; + private QueryPanel qPanel = null; + + private Vector mProjs = null; + protected boolean bUseAlgo2=false; + protected boolean isSelf=false; + protected int cntUsePseudo=0, cntSynteny=0; // for Overview + + private int screenWidth, screenHeight; + private JSplitPane splitPane = null; + private JPanel mainPanel = null; + private MenuPanel menuPanel = null; + private OverviewPanel overviewPanel = null; + + private JScrollPane localQueryPane = null; + private ResultsPanel resultsPanel = null; + + private Vector allPanelVec = null; + + private int resultCounter = 0; + private int msaCounter = 0; + private static final long serialVersionUID = 9349836385271744L; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/SummaryPanel.java",".java","8746","244","package symapQuery; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Vector; + +import javax.swing.Box; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Utilities; + +/************************************************** + * * The summary at the bottom of the results table. + * Compute the summary in one place (except regions) + * Called from TableMainPanel.buildTable + */ + +public class SummaryPanel extends JPanel { + private static final long serialVersionUID = 1L; + private JPanel statsPanel=null; + + private Vector rowsFromDB; + private QueryPanel qPanel; + private SpeciesPanel spPanel; + private HashMap projGrpMap; + private HashMap geneCntMap; // computed in DBdata.makeGeneCounts + + private boolean isSelf=false; + + public SummaryPanel(Vector rowsFromDB, QueryPanel qPanel, // rows have been merged + HashMap projMap, // PgeneN and Multi summary + HashMap geneCntMap) { // spIdx annotidx counts + + if (statsPanel == null) statsPanel = Jcomp.createPagePanel(); + if(rowsFromDB==null || rowsFromDB.size()==0) return; + + this.rowsFromDB = rowsFromDB; + this.qPanel = qPanel; + this.projGrpMap = projMap; + this.geneCntMap = geneCntMap; + isSelf = qPanel.isSelf(); + spPanel = qPanel.getSpeciesPanel(); + + computeStats(); + } + protected JPanel getPanel() {return statsPanel;} + + /**************************************************** + * Compute Stats - fills in the rest of panel + */ + private void computeStats() { + + HashMap chrStrMap = new HashMap(); + HashSet gidxSet = new HashSet (); + + // Create Chr: x of x + for (DBdata dd : rowsFromDB) { + if (!gidxSet.contains(dd.getChrIdx(0))) gidxSet.add(dd.getChrIdx(0)); + if (!gidxSet.contains(dd.getChrIdx(1))) gidxSet.add(dd.getChrIdx(1)); + } + + Vector order = new Vector (); // needed so stats are in order + + for (int p = 0; p < spPanel.getNumSpecies(); p++) { // Chromosome stats; used if not Group + String projName = spPanel.getSpName(p); + if (!isSelf || p==0) order.add(spPanel.getSpIdx(p)); + else order.add(order.get(0)+1); // +1 Used in DBdata.makeGeneCnts and below + + String [] gidxList = spPanel.getChrIdxList(p); + HashSet spGidx = new HashSet (); + for (String c : gidxList) + spGidx.add(Integer.parseInt(c)); + + int nchrs = gidxList.length; + int xchr = 0; + for (int idx : gidxSet) + if (spGidx.contains(idx)) xchr++; + + String chrStr = String.format(""%2d of %2d"", xchr, nchrs); + chrStrMap.put(projName, chrStr); + } + gidxSet.clear(); + + if (qPanel.isSingle()) createSingle(chrStrMap); + else createPairHits(chrStrMap, order); + } + /***************************************************** + * Has Gene: Either %d Both %d None %d Has Block: Yes %d No %d + * + * Sp1 Hits: %d Annotated: %d Chr: %d Regions: %d + * + * Works for isSelf because SpeciesPanel uses spIdx+1 for 2nd project + */ + private void createPairHits(HashMap chrStrMap, // project name, N chr of M + Vector order) { + try { + int either=0, both=0, none=0, block=0, collinear=0, maxGrp=0, minor=0; + HashMap proj2hits = new HashMap (); + HashMap proj2annot = new HashMap (); + HashMap blockCnt = new HashMap (); + HashMap collinearCnt = new HashMap (); + + for (DBdata dd : rowsFromDB) { + int spIdx1 = dd.getSpIdx(0); + int spIdx2 = (isSelf) ? spIdx1+1 : dd.getSpIdx(1); + + counterInc(proj2hits, spIdx1, 1); + counterInc(proj2hits, spIdx2, 1); + + boolean anno1 = dd.hasGene(0); + boolean anno2 = dd.hasGene(1); + if (anno1) counterInc(proj2annot, spIdx1, 1); + if (anno2) counterInc(proj2annot, spIdx2, 1); + + if (anno1 && anno2) both++; + else if (!anno1 && !anno2) none++; + else either++; + + if (dd.geneTag[0].endsWith(Q.minor)) minor++; + if (dd.geneTag[1].endsWith(Q.minor)) minor++; + + if (dd.hasBlock()) { + block++; + counterInc(blockCnt, dd.blockStr, 1); + } + if (dd.hasCollinear()) { + collinear++; + counterInc(collinearCnt, dd.collinearStr, 1); + } + if (dd.hasGroup()) { + String [] tok = dd.grpStr.split(Q.GROUP); + int n = Utilities.getInt(tok[tok.length-1]); + if (n>maxGrp) maxGrp=n; + } + } + // Add 1st line of summary + String label = String.format(""Block (Hits): %,d (%,d) Annotated: Both %,d One %,d None %,d"", + blockCnt.size(), block, both, either, none); + if (minor>0) label += String.format("" Minor %,d"", minor); // only >0 if Every+ or Gene# + if (maxGrp>0) label += String.format("" Groups: #%,d"", maxGrp); // runs off page if not before collinear, which then runs off page.. + if (collinear>0) label += String.format("" Collinear (Hits): %,d (%,d)"", collinearCnt.size(), collinear); + + JLabel theLabel = Jcomp.createMonoLabel(label, 12); + statsPanel.add(theLabel); + statsPanel.add(Box.createVerticalStrut(5)); + + // 2nd lines with Project gene counts + // format: + int w=5, h=0, a=0, g=0, x=0; // find width + for (int spIdx : order) { + String pName; + if (!isSelf) pName = spPanel.getSpNameFromSpIdx(spIdx); + else pName = spPanel.getSelfName(x++); + + w = Math.max(w, pName.length()); + + if (order.size()>2) {// hits is all the same unless more than 2 species + int nHit = proj2hits.containsKey(spIdx) ? proj2hits.get(spIdx) : 0; + h = Math.max(h, String.format(""%,d"", nHit).length()); + } + int nAnno = proj2annot.containsKey(spIdx) ? proj2annot.get(spIdx) : 0; + a = Math.max(a, String.format(""%,d"", nAnno).length()); + + int nUnq = geneCntMap.containsKey(spIdx) ? geneCntMap.get(spIdx) : 0; + g = Math.max(g, String.format(""%,d"", nUnq).length()); + + // CAS579c format wrong; if (isSelf) break; + } + String nf; + if (h==0) nf = ""%-"" + w + ""s Annotated: %,"" + a + ""d Genes: %,"" + g + ""d""; + else nf = ""%-"" + w + ""s Hits: %,"" + h + ""d Annotated: %,"" + a + ""d Genes: %,"" + g + ""d""; + + // Loop through species + x=0; + for (int spIdx : order ) { + String pName; + if (!isSelf) pName = spPanel.getSpNameFromSpIdx(spIdx); + else pName = spPanel.getSelfName(x++); + + int nHit = proj2hits.containsKey(spIdx) ? proj2hits.get(spIdx) : 0; + int nAnno = proj2annot.containsKey(spIdx) ? proj2annot.get(spIdx) : 0; + int nUnq = geneCntMap.containsKey(spIdx) ? geneCntMap.get(spIdx) : 0; // isSelf will have spIdx + + if (h==0) label = String.format(nf, pName, nAnno, nUnq); + else label = String.format(nf, pName, nHit, nAnno, nUnq); + + String chrStr = chrStrMap.containsKey(pName) ? chrStrMap.get(pName) : ""Unk""; + if (projGrpMap.containsKey(pName)) label += "" "" + projGrpMap.get(pName); // Multi&PgeneF has project stats + else label += "" Chr: "" + chrStr; // else, Chr n of m + + theLabel = Jcomp.createMonoLabel(label, 12); + + statsPanel.add(Box.createVerticalStrut(2)); + statsPanel.add(theLabel); + } + } + catch (Exception e) {ErrorReport.print(e, ""Create hit summary"");} + } + private void createSingle(HashMap chrStrMap) { // CAS579c simplify + try { + String dname="""", chrStr=""""; + for (String x : chrStrMap.keySet()) { + if (!x.endsWith(Globals.SS_X)) { + dname = x; + chrStr = chrStrMap.get(x); + break; + } + } + if (dname.equals("""")) {// probably ends with SS_Z + for (String x : chrStrMap.keySet()) { + dname = x; + chrStr = chrStrMap.get(x); + break; + } + } + int cnt=rowsFromDB.size(); + + String type = (qPanel.isSingleOrphan()) ? ""Orphans"" : ""Genes""; + String label = String.format(""%-13s %s: %,d Chr: %s"",dname, type, cnt, chrStr); + JLabel theLabel = Jcomp.createMonoLabel(label, 12); + + statsPanel.add(Box.createVerticalStrut(4)); + statsPanel.add(theLabel); + } + catch (Exception e) {ErrorReport.print(e, ""Create orphan summary"");} + } + + + private void counterInc(HashMap ctr, Integer key, int inc) { + if (inc == 0) return; + if (!ctr.containsKey(key)) ctr.put(key, inc); + else ctr.put(key, ctr.get(key)+inc); + } + private void counterInc(HashMap ctr, String key, int inc){ + if (inc == 0) return; + if (!ctr.containsKey(key)) ctr.put(key, inc); + else ctr.put(key, ctr.get(key)+inc); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","java/src/symapQuery/UtilReportNR.java",".java","34787","980","package symapQuery; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.TreeMap; +import java.util.ArrayList; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JTextField; + +import symap.Globals; +import util.ErrorReport; +import util.Jcomp; +import util.Jhtml; +import util.Popup; + +/*********************************************** + * Gene Report when there is no reference; + * most of this (e.g. anno) is duplicated from UtilReport; its easier then zillions of if-then-else + * There is no TSV file + */ +public class UtilReportNR extends JDialog { + private static final long serialVersionUID = 1L; + private final int defTxtWidth=40, padWithSpace=10; + private static String filePrefix = ""Report""; + private int cntFullLink=0; + + private static final String keyC = "","", // input key parameter for anno + semiC = "";"", // fixed delimiter for anno output + keyVal = ""="", // between keyword and value + tup = "":"", // char between tuple tags + keyDot = ""."", // create hash key + isGrp=""#"", // Group number + nLink=""(""; // opening parenthesis for cluster link count + private static final String noAnno=""---"", + htmlSp="" "", + htmlBr=""
""; + + // Okay: From input menu: the setting are used as the defaults + // Object is reused - so reset anything not wanted from last time + private boolean bPopHtml=true, bExHtml=false; + private int descWidth=40; + private boolean hasKey=false; + private boolean bTruncate=false, + bShowGene=false, + bLinkRow=false, + bShowBorder=true, + bShowGrp=true; + + private PrintWriter outFH = null; + private String title=""""; + + // Anno Keys: + private int nSpecies=0; // createSpecies + private HashMap spIdxPosMap = new HashMap (); // idx, pos + private HashMap spPosIdxMap = new HashMap (); // pos, idx + private String [] spInputKey; // okay + // buildCompute puts genes in map; buildXannoMap() add annotation + private HashMap spAnnoMap = new HashMap (); + + // build and output + private ArrayList clustArr = new ArrayList (); + + /***************************************************************************/ + protected UtilReportNR(TableMainPanel tdp) { // this is called 1st time for Query + this.tPanel = tdp; + spPanel = tdp.qPanel.spPanel; + + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + title = ""SyMAP Cluster Report""; + setTitle(title); + + mainPanel = Jcomp.createPagePanel(); + createSpecies(); + createDisplay(); + createOutput(); + + pack(); + + setModal(true); // nothing else can happen until ok,cancel + toFront(); + setResizable(false); + setLocationRelativeTo(null); + } + + // Reference and keywords + private void createSpecies() { + JPanel optPanel = Jcomp.createPagePanel(); + + qPanel = tPanel.qPanel; + nSpecies = qPanel.nSpecies; + + radSpecies = new JLabel [nSpecies]; + txtSpKey = new JTextField [nSpecies]; + + int width = 100; + JPanel row = Jcomp.createRowPanel(); + JLabel label = Jcomp.createLabel(""Species""); + row.add(label); + if (Jcomp.isWidth(width, label)) row.add(Box.createHorizontalStrut(Jcomp.getWidth(width, label))); + + row.add(Jcomp.createLabel(""Gene Annotation Columns"", + ""Enter comma-delimited list of keywords from All_Anno column for one or more species."")); + optPanel.add(row); + + int rwidth=width; + for(int x=0; x2 species being displayed."" + + ""\n Hover over option for more detail.""; + msg += ""\n\nSee ? for details.\n""; + + Popup.displayInfoMonoSpace(this, ""Quick Help"", msg, false); + } + /**************************************************************8 + * Shared + */ + private void doReport() { + /*-------- Settings ---------*/ + spInputKey = new String [nSpecies]; // List of input keywords per species + for (int i=0; i grpMap = new HashMap (); + HashSet gnTagSet = new HashSet (); + System.gc(); + + for (int row=0; row nAnnoMap = spAnnoMap.get(pos0).nAnnoMap; + nAnnoMap.put(rd.geneTag[0], """"+rd.nRow); // nRow will be replaced with Anno from nRow + } + } + + int pos1 = spIdxPosMap.get(rd.spIdx[1]); + String key1 = rd.groupN + keyDot + pos1 + keyDot + rd.geneTag[1]; + if (!gnTagSet.contains(key1)) { + gnTagSet.add(key1); + if (hasKey && !spInputKey[pos1].isEmpty()) { // All geneVec get put in nAnnoMap + HashMap nAnnoMap = spAnnoMap.get(pos1).nAnnoMap; + nAnnoMap.put(rd.geneTag[1], """"+rd.nRow); // nRow will be replaced with Anno from nRow + } + } + grpObj.add(pos0, rd.geneTag[0], pos1, rd.geneTag[1]); + } + if (clustArr.size()==0) return; + + Globals.rprt(""Sort results""); + Collections.sort(clustArr, new Comparator () { + public int compare(Clust a, Clust b) { + return a.rGrpN - b.rGrpN; + } + }); + if (hasKey) { + Globals.rprt(""Add annotations""); + buildXannoMap(); // Annotations from 1st loop + } + + Globals.rprt(""Finish""); + System.gc(); + int cnt=0; + if (!bLinkRow) { + for (Clust grp : clustArr) { + if (++cnt % Q.INC == 0) Globals.rprt(""Finish "" + cnt); + grp.finish(); + } + } + else { + for (Clust grp : clustArr) { + if (++cnt % Q.INC == 0) Globals.rprt(""Finish link "" + cnt); + new Links(grp); + } + } + Globals.rclear(); + } + catch (Exception e) {ErrorReport.print(e, ""Creating cluster report""); } + catch (OutOfMemoryError e) {ErrorReport.print(e, ""Out of memory creating cluster report"");} + } + + + /****************************************************** + * Intialized in Okay; genes added in buildCompute; add anno here + * Get All_Anno key/values; uses spAnnoMap; puts HTML
between keyword values + */ + private boolean buildXannoMap() { + try { + TmpRowData rd = new TmpRowData(tPanel); + + String notFoundKey=""""; + for (int nSp=0; nSp nAnnoMap = spAnnoMap.get(nSp).nAnnoMap; + + HashMap keyCntMap = new HashMap (); // lookup; cnt to make sure all are found + String [] set = spInputKey[nSp].split(keyC); + for (int i=0; i=descWidth) v = v.substring(0, descWidth-3)+""...""; + + String wval; + if (v.isEmpty() || v.equals(Q.empty)) wval = Q.dash; + else if (v.length()>=descWidth) wval = Jhtml.wrapLine(v, descWidth, htmlBr+htmlSp); + else wval = v; + + if (!allVal.equals("""")) allVal += "" mrows = new ArrayList (); // merged links; + private HashMap tupleMap; // tag:tag, true - can add, false - been added (still used for lookup) + + private Links(Clust grp) { + this.grp = grp; + tupleMap = grp.tupleMap; // created in Clust.add + + merge(); + finish(); + } + + /***********************************************/ + private void merge() { + try { + for (int spR=0; spR spTagSetR = grp.spTagMap.get(spR); // process tags in sorted tree order + + for (String tagR : spTagSetR.keySet()) { + boolean found=true; // a tag can be in multiple linked rows + while (found) { + String [] rowTags = new String [nSpecies]; + for (int i=0; i spTagSetP = grp.spTagMap.get(spP); + for (String tagP : spTagSetP.keySet()) { + String tuple = (spR0) ? isLinked(rowTags, spR, spP, tagP) : true; + if (!bPass) continue; + + rowTags[spP] = tagP; + tupleMap.put(tuple, false); + cntAdd++; + + break; + } + } + if (cntAdd==1) return false; // nothing added + if (cntAdd==nSpecies) {cntFullLink++; grp.cntFull++; return true;} // all column with tag + + /* For each empty column, is there an untouched linked tag that can be added? */ + for (int spE=0; spE spTagSet = grp.spTagMap.get(spE); // check tags for this column + for (String tagE : spTagSet.keySet()) { + if (isLinked(rowTags, spE, tagE)) { + cntAdd++; + rowTags[spE] = tagE; + break; + } + } + } + if (cntAdd==nSpecies) {cntFullLink++; grp.cntFull++;} + return true; + } + catch (Exception e) {ErrorReport.print(e, ""Merge linked rows""); return false;} + } + /* is tagP with all other tags in row excluding ref? */ + private boolean isLinked(String [] rowTags, int spR, int spP, String tagP) { + HashSet rmTup = new HashSet (); // do not set removed until tuple gets added + + for (int sp=0; sp rmTup = new HashSet (); + + for (int sp=0; sp tagArr = new ArrayList (); // one per species + + for (int r=0; r> spTagMap; // pos, merged unique tags; pos=species column, entries no row based + private ArrayList > spTagArr; // pos, not unique tags; pos=species column, entry for each row + private HashMap tupleMap; // tag:tag, true - can add, false - been added (still need for lookup) + private int cntFull=0; + + private Clust(int grpN, int grpSz) { + rGrpN = grpN; + rGrpSz = grpSz; + spTagMap = new ArrayList > (nSpecies); + for (int i=0; i ()); + + spTagArr = new ArrayList > (nSpecies); // do not initialize; see finish + + if (bLinkRow) { + try { + tupleMap = new HashMap (grpSz); + } + catch (OutOfMemoryError e) { + String msg = ""Out of memory: cannot run Gene Links with this Cluster results"" + + ""\nGroup too big: Group "" + grpN + "" size "" + grpSz + + ""\nIncrease memory or use Sorted Order""; + Globals.eprt(msg); + Popup.showWarningMessage(msg); + bLinkRow=false; + } + } + } + private void add(int pos0, String tag0, int pos1, String tag1) { + if (!spTagMap.get(pos0).containsKey(tag0)) spTagMap.get(pos0).put(tag0, 1); + else { + TreeMap map = spTagMap.get(pos0); + map.put(tag0, map.get(tag0)+1); + } + if (!spTagMap.get(pos1).containsKey(tag1)) spTagMap.get(pos1).put(tag1, 1); + else { + TreeMap map = spTagMap.get(pos1); + map.put(tag1, map.get(tag1)+1); + } + + if (bLinkRow) { + String tuple = (pos0 tagMap = spTagMap.get(sp); + + ArrayList tagArr = new ArrayList (tagMap.size()); + for (String tag : tagMap.keySet()) {// Zoutput.addAnnoCols splits on ""("" for tag lookup + String xtag = String.format(""%s %s%d)"", tag, nLink, tagMap.get(tag)); // don't pad; nLink=""("" + tagArr.add(xtag); + } + spTagArr.add(tagArr); + } + } + // Newly created by Links + private void finish(ArrayList tagArr) {// enter in species position order + spTagArr.add(tagArr); + } + + } // end group class + + // one per species where nAnnoMap contains gene values of keyword + private class Anno { + private HashMap nAnnoMap = new HashMap (); // gene#, value + } + /*********************************************************************** + * XXX Output Is a class to consolidate its methods + */ + private class Zoutput { + int gnNum=0; + + StringBuffer hBodyStr= new StringBuffer(); + + private void runReport() { + String report = reportHTML(); + if (report==null) return; + + if (bPopHtml) { + util.Jhtml.showHtmlPanel(null, title, report); + } + else { + outFH = getFileHandle(); + if (outFH==null) return; + + outFH.println(report); + outFH.close(); + } + } + + /*********************************************************** + * build HTML for popup and file; uses geneVec and spAnnoMap + */ + private String reportHTML() { + try { + // column headings + String hColStr=""""; + int colSpan=0; + + hColStr += """"; // no row column + for (int x=0; x
"" + name + ""
""; // Exclude CAS579c + else hColStr += ""
"" + name + ""
""; + } + for (int x=0; x
"" + name + "" "" + spInputKey[x].trim() + ""
""; + colSpan++; + } + } + hColStr += ""\n""; + + // Table + while (true) { // loop through geneVec; while loop because the counts are different for Coset and Gene + if (gnNum>=clustArr.size()) break; + + Clust grpObj = clustArr.get(gnNum++); + if (gnNum%100 == 0) Globals.rprt(""Processed "" + gnNum + "" groups""); + + if (!bShowBorder) hBodyStr.append(""
""); + if (bShowGrp) { + String x = (grpObj.cntFull>0 && nSpecies>2) ? String.format("" (%d asr)"", grpObj.cntFull) : """"; + String setsz = String.format(""%s%s %s"", isGrp, (grpObj.rGrpSz + Q.GROUP + grpObj.rGrpN), x); + hBodyStr.append("""" + setsz); + } + /* Output row of columns for current gnObj */ + hBodyStr.append(""""); // no row number + + for (int posSp=0; posSp tagArr = grpObj.spTagArr.get(posSp); + + if (tagArr.size()==0) { // no gene for this species + hBodyStr.append(""\n "" + htmlSp + """"); + } + else { // one or more genes in non-ref column + hBodyStr.append(""\n ""); + + int j=0; + for (String tag : tagArr) { // all tags in this column;   has been used for blank + if (j>0) hBodyStr.append(htmlBr); + hBodyStr.append(tag); + j++; + } + } + } // end species loop to write gene# columns for this row + if (hasKey) addAnnoCols(grpObj); + hBodyStr.append(""\n""); + } // End loop geneVec + + clearDS(); Globals.rclear(); + + // Finish + String head = strHeadHTML(); // title, filters, stats, table start + String tail= strTailHTML(); + + if (gnNum==0) { // this may happen, as all included must be in a cluster + if (!bPopHtml) { + String msg = ""No reference genes fit the Display options\n"" + strTitle("""", ""\n"", gnNum); + JOptionPane.showMessageDialog(null, msg, ""No results"", JOptionPane.WARNING_MESSAGE); + return null; + } + return head + ""No reference genes fit the Display options"" + tail; + } + return head + hColStr + hBodyStr.toString() + tail; // for file or popup + } + catch (Exception e) {ErrorReport.print(e, ""Build HTML""); return null;} + } + private String strHeadHTML() { + String head = ""\n\n"" + + """" + title + ""\n"" + ""\n\n\n"" + ""\n""; + + head += ""
"" + strTitle("""", htmlBr, gnNum) + """"; //
in tail + + head += String.format(""%s%s%,d Clusters"", htmlBr, htmlBr, gnNum); + String note = (bLinkRow && cntFullLink>0 && nSpecies>2) ? + String.format(""; %,d All species rows (asr)"", cntFullLink) : """"; + head += note; + + head += ""\n""; + + return head; + } + private String strTailHTML() { + String tail=""
""; + if ((gnNum>100) && bExHtml) tail += ""

Go to top\n""; + tail += ""\n""; + + return tail; + } + /*********************************************************** + * Columns of the user input keyword=value + * already has
between a species keyword values, e.g. ID
Desc + */ + private void addAnnoCols(Clust gnObj) { + try { + HashSet tagsAdd = new HashSet (); + for (int nSp=0; nSp tagSet = gnObj.spTagArr.get(nSp); // print in same order as species column + + if (tagSet.size()==0) { // no genes + if (bExHtml) hBodyStr.append(""\n "" + htmlSp); // nl make file manually editable + else hBodyStr.append("""" + htmlSp); + continue; + } + HashMap nAnnoMap = spAnnoMap.get(nSp).nAnnoMap; + String anno=""""; + + for (String tag : tagSet) { + if (tag.equals("""") || tag.startsWith(htmlSp)) continue; // blank lines in Link rows as place holders + if (tagsAdd.contains(tag)) continue; // lots of dups with Link Row + tagsAdd.add(tag); + + String maptag = (!tag.contains(nLink)) ? tag + : tag.substring(0, tag.indexOf("" "")).trim(); // (n) was added in Clust.finish + String showtag = """"; + if (bShowGene) { + String sp=""""; + for (int i=0; i"" + anno); + else hBodyStr.append(""\n "" + anno); + } // end species loop to write annotation columns for this row + } + catch (Exception e) {ErrorReport.print(e, ""Build Anno Columns"");} + } + /************************************************************** + * First lines: title in HTML and remarks in TSV + */ + private String strTitle(String remark, String br, int gnNum) { // br is ""\n"" if showing error, else it is
+ String head = remark + title ; + br = br + remark; + + String sum = tPanel.theSummary; + if (sum.length()>40 && !sum.startsWith(""Cluster"")) { + int index = sum.indexOf(""Cluster""); + String part1 = sum.substring(0,index).trim(); + if (part1.endsWith("";"")) + part1 = part1.substring(0, part1.length()-1); + String part2 = sum.substring(index); + sum = part1 + br + "" "" + part2; + } + head += br + ""Query: "" + sum; + String x = (bLinkRow) ? ""Link rows"" : ""Unlinked unique""; + x = br + ""Display: "" + x; + + return head + x; + } + + /* getFileHandle */ + private PrintWriter getFileHandle() { + String saveDir = Globals.getExport(); + + String type; + type = ""Clust""; + + String name = filePrefix + type; + String fname = (bExHtml) ? name + "".html"" : name + "".tsv""; + + JFileChooser chooser = new JFileChooser(saveDir); + chooser.setSelectedFile(new File(fname)); + if(chooser.showSaveDialog(tPanel.qFrame) != JFileChooser.APPROVE_OPTION) return null; + if(chooser.getSelectedFile() == null) return null; + + String saveFileName = chooser.getSelectedFile().getAbsolutePath(); + if (!saveFileName.endsWith("".html"")) saveFileName += "".html""; + + if (new File(saveFileName).exists()) { + if (!Popup.showConfirm2(""File exists"",""File '"" + saveFileName + ""' exists.\nOverwrite?"")) return null; + } + PrintWriter out=null; + try { + out = new PrintWriter(new FileOutputStream(saveFileName, false)); + } + catch (Exception e) {ErrorReport.print(e, ""Cannot open file - "" + saveFileName);} + + return out; + } + } + /*********************************************************************/ + // Interface + private TableMainPanel tPanel; + private QueryPanel qPanel; + private SpeciesPanel spPanel; + private JPanel mainPanel; + + private JLabel [] radSpecies=null; + private JTextField [] txtSpKey=null; + + private JTextField txtDesc = null; + private JCheckBox chkTrunc = null, chkShowGene = null; + + private JRadioButton radOrder, radLink; + private JCheckBox chkBorder = null, chkShowNum = null; + + private JRadioButton btnPop = null; + private JButton btnOK=null, btnCancel=null, btnClear=null, btnInfo=null; +} +","Java" +"Nucleic acids","csoderlund/SyMAP","scripts/ConvertNCBI.java",".java","38006","1038"," +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.zip.GZIPInputStream; +import java.util.TreeMap; +import java.util.HashMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/************************************************************* + * ConvertNCBI: NCBI genome files formatted for SyMAP + * See https://csoderlund.github.io/SyMAP/input/ncbi.html + * + * Called from xToSymap, but can be used stand-alone. + * + * Written by CAS 16/Jan/18; made part of toSymap and other changes for CAS557; CAS558 rewrote and simplified + * This assumes input of the project directory, which has either + * 1. The ncbi_dataset.zip unzipped, .e.g + * /data/seq/Arab/ncbi_dataset/data/GCF_000001735.4 + * or the .fna and .gff files directly under the project directory + * + * Note: I am no expert on NCBI GFF format, so I cannot guarantee this is 100% correct mapping for all input. + * Your sequences/annotations may have other variations. + * Hence, you may want to edit this to customize it for your needs -- its simply written so easy to modify. + * See https://csoderlund.github.io/SyMAP/input/ncbi.html#edit + * + * From NCBI book and confirm by https://ftp.ncbi.nlm.nih.gov/refseq/release/release-notes/RefSeq-release225.txt + * AC_ Genomic Complete genomic molecule, usually alternate assembly (or linkage) + * NC_ Genomic Complete genomic molecule, usually reference assembly (or linkage) - use sequence unless Prefix only disqualifies + * NG_ Genomic Incomplete genomic region + * NT_ Genomic Contig or scaffold, clone-based or WGS - use sequence if scaffold + * NW_ Genomic Contig or scaffold, primarily WGS - use sequence if scaffold + * NZ_ Genomic Complete genomes and unfinished WGS data + * + Gene attributes written: ID=geneID; Name=(if not contained in geneID); + rnaID= first mRNA ID (cnt of number of mRNAs) + desc=gene description or 1st mRNA product + protein-ID=1st CDS for 1st mRNA + */ + +public class ConvertNCBI { + static private boolean isToSymap=true; + static private int defGapLen=30000; + + private final String header = ""### Written by SyMAP ConvertNCBI""; // Split expects this to be 1st line + private String logFileName = ""/xConvertNCBI.log""; + private final String plus =""+"", star=""*""; + + //output - the projDir gets appended to the front + private String seqDir = ""sequence""; // Default sequence directory for symap + private String annoDir = ""annotation""; // Default annotation directory for symap + private final String outFaFile = ""/genomic.fna""; // Split expects this name + private final String outGffFile = ""/anno.gff""; // Split expects this name + private final String outGapFile = ""/gap.gff""; + + // downloaded via NCBI Dataset link + private final String ncbi_dataset=""ncbi_dataset""; + private final String ncbi_data= ""/data""; + private final String faSuffix = "".fna""; + private final String gffSuffix = "".gff""; + private String subDir=null; + + // args (can be set from command line) + private boolean INCLUDESCAF = false; + private boolean INCLUDEMtPt = false; + private boolean MASKED = false; + private boolean ATTRPROT = false; + private boolean VERBOSE = false; + + // args (if running standalone, change in main) + private int gapMinLen; // Print to gap.gff if #N's is greater than this + private String prefixOnly=null; // e.g. NC + + // Changed for specific input; if unknown and prefixOnly, no suffix + private String chrPrefix=""Chr"", chrPrefix2=""C"", chrType=""chromosome""; // These are checked in Split + private String scafPrefix=""s"", scafType=""scaffold""; // single letter is used because the ""Chr"" is usually removed to save space + private String unkPrefix=""Unk"", unkType=""unknown""; + + private int traceNum=5; // if verbose, change to 20 + private final int traceScafMaxLen=10000; // All scaffold are printed to fasta file, but only summarized if >scafMax + private final int traceNumGenes=3; // Only print sequence if at least this many genes + + // types + private final String geneType = ""gene""; + private final String mrnaType = ""mRNA""; + private final String exonType = ""exon""; + private final String cdsType = ""CDS""; + + // attribute keywords + private final String idAttrKey = ""ID""; + private final String nameAttrKey = ""Name""; + private final String biotypeAttrKey = ""gene_biotype""; + private final String biotypeAttr = ""protein_coding""; + private final String parentAttrKey = ""Parent""; + private final String productAttrKey = ""product""; + private final String descAttrKey = ""description""; + private final String exonGeneAttrKey = ""gene""; + private final String cdsProteinAttrKey = ""protein_id""; + + private final String PROTEINID = ""proteinID=""; // CAS558 new keywords for gene attributes + private final String MRNAID = ""rnaID=""; // ditto + private final String DESC = ""desc=""; // ditto + private final String RMGENE = ""gene-""; + private final String RMRNA = ""rna-""; + + // input + private String projDir = null; + private String inFaFile = null; + private String inGffFile = null; + + // Other global variables + private TreeMap chr2id = new TreeMap (); + private TreeMap id2chr = new TreeMap (); + private TreeMap id2scaf = new TreeMap (); + private TreeMap cntChrGene = new TreeMap (); + private TreeMap cntScafGene = new TreeMap (); + + // Summary + private TreeMap allTypeCnt = new TreeMap (); + private TreeMap allGeneBiotypeCnt = new TreeMap (); + private TreeMap allGeneSrcCnt = new TreeMap (); + private int cntChrGeneAll=0, cntScafGeneAll=0, cntGeneNotOnSeq=0, cntScafSmall=0; + + private int nChr=0, nScaf=0, nMt=0, nUnk=0, nGap=0; // for numbering output seqid and totals + private int cntChr=0, cntScaf=0, cntMtPt=0, cntUnk=0, cntOutSeq=0, cntNoOutSeq=0; + private long chrLen=0, scafLen=0, mtptLen=0, unkLen=0, totalLen=0; + + private PrintWriter fhOut, ghOut; + private PrintWriter logFile=null; + + private int cntMask=0; + private TreeMap cntBase = new TreeMap (); + private HashMap hexMap = new HashMap (); + + + private boolean bSuccess=true; + private final int PRT = 10000; + + public static void main(String[] args) { + isToSymap=false; + new ConvertNCBI(args, defGapLen, null); + } + protected ConvertNCBI(String [] args, int gapLen, String prefix) { // CAS557 make accessible from ConvertFrame + if (args.length==0) { // command line + checkArgs(args); + return; + } + gapMinLen = gapLen; + prefixOnly = prefix; + + projDir = args[0]; + prt(""\n------ ConvertNCBI "" + projDir + "" ------""); + if (!checkInitFiles() || !bSuccess) return; + + //hexMap.put(""%09"", "" ""); // tab - break on this + hexMap.put(""%3D"", ""-""); // = but cannot have these in attr, so use dash + hexMap.put(""%0A"", "" ""); // newline + hexMap.put(""%25"", ""%""); // % + hexMap.put(""%2C"", "",""); // , + hexMap.put(""%3B"", "",""); // ; but cannot have these in attr, so use comma + hexMap.put(""%26"", ""&""); // & + + createLog(args); if (!bSuccess) return; + checkArgs(args); if (!bSuccess) return; + + rwFasta(); if (!bSuccess) return; + + rwAnno(); if (!bSuccess) return; + + printSummary(); + + prt(""""); + printSuggestions(); + prt(""------ Finish ConvertNCBI "" + projDir + "" ------""); + if (logFile!=null) logFile.close(); + } + private void printSuggestions() { + boolean isChr = true; + if (chr2id.size()>0) { + for (String c : chr2id.keySet()) { + if (!c.startsWith(chrPrefix)) { + isChr=false; + break; + } + } + if (isChr && !INCLUDESCAF) prt(""Suggestion: Set SyMAP project parameter 'Group prefix' to 'Chr'.""); + } + + if (cntOutSeq==0) prt(""Are these NCBI files? Should scaffolds be included? Should 'Prefix only' be set?""); + else + if (cntOutSeq>30) prt( ""Suggestion: There are "" + String.format(""%,d"",cntOutSeq) + "" sequences. "" + + ""Set SyMAP project parameter 'Minimum length' to reduce number loaded.""); + } + + /*************************************************************************** + * * Fasta file example: + * >NC_016131.2 Brachypodium distachyon strain Bd21 chromosome 1, Brachypodium_distachyon_v2.0, whole genome shotgun sequence + * >NW_014576703.1 Brachypodium distachyon strain Bd21 unplaced genomic scaffold, Brachypodium_distachyon_v2.0 super_11, whole genome shotgun sequence * + * NOTE: NCBI files are soft-masked, which is used to compute the gaps. + * If its then hard-masked (soft->N's), gaps and hard-masked appear the same + */ + private void rwFasta() { + try { + fhOut = new PrintWriter(new FileOutputStream(seqDir + outFaFile, false)); + fhOut.println(header); + ghOut = new PrintWriter(new FileOutputStream(annoDir + outGapFile, false)); + ghOut.println(header); + + char [] base = {'A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'}; + for (char b : base) cntBase.put(b, 0); + + // Process file + rwFasta(inFaFile); if (!bSuccess) return; + + fhOut.close(); ghOut.close(); + + // 1st part of summary + String xx = (VERBOSE) ? ""("" + star + "")"" : """"; + prt(String.format(""Sequences not output: %,d %s"", cntNoOutSeq, xx)); + prt(""Finish writing "" + seqDir + outFaFile + "" ""); + + prt(""""); + prt( String.format(""A %,11d a %,11d"", cntBase.get('A'), cntBase.get('a')) ); + prt( String.format(""T %,11d t %,11d"", cntBase.get('T'), cntBase.get('t')) ); + prt( String.format(""C %,11d c %,11d"", cntBase.get('C'), cntBase.get('c')) ); + prt( String.format(""G %,11d g %,11d"", cntBase.get('G'), cntBase.get('g')) ); + prt( String.format(""N %,11d n %,11d"", cntBase.get('N'), cntBase.get('n') )); + String other=""""; // CAS513 + for (char b : cntBase.keySet()) { + boolean found = false; + for (char x : base) if (x==b) {found=true; break;} + if (!found) other += String.format(""%c %,d "", b, cntBase.get(b)); + } + if (other!="""") prt(other); + cntBase.clear(); + prt(String.format(""Total %,d"", totalLen)); + + if (MASKED) prt(String.format(""Hard masked: %,d lower case changed to N"", cntMask)); + + prt(""""); + prt(String.format(""Gaps >= %,d: %,d"", gapMinLen, nGap)); + prt(""Finish writing "" + annoDir + outGapFile + "" ""); + } + catch (Exception e) {e.printStackTrace(); die(""rwFasta"");} + } + /******************************************************** + * >NC_010460.4 Sus scrofa isolate TJ Tabasco breed Duroc chromosome 18, Sscrofa11.1, whole genome shotgun sequence + * >NC_010461.5 Sus scrofa isolate TJ Tabasco breed Duroc chromosome X, Sscrofa11.1, whole genome shotgun sequence + * >NW_018084777.1 Sus scrofa isolate TJ Tabasco breed Duroc chromosome Y unlocalized genomic scaffold, + */ + private void rwFasta(String fastaFile) { + try { + prt(""\nProcessing "" + fastaFile); + BufferedReader fhIn = openGZIP(fastaFile); if (!bSuccess) return; + + String line=""""; + int len=0, lineN=0; + + String idcol1="""", prtName="""", seqType=""""; + boolean bPrt=false, isChr=false, isScaf=false, isMT=false; + boolean bMt=false, bPt=false; + int baseLoc=0, gapStart=0, gapCnt=1; + + while ((line = fhIn.readLine()) != null) { + lineN++; + if (line.startsWith(""!"") || line.startsWith(""#"") || line.trim().equals("""")) continue; + + if (line.startsWith("">"")) { // id line + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMT, len, idcol1, prtName); + len=0; + } + String line1 = line.substring(1).trim(); + String [] tok = line1.split(""\\s+""); + if (tok.length==0) { + die(""Header line is blank: line #"" + lineN); + return; + } + idcol1 = tok[0]; + + isChr=isScaf=isMT=false; // CAS557 start check prefix (was only checking for contains) + + if (idcol1.startsWith(""NC_"")) isChr=true; + else if (idcol1.startsWith(""NW_"") || idcol1.startsWith(""NT_"") ) isScaf=true; + + if (isChr) { + if (line.contains(""mitochondrion"") || line.contains(""mitochondrial"") + || line.contains(""plastid"") || line.contains(""chloroplast"")) isMT=true; // Mt/Pt, etc are NC_, but not 'chromosome' + } + if (isChr) cntChr++; + else if (isScaf) cntScaf++; + else if (isMT) cntMtPt++; + else cntUnk++; + + if (prefixOnly!=null) { // CAS557 new parameter + if (!idcol1.startsWith(prefixOnly)) { + cntNoOutSeq++; + continue; + } + } + + gapStart=1; gapCnt=0; baseLoc=0; + bPrt=false; + if (isChr && !isMT) { + nChr++; + seqType=chrType; + prtName = createChrPrtName(line); + id2chr.put(idcol1, prtName); + chr2id.put(prtName, idcol1); + cntChrGene.put(idcol1, 0); + + bPrt=true; + } + else if (isMT && INCLUDEMtPt) { + nChr++; + if (line.contains(""mitochondrion"") || line.contains(""mitochondrial"")) { + prtName= chrPrefix + ""Mt""; + if (!bMt) {bMt=true; nMt++;} + else { + cntNoOutSeq++; + if (VERBOSE) prt(""Ignore Mt: "" + line); + continue; + } + } + else { + prtName = chrPrefix + ""Pt""; + if (!bPt) {bPt=true; nMt++;} + else { + cntNoOutSeq++; + if (VERBOSE) prt(""Ignore Mt: "" + line); + continue; + } + } + id2chr.put(idcol1, prtName); + chr2id.put(prtName, idcol1); + cntChrGene.put(idcol1, 0); + + seqType=chrType; + bPrt=true; + } + else if (isScaf && INCLUDESCAF) { + nScaf++; + prtName = scafPrefix + padNum(nScaf+""""); + id2scaf.put(idcol1, prtName); + cntScafGene.put(idcol1, 0); + + seqType=scafType; + bPrt=true; + } + else { + if (isScaf) {prtName=scafPrefix;} + else if (isMT) {prtName=""Mt/Pt"";} + else {prtName=unkPrefix;} + + if (prefixOnly!=null) {// use chr, don't know what it is + nUnk++; + prtName = unkPrefix + padNum(nUnk+""""); + id2chr.put(idcol1, prtName); + cntChrGene.put(idcol1, 0); + seqType=unkType; + bPrt=true; + } + } + if (bPrt) { + fhOut.println("">"" + prtName + "" "" + idcol1 + "" "" + seqType); + cntOutSeq++; + } + else cntNoOutSeq++; + } // finish header line + ////////////////////////////////////////////////////////////////////// + else { // sequence line + String aline = line.trim(); + if (bPrt) { + char [] bases = aline.toCharArray(); + + //eval for gaps, mask and count bases + for (int i =0 ; i0) { // gaps + if (gapCnt>gapMinLen) { + nGap++; + String x = createGap(prtName, gapStart, gapCnt); + ghOut.println(x); + } + gapStart=0; gapCnt=1; + } + if (MASKED) { + if (b=='a' || b=='c' || b=='t' || b=='g' || b=='n') { + bases[i]='N'; + cntMask++; + } + } + } + if (MASKED) aline = new String(bases); + } + + len += aline.length(); + if (bPrt) fhOut.println(aline); + } // finish seq line + } + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMT, len, idcol1, prtName); + } + System.err.print("" \r""); + fhIn.close(); + } + catch (Exception e) {die(e, ""rwFasta: "" + fastaFile);} + } + // >NC_015438.3 Solanum lycopersicum cultivar Heinz 1706 chromosome 12, SL3.0, whole genome""; + // >NC_003279.8 Caenorhabditis elegans chromosome III + // >NC_003070.9 Arabidopsis thaliana chromosome X sequence + // >NC_027748.1 Brassica oleracea TO1000 chromosome C1, BOL, whole genome shotgun sequence + private String createChrPrtName(String line) { + try { + String name=null; + String [] words = line.split(""\\s+""); // CAS557 this gets them all I think... + for (int i=0; i1000000) System.out.print(msg2 + ""\r""); + } + else { + unkLen += len; + if (bPrt || VERBOSE) { + if (cntUnk<=traceNum) prt(msg); + else if (cntUnk==traceNum+1) prt(""Suppressing further unknown logs""); + else System.out.print(msg2 + ""\r""); + } + else if (len>1000000) System.out.print(msg2 + ""\r""); + } + } + /*************************************************************************** + * XXX GFF file example: + * NC_016131.2 Gnomon gene 18481 21742 . + . ID=gene3;Dbxref=GeneID:100827252;Name=LOC100827252;gbkey=Gene;gene=LOC100827252;gene_biotype=protein_coding + NC_016131.2 Gnomon mRNA 18481 21742 . + . ID=rna2;Parent=gene3;Dbxref=GeneID:100827252,Genbank:XM_003563157.3;Name=XM_003563157.3;gbkey=mRNA;gene=LOC100827252;model_evidence=Supporting evidence includes similarity to: 3 Proteins%2C and 78%25 coverage of the annotated genomic feature by RNAseq alignments;product=angio-associated migratory cell protein-like;transcript_id=XM_003563157.3 + NC_016131.2 Gnomon exon 18481 18628 . + . ID=id15;Parent=rna2;Dbxref=GeneID:100827252,Genbank:XM_003563157.3;gbkey=mRNA;gene=LOC100827252;product=angio-associated migratory cell protein-like;transcript_id=XM_003563157.3 + */ + // anno per gene + private String geneID="""",geneLine="""", gchr="""", gproteinAt="""", gmrnaAt="""", gproductAt=""""; + private String mrnaLine="""", mrnaID=""""; + private Vector exonVec = new Vector (); + private int cntUseGene=0, cntUseMRNA=0, cntUseExon=0, cntThisGeneMRNA=0; + + private void rwAnno() { + try { + if (inGffFile==null) return; + prt(""""); + prt(""Processing "" + inGffFile); + + int cntReadGene=0, cntReadMRNA=0, cntReadExon=0; + BufferedReader fhIn = openGZIP(inGffFile); if (!bSuccess) return; + PrintWriter fhOutGff = new PrintWriter(new FileOutputStream(annoDir + outGffFile, false)); + fhOutGff.println(header); + + String line=""""; + int skipLine=0; + + while ((line = fhIn.readLine()) != null) { + line = line.trim(); + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().length()==0) continue; + + String [] tok = line.split(""\\t""); + if (tok.length!=9) { + skipLine++; + if (skipLine<10) prt(""Bad line: "" + line); + else die(""too many errors""); + continue; + } + + // Count everything here for summary + String type = tok[2].trim(); // gene, mRNA, exon... + if (!allTypeCnt.containsKey(type)) allTypeCnt.put(type,1); + else allTypeCnt.put(type, allTypeCnt.get(type)+1); + + if (type.equals(geneType)) { + rwAnnoOut(fhOutGff); + rwAnnoGene(tok, line); + cntReadGene++; cntThisGeneMRNA++; + if (cntReadGene%PRT==0) System.err.print("" Process "" + cntReadGene + "" genes...\r""); + } + else if (type.equals(mrnaType)) { + rwAnnoMRNA(tok, line); + cntReadMRNA++; + } + else if (type.equals(cdsType)) { + rwAnnoCDS(tok, line); + } + else if (type.equals(exonType)) { + rwAnnoExon(tok, line); + cntReadExon++; + } + } + fhIn.close(); fhOutGff.close(); + prt(String.format("" Use Gene %,d from %,d "", cntUseGene, cntReadGene)); + prt(String.format("" Use mRNA %,d from %,d "", cntUseMRNA, cntReadMRNA)); + prt(String.format("" Use Exon %,d from %,d "", cntUseExon, cntReadExon)); + prt(""Finish writing "" + annoDir + outGffFile + "" ""); + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + + private void rwAnnoGene(String [] tok, String line) { + try { + // counts for gene + String [] typeAttrs = tok[8].trim().split("";""); + String biotype = getVal(biotypeAttrKey, typeAttrs); + if (!allGeneBiotypeCnt.containsKey(biotype)) allGeneBiotypeCnt.put(biotype,1); + else allGeneBiotypeCnt.put(biotype, allGeneBiotypeCnt.get(biotype)+1); + + String src = tok[1].trim(); // RefSeq, Gnomon.. + if (src.contains(""%2C"")) src = src.replace(""%2C"", "",""); + + if (!allGeneSrcCnt.containsKey(src)) allGeneSrcCnt.put(src,1); + else allGeneSrcCnt.put(src, allGeneSrcCnt.get(src)+1); + + if (!biotype.equals(biotypeAttr)) return; // protein-coding + + String idcol1 = tok[0]; // chromosome, scaffold, linkage group... + if (id2chr.containsKey(idcol1)) { + cntChrGeneAll++; + gchr = id2chr.get(idcol1); + cntChrGene.put(idcol1, cntChrGene.get(idcol1)+1); + } + else if (id2scaf.containsKey(idcol1)) { + cntScafGeneAll++; + gchr = id2scaf.get(idcol1); + cntScafGene.put(idcol1, cntScafGene.get(idcol1)+1); + } + else { + cntGeneNotOnSeq++; + return; + } + //////////// + geneID = getVal(idAttrKey, typeAttrs); + geneLine = line; + cntUseGene++; + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + // mRNA is not loaded into SyMAP, but needed for exon parentID + private void rwAnnoMRNA(String [] tok, String line) { + try { + if (!mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + if (!geneID.equals(pid)) return; + + //////////////////////// + mrnaID = getVal(idAttrKey, attrs); + + String mid = mrnaID.replace(RMRNA,""""); + gmrnaAt = MRNAID + mid; + gproductAt = DESC + getVal(productAttrKey, attrs); + + String idStr = idAttrKey + ""="" + mrnaID.replace(RMRNA,""""); + String parStr = parentAttrKey + ""="" + geneID.replace(RMGENE,""""); + String newAttrs = idStr + "";"" + parStr + "";"" + gproductAt; + mrnaLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + + tok[4] + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + + cntUseMRNA++; + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + private void rwAnnoCDS(String [] tok, String line) { + try { + if (!ATTRPROT || mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (mrnaID.equals(pid)) { + gproteinAt = "";"" + PROTEINID + getVal(cdsProteinAttrKey, attrs); + } + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + /** Write genes and exons to file**/ + private void rwAnnoExon(String [] tok, String line) { + try { + if (mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (!mrnaID.equals(pid)) return; + + ////////////// + String idStr = idAttrKey + ""="" + getVal(idAttrKey, attrs); // create shortened attribute list + String parStr = parentAttrKey + ""="" + mrnaID.replace(RMRNA,""""); + String geneStr = exonGeneAttrKey + ""="" + getVal(exonGeneAttrKey, attrs); + String newAttrs = idStr + "";"" + parStr + "";"" + geneStr; + String nLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + exonVec.add(nLine); + cntUseExon++; + } + catch (Exception e) {die(e, ""rwAnnoExon"");} + } + private void rwAnnoOut( PrintWriter fhOutGff) { + try { + if (geneID.trim().equals("""")) return; + if (mrnaID.trim().equals("""")) return; + + String [] tok = geneLine.split(""\\t""); + if (tok.length!=9) die(""Gene: "" + tok.length + "" "" + geneLine); + + if (geneID.startsWith(RMGENE)) geneID = geneID.replace(RMGENE,""""); // CAS558 remove gene- + String idAt = idAttrKey + ""="" + geneID + "";""; + + String [] attrs = tok[8].split("";""); + String val = getVal(nameAttrKey, attrs); + String nameAt = (!geneID.contains(val)) ? (nameAttrKey + ""="" + val + "";"") : """"; // CHANGE here to alter what attributes are saved + + String desc = getVal(descAttrKey, attrs).trim(); + if (!desc.equals("""")) gproductAt = DESC + desc; + else gproductAt=""""; + + gmrnaAt += "" ("" + cntThisGeneMRNA + "");""; + + String allAttrs = idAt + nameAt + gmrnaAt + gproductAt + gproteinAt; + + String line = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + allAttrs; + + if (line.contains(""%"")) { + for (String hex : hexMap.keySet()) { + if (line.contains(hex)) line = line.replace(hex, hexMap.get(hex)); + } + } + fhOutGff.println(""###\n"" + line); + + fhOutGff.println(mrnaLine); + + for (String eline : exonVec) fhOutGff.println(eline); + + cntThisGeneMRNA=0; + geneID=geneLine=gchr=gproteinAt=gmrnaAt=gproductAt=mrnaID=mrnaLine=""""; + exonVec.clear(); + } + catch (Exception e) {die(e, ""rwAnnoOut"");} + } + + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return x[1]; + } + return """"; + } + + /***********************************************************************/ + private void printSummary() { + prt("" ""); + if (VERBOSE) { + prt("">>Sequence ""); + if (cntChr>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntChr, nChr, ""Chromosomes"", chrLen)); + } + if (cntMtPt>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntMtPt, nMt, ""Mt/Pt"", mtptLen)); + } + if (cntScaf>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d (%,d < %,dbp)"", + cntScaf,nScaf, ""Scaffolds"", scafLen, cntScafSmall, traceScafMaxLen)); + } + if (cntUnk>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntUnk, nUnk, ""Unknown"", unkLen)); + } + + if (inGffFile==null) return; + + ////////////////// anno //////////////// + prt("" ""); + + prt("">>All Types (col 3) ("" + plus + "" are processed keywords)""); + for (String key : allTypeCnt.keySet()) { + boolean bKey = ATTRPROT && key.equals(cdsType); + String x = (key.equals(geneType) || key.equals(mrnaType) || key.equals(exonType)) || bKey ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allTypeCnt.get(key), x)); + } + + prt("">>All Gene Source (col 2)""); + for (String key :allGeneSrcCnt.keySet()) { + prt(String.format("" %-22s %,8d"", key, allGeneSrcCnt.get(key))); + } + prt("">>All gene_biotype= (col 8) ""); + for (String key : allGeneBiotypeCnt.keySet()) { + String x = (key.equals(biotypeAttr)) ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allGeneBiotypeCnt.get(key), x)); + } + } + prt(String.format("">>Chromosome gene count %,d "", cntChrGeneAll)); + for (String prt : chr2id.keySet()) { + String id = chr2id.get(prt); + prt(String.format("" %-10s %-20s %,8d"", prt, id, cntChrGene.get(id))); + } + if (INCLUDESCAF) { + int cntOne=0; + prt(String.format("">>Scaffold gene count %,d (list scaffolds with #genes>%d) "", cntScafGeneAll, traceNumGenes)); + for (String id : cntScafGene.keySet()) { + if (cntScafGene.get(id)>traceNumGenes) + prt(String.format("" %-10s %-20s %,8d"", id2scaf.get(id), id, cntScafGene.get(id))); + else cntOne++; + } + prt(String.format("" Scaffolds with <=%d gene (not listed) %,8d"", traceNumGenes, cntOne)); + prt(String.format("" Genes not included %,8d"", cntGeneNotOnSeq)); + } + else prt(String.format("" %s %,8d"", ""Genes not on Chromosome"", cntGeneNotOnSeq)); + } + + /************************************************************************** + * Find .fna and .gff in top project directory or in projDir/ncbi_dataset/data/

+ */ + private boolean checkInitFiles() { + try { + if (projDir==null || projDir.trim().equals("""")) { + die(""No project directory""); + return false; + } + File[] files; + String dsDirName=null; + + File dir = new File(projDir); + if (!dir.isDirectory()) + return die(projDir + "" is not a directory.""); + + // for check projDir/ncbi_dataset/data/ + files = dir.listFiles(); + boolean isDS=false; + for (File f : files) { + if (f.isDirectory()) { + if (f.getName().contentEquals(ncbi_dataset)) { + isDS = true; + break; + } + } + } + if (isDS) { + if (!projDir.endsWith(""/"")) projDir += ""/""; + dsDirName = projDir + ncbi_dataset + ncbi_data; + + dir = new File(dsDirName); + if (!dir.isDirectory()) + return die(""ncbi_dataset directory is incorrect "" + dsDirName); + + files = dir.listFiles(); + for (File f : files) { + if (f.isDirectory()) { + subDir = f.getName(); + break; + } + } + if (subDir==null) return die(dsDirName + "" missing sub-directory""); + + dsDirName += ""/"" + subDir; + } + else { + dsDirName = projDir; + } + + // find .fna and .gff files in dsDirName + File dsDir = new File(dsDirName); + if (!dsDir.isDirectory()) + return die(dsDir + "" is not a directory.""); + + files = dsDir.listFiles(); + for (File f : files) { + if (!f.isFile() || f.isHidden()) continue; + + String fname = f.getName(); + + if (fname.endsWith(faSuffix + "".gz"") || fname.endsWith(faSuffix)) { + if (inFaFile!=null) { + prt(""Multiple fasta files - using "" + inFaFile); + break; + } + inFaFile = dsDirName + ""/"" + fname; + } + else if (fname.endsWith(gffSuffix + "".gz"") || fname.endsWith(gffSuffix)) { + if (inGffFile!=null) { + prt(""Multiple fasta files - using "" + inFaFile); + break; + } + inGffFile= dsDirName + ""/"" +fname; + } + } + + if (inFaFile == null) return die(""Project directory "" + projDir + "": no file ending with "" + faSuffix + "" or ""+ faSuffix + "".gz (i.e. Ensembl files)""); + if (inGffFile == null) prt(""Project directory "" + projDir + "": no file ending with "" + gffSuffix + "" or "" + gffSuffix + "".gz""); + + // Create sequence and annotation directories + if (!projDir.endsWith(""/"")) projDir += ""/""; + seqDir = projDir + seqDir; + checkDir(true, seqDir); if (!bSuccess) return false; + + annoDir = projDir + annoDir; + checkDir(false, annoDir); if (!bSuccess) return false; + + return true; + } + catch (Exception e) { return die(e, ""Checking "" + projDir); } + } + /*****************************************************************/ + private void createLog(String [] args) { + if (args.length==0) return; + logFileName = args[0] + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {die(""Cannot open "" + logFileName); logFile=null;} + } + private boolean checkDir(boolean isSeq, String dir) { + File nDir = new File(dir); + if (nDir.exists()) { + String x = (isSeq) ? "" .fna and .fa "" : "" .gff and .gff3""; + prt(dir + "" exists - remove existing "" + x + "" files""); + deleteFilesInDir(isSeq, nDir); + return true; + } + else { + if (!nDir.mkdir()) + return die(""*** Failed to create directory '"" + nDir.getAbsolutePath() + ""'.""); + } + return true; + } + private void deleteFilesInDir(boolean isSeq, File dir) { + if (!dir.isDirectory()) return; + + String[] files = dir.list(); + + if (files==null) return; + + for (String fn : files) { + if (isSeq) { + if (fn.endsWith("".fna"") || fn.endsWith("".fa"")) { + new File(dir, fn).delete(); + } + } + else { + if (fn.endsWith("".gff"") || fn.endsWith("".gff3"")) { + new File(dir, fn).delete(); + } + } + } + } + private BufferedReader openGZIP(String file) { + try { + if (!file.endsWith("".gz"")) { + File f = new File (file); + if (f.exists()) return new BufferedReader ( new FileReader (f)); + else die(""Cannot open file "" + file); + } + else if (file.endsWith("".gz"")) { + FileInputStream fin = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fin); + InputStreamReader xover = new InputStreamReader(gzis); + return new BufferedReader(xover); + } + else die(""Do not recognize file suffix: "" + file); + } + catch (Exception e) {die(e, ""Cannot open file "" + file);} + return null; + } + /*******************************************************/ + private void checkArgs(String [] args) { + if (args.length==0 || args[0].equals(""-h"") || args[0].equals(""-help"") || args[0].equals(""help"")) { // for stand alone + prt(""\nConvertNCBI [options] ""); + prt("" the project directory must contain the FASTA file and the GFF is optional: "" + + ""\n FASTA file ending with .fna or .fna.gz"" + + ""\n GFF file ending with .gff or .gff.gz"" + + ""\n Alternatively, the directory can contain the ncbi_dataset directory."" + + ""\nOptions:"" + + ""\n-m assuming a soft-masked genome file, convert it to hard-masked."" + + ""\n-s include any sequence with NT_ or NW_ prefix'."" + + ""\n-t include Mt and Pt chromosomes."" + + ""\n-p include the protein name (1st CDS) in the attribute field."" + + ""\n-v write extra information."" + + ""\n\nSee https://csoderlund.github.io/SyMAP/input for details.""); + System.exit(0); + } + + if (args.length>1) { + for (int i=1; i< args.length; i++) + if (args[i].equals(""-s"")) { + INCLUDESCAF=true; + chrPrefix = chrPrefix2; + } + else if (args[i].equals(""-t"")) INCLUDEMtPt=true; + else if (args[i].equals(""-v"")) VERBOSE=true; + else if (args[i].equals(""-m"")) MASKED=true; + else if (args[i].equals(""-p"")) ATTRPROT=true; + } + prt(""Parameters:""); + prt("" Project directory: "" + projDir); + + if (gapMinLen!=defGapLen) prt("" Gap minimum size: "" + gapMinLen); // set in main + if (prefixOnly!=null) prt("" Prefix Only: "" + prefixOnly); // set in main + + if (INCLUDESCAF) { + prt("" Include scaffold sequences ('NT_' or 'NW_' prefix)""); + prt("" Uses prefixes Chr '"" + chrPrefix2 + ""' and Scaffold '"" + scafPrefix + ""'""); + } + if (INCLUDEMtPt) prt("" Include Mt and Pt chromosomes""); + if (MASKED) prt("" Hard mask sequence""); + if (ATTRPROT) prt("" Include protein-id in attributes""); + if (VERBOSE) {traceNum=20; prt("" Verbose"");} + } + private boolean die(Exception e, String msg) { + System.err.println(""Fatal error -- "" + msg); + e.printStackTrace(); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private boolean die(String msg) { + System.err.println(""Fatal error -- "" + msg); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","csoderlund/SyMAP","scripts/ConvertEnsembl.java",".java","33107","944"," +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.TreeMap; +import java.util.Vector; +import java.util.zip.GZIPInputStream; + +/************************************************************* + * ConvertEnsembl: Ensembl genome files formatted for SyMAP + * See https://csoderlund.github.io/SyMAP/input/ensembl.html + * + * Called from toSymap, but can be used stand-alone. + * + * Written by CAS Oct2019; made part of toSymap and other changes for CAS557; altered in CAS558 + * This assumes input of, e.g: + * 1. ftp://ftp.ensemblgenomes.org/pub/plants/release-45/fasta//dna/.dna_sm.toplevel.fa.gz + * Note: either hard-masked (rm) where repeats are replaced with Ns, or soft-masked (sm) where repeats are in lower-case text. + * 2. ftp://ftp.ensemblgenomes.org/pub/plants/release-45/gff3//.chr.gff3.gz + * + * Note: I am no expert on Ensembl GFF format, so I cannot guarantee this is 100% correct mapping for all input. + * Your sequences/annotations may have other variations. + * Hence, you may want to edit this to customize it for your needs -- its simply written so easy to modify. + * See https://csoderlund.github.io/SyMAP/input/ensembl.html#edit + */ + +public class ConvertEnsembl { + static private boolean isToSymap=true; // set to false in main if standalone + static private int defGapLen=30000; + + private final String header = ""### Written by SyMAP ConvertEnsembl""; // Split expects this to be 1st line + private String logFileName = ""/xConvertENS.log""; + private final String star = ""*"", plus=""+""; + private final String source = ""[Source""; // remove this from description + + private final int PRT = 10000; + private final int scafMaxLen=10000; // counted if less than this + private int traceNum=5; // if verbose, change to 20 + private final int traceNumGenes=3; // Only print sequence if at least this many genes + + //input - project directory + private final String faSuffix = "".fa""; + private final String gffSuffix = "".gff3""; + + //output - the projDir gets appended to the front + private String seqDir = ""sequence""; // Default sequence directory for symap + private String annoDir = ""annotation""; // Default sequence directory for symap + + private final String outFaFile = ""/genomic.fna""; // Split expects this name + private final String outGffFile = ""/anno.gff""; // Split expects this name + private final String outGapFile = ""/gap.gff""; + + // args (can be set from command line) + private boolean VERBOSE = false; + private boolean INCLUDESCAF = false; + private boolean INCLUDEMtPt = false; + private boolean ATTRPROT = false; + + // args (if running standalone, change in main) + private int gapMinLen=defGapLen; // Print to gap.gff if #N's is greater than this + private String prefixOnly=null; // e.g. NC + private boolean bNumOnly=false; // Only number, X, Y or roman numeral + + private String chrPrefix=""Chr"", chrPrefix2=""C"", chrType=""chromosome""; // these values are checked in Split + private String scafPrefix=""s"", scafType=""scaffold""; + private String unkPrefix=""Unk"", unkType=""unknown""; + + // types + private final String geneType = ""gene""; + private final String mrnaType = ""mRNA""; + private final String exonType = ""exon""; + private final String cdsType = ""CDS""; + + // attribute keywords + private final String idAttrKey = ""ID""; // Gene and mRNA + private final String nameAttrKey = ""Name""; // All + private final String descAttrKey = ""description""; // Gene + private final String biotypeAttrKey = ""biotype""; // Gene + private final String biotypeAttr = ""protein_coding""; // Gene + private final String parentAttrKey = ""Parent""; // mRNA and Exon + private final String cdsProteinAttrKey = ""protein_id""; + + private final String PROTEINID = ""proteinID=""; // CAS558 new keywords for gene attributes + private final String MRNAID = ""rnaID=""; // ditto + private final String DESC = ""desc=""; // ditto + private final String RMGENE = ""gene:""; + private final String RMTRAN = ""transcript:""; + + // input + private String projDir = null; // command line input + // Ensembl allows individual chromosomes to be downloaded, hence, the vector + private Vector inFaFileVec = new Vector (); // must be in projDir, end with fastaSuffix + private Vector inGffFileVec = new Vector (); // must be in projDir, end with annoSuffix + + // All chromosome and scaffold names are mapped to ChrN and ScafN + private TreeMap cntChrGene = new TreeMap (); + private TreeMap cntScafGene = new TreeMap (); + private TreeMap id2scaf = new TreeMap (); + private TreeMap id2chr = new TreeMap (); + private TreeMap chr2id = new TreeMap (); + + private TreeMap allTypeCnt = new TreeMap (); + private TreeMap allGeneBiotypeCnt = new TreeMap (); + private TreeMap allGeneSrcCnt = new TreeMap (); + + + private int cntChrGeneAll=0, cntScafGeneAll=0, cntOutSeq=0, cntNoOutSeq=0, cntScafSmall=0; + private int nChr=0, nScaf=0, nMt=0, nUnk=0, nGap=0; // for numbering output seqid and totals + private int cntChr=0, cntScaf=0, cntMtPt=0, cntUnk=0; // for counting regardless of write to file + private long chrLen=0, scafLen=0, mtptLen=0, unkLen=0, totalLen=0; + + private HashMap hexMap = new HashMap (); // CAS548 add + + private TreeMap cntBase = new TreeMap (); + private PrintWriter fhOut, ghOut; + private PrintWriter logFile=null; + + private boolean bSuccess=true; + + /************************************************************************/ + public static void main(String[] args) { + isToSymap=false; + new ConvertEnsembl(args, defGapLen, null, false); + } + protected ConvertEnsembl(String[] args, int gapLen, String prefix, boolean bNum) { // CAS557 make accessible from ConvertFrame + if (args.length==0) { // command line + checkArgs(args); + return; + } + gapMinLen = gapLen; + prefixOnly = prefix; + bNumOnly = bNum; + + projDir = args[0]; + prt(""\n------ ConvertEnsembl "" + projDir + "" ------""); + checkInitFiles(); if (!bSuccess) return; + + //hexMap.put(""%09"", "" ""); // tab break on this + hexMap.put(""%3D"", ""-""); // = but cannot have these in attr, so use dash + hexMap.put(""%0A"", "" ""); // newline + hexMap.put(""%25"", ""%""); // % + hexMap.put(""%2C"", "",""); // , + hexMap.put(""%3B"", "",""); // ; but cannot have these in attr, so use comma + hexMap.put(""%26"", ""&""); // & + + createLog(args); if (!bSuccess) return; + checkArgs(args); if (!bSuccess) return; + + rwFasta(); + + rwAnno(); if (!bSuccess) return; + + printSummary(); + + prt(""""); + printSuggestions(); + prt(""------ Finish ConvertEnsembl "" + projDir + "" -------""); + if (logFile!=null) logFile.close(); + } + private void printSuggestions() { + boolean isChr = true; + if (chr2id.size()>0) { + for (String c : chr2id.keySet()) { + if (!c.startsWith(chrPrefix)) { + isChr=false; + break; + } + } + if (isChr && !INCLUDESCAF) prt(""Suggestion: Set SyMAP project parameter 'Group prefix' to 'Chr'.""); + } + if (cntOutSeq==0) prt(""Are these Ensembl files? Should scaffolds be included? Should 'Prefix only' be set?""); + else if (cntOutSeq>30) prt( ""Suggestion: There are "" + String.format(""%,d"",cntOutSeq) + "" sequences. "" + + ""Set SyMAP project parameter 'Minimum length' to reduce number loaded.""); + } + /** + * * Fasta file example: + * >1 dna_sm:chromosome chromosome:IRGSP-1.0:1:1:43270923:1 REF + * >Mt dna_sm:chromosome chromosome:IRGSP-1.0:Mt:1:490520:1 REF + * >Syng_TIGR_043 dna_sm:scaffold scaffold:IRGSP-1.0:Syng_TIGR_043:1:4236:1 REF + */ + private void rwFasta() { + try { + cntBase = new TreeMap (); + char [] base = {'A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'}; + for (char b : base) cntBase.put(b, 0); + + fhOut = new PrintWriter(new FileOutputStream(seqDir+outFaFile, false)); + fhOut.println(header); + + ghOut = new PrintWriter(new FileOutputStream(annoDir + outGapFile, false)); + ghOut.println(header); + + for (String file : inFaFileVec) { + rwFasta(file); + } + fhOut.close(); ghOut.close(); + System.err.print("" \r""); + String xx = (VERBOSE) ? ""("" + star + "")"" : """"; + prt(String.format(""Sequences not output: %,d %s"", cntNoOutSeq, xx)); + prt(""Finish writing "" + seqDir + outFaFile + "" ""); + + prt(""""); + prt( String.format(""A %,11d a %,11d"", cntBase.get('A'), cntBase.get('a')) ); + prt( String.format(""T %,11d t %,11d"", cntBase.get('T'), cntBase.get('t')) ); + prt( String.format(""C %,11d c %,11d"", cntBase.get('C'), cntBase.get('c')) ); + prt( String.format(""G %,11d g %,11d"", cntBase.get('G'), cntBase.get('g')) ); + prt( String.format(""N %,11d n %,11d"", cntBase.get('N'), cntBase.get('n') )); + String other=""""; + for (char b : cntBase.keySet()) { + boolean found = false; + for (char x : base) if (x==b) {found=true; break;} + if (!found) other += String.format(""%c %,d "", b, cntBase.get(b)); + } + if (other!="""") prt(other); + + cntBase.clear(); + prt(String.format(""Total %,d"", totalLen)); + + prt("" ""); + prt(String.format(""Gaps >= %,d: %,d (using N and n)"", gapMinLen, nGap)); + prt(""Finish writing "" + annoDir + outGapFile + "" ""); + } + catch (Exception e) {die(e, ""rwFasta"");} + } + private void rwFasta(String fileName) { + try { + prt(""Processing "" + fileName); + + String prtName="""", idCol1="""", line; + boolean bPrt=false, isChr=false, isScaf=false, isMtPt=false; + boolean bMt=false, bPt=false; + int baseLoc=0, gapStart=0, gapCnt=1, len=0, lineN=0; + + BufferedReader fhIn = openGZIP(fileName); if (!bSuccess) return; + + while ((line = fhIn.readLine()) != null) { + lineN++; + if (line.startsWith(""!"") || line.startsWith(""#"") || line.trim().equals("""")) continue; + + if (line.startsWith("">"")) { + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMtPt, len, idCol1, prtName); + len=0; + } + bPrt=false; + String line1 = line.substring(1).trim(); + String [] tok = line1.split(""\\s+""); + if (tok.length==0) { + die(""Header line is blank: line #"" + lineN); + return; + } + + idCol1 = tok[0].trim(); + + isMtPt = idCol1.toLowerCase().startsWith(""mt"") // CAS557 MT or mtDNA... and add line check + || idCol1.toLowerCase().startsWith(""pt"") + || line.contains(""mitochondrion"") + || line.contains(""plastid"") + || line.contains(""mitochondrial"") + || line.contains(""chloroplast""); + + isChr = isChrNum(idCol1) || line.contains(""chromosome""); // CAS557 start checking for word + + isScaf = line.contains(""scaffold""); + + if (isChr && !isMtPt) cntChr++; + else if (isMtPt) cntMtPt++; + else if (isScaf) cntScaf++; + else cntUnk++; + + if (prefixOnly!=null) { // CAS557 new parameter + if (!idCol1.startsWith(prefixOnly)) { + cntNoOutSeq++; + continue; + } + } + else if (bNumOnly) { + if (!isChrNum(idCol1)) { + cntNoOutSeq++; + continue; + } + } + + if (isChr && !isMtPt) { + nChr++; + prtName = isChrNum(idCol1) ? chrPrefix + padNum(tok[0]) : idCol1; // tok[0], e.g. C1 for cabbage + cntChrGene.put(idCol1, 0); + id2chr.put(idCol1, prtName); + chr2id.put(prtName, idCol1); + + fhOut.println("">"" + prtName + "" "" + idCol1 + "" "" + chrType); + bPrt=true; + } + else if (isMtPt && INCLUDEMtPt) { // just like for numeric chromosome + prtName = chrPrefix + tok[0]; + + if (idCol1.equalsIgnoreCase(""Mt"")) { + if (bMt) { + if (VERBOSE) prt(""Ignore Mt: "" + line); + cntNoOutSeq++; + continue; + } + else {bMt=true; nMt++;} + } + if (idCol1.equalsIgnoreCase(""Pt"")) { + if (bPt) { + if (VERBOSE) prt(""Ignore Pt: "" + line); + cntNoOutSeq++; + continue; + } + else {bPt=true; nMt++;} + } + cntChrGene.put(idCol1, 0); + id2chr.put(idCol1, prtName); + chr2id.put(prtName, idCol1); + + fhOut.println("">"" + prtName + "" "" + idCol1 + "" "" + chrType); + bPrt=true; + } + else if (isScaf && INCLUDESCAF) { + nScaf++; + prtName = scafPrefix + padNum(nScaf+""""); // scaf use name + + id2scaf.put(idCol1, prtName); + cntScafGene.put(idCol1, 0); + gapStart=1; gapCnt=0; baseLoc=0; + + fhOut.println("">"" + prtName+ "" "" + idCol1 + "" "" + scafType); + bPrt=true; + } + else { + if (isScaf) {prtName=""Scaf"";} + else if (isMtPt) {prtName=""Mt/Pt"";} + else {prtName=""Unk"";} + + if (prefixOnly!=null) {// use chr, don't know what it is + nUnk++; + prtName = unkPrefix + padNum(nUnk+""""); // but no prefix + id2chr.put(idCol1, prtName); + cntChrGene.put(idCol1, 0); + + bPrt=true; + fhOut.println("">"" + prtName+ "" "" + idCol1 + "" "" + unkType); + } + } + if (bPrt) cntOutSeq++; else cntNoOutSeq++; + } + ////////////////////////////////////////////////////////////////// + else { + String aline = line.trim(); + if (bPrt) { + char [] bases = aline.toCharArray(); + + for (int i =0 ; i0) { // gaps + if (gapCnt>gapMinLen) { + nGap++; + String x = createGap(prtName, gapStart, gapCnt); + if (bPrt) ghOut.println(x); + } + gapStart=0; gapCnt=1; + } + } + } + len += aline.length(); + if (bPrt) fhOut.println(aline); + } + } + if (len>0) { + totalLen += len; + printTrace(bPrt, isChr, isScaf, isMtPt, len, idCol1, prtName); + } + fhIn.close(); + } + catch (Exception e) {die(e, ""rwFasta"");} + } + private boolean isChrNum(String col1) { + if (col1.contentEquals(""X"") || col1.contentEquals(""Y"")) return true; + try { + Integer.parseInt(col1); + return true; + } + catch (Exception e) { + if (col1.length()>3) return false; + // roman + char [] x = col1.toCharArray(); + for (char y : x) { + if (y!='I' && y!='V' && y!='X') return false; + } + return true; + } + } + //chr3 consensus gap 4845507 4895508 . + . Name ""chr03_0"" + private String createGap(String chr, int start, int len) { + String id = ""Gap_"" + nGap + ""_"" + len; + return chr + ""\tsymap\tgap\t"" + start + ""\t"" + (start+len) + ""\t.\t+\t.\tID=\"""" + id + ""\""""; + } + // The zero is added so that the sorting will be integer based + private String padNum(String x) { + try { + Integer.parseInt(x); + if (x.length()==1) return ""0"" + x; + else return x; + } + catch (Exception e) { + return x; + } // could be X or Y + } + + private void printTrace(boolean bPrt, boolean isChr, boolean isScaf, boolean isMtPt, int len, String id, String prtname) { + String x = (bPrt) ? """" : star; + String msg = String.format(""%-7s %-15s %,11d %s"", prtname, id, len,x); + String msg2 = String.format("" %s %,d %s .... "", prtname, len,x); + if (isChr && !isMtPt) { + chrLen+=len; + if (bPrt || VERBOSE) { + if (cntChr<=traceNum) prt(msg); + else if (cntChr==traceNum+1) prt(""Suppressing further chromosome logs""); + else System.out.print(msg2 + ""\r""); + } + else System.out.print(msg2 + ""\r""); + } + else if (isMtPt) { + mtptLen+=len; + if (bPrt || VERBOSE) { + if (cntMtPt<=traceNum) prt(msg); + else if (cntMtPt==traceNum+1) prt(""Suppressing further Mt/Pt logs""); + else System.out.print(msg2 + ""\r""); + } + } + else if (isScaf) { + scafLen+=len; + if (len1000000) System.out.print(msg2 + ""\r""); + } + else { + unkLen += len; + if (bPrt || VERBOSE) { + if (cntUnk<=traceNum) prt(msg); + else if (cntUnk==traceNum+1) prt(""Suppressing further unknown logs""); + else System.out.print(msg2 + ""\r""); + } + else if (len>1000000) System.out.print(msg2 + ""\r""); + } + } + + /******************************************************************************** + * XXX GFF file, e.g. +1 araport11 gene 3631 5899 . + . ID=gene:AT1G01010;Name=NAC001;biotype=protein_coding;description=NAC domain containing protein 1 [Source:NCBI gene (formerly Entrezgene)%3BAcc:839580];gene_id=AT1G01010;logic_name=araport11 +1 araport11 mRNA 3631 5899 . + . ID=transcript:AT1G01010.1;Parent=gene:AT1G01010;Name=NAC001-201;biotype=protein_coding;transcript_id=AT1G01010.1 +1 araport11 five_prime_UTR 3631 3759 . + . Parent=transcript:AT1G01010.1 +1 araport11 exon 3631 3913 . + . Parent=transcript:AT1G01010.1;Name=AT1G01010.1.exon1;constitutive=1;ensembl_end_phase=1;ensembl_phase=-1;exon_id=AT1G01010.1.exon1;rank=1 + */ + private int cntGene=0, cntExon=0, cntMRNA=0, cntGeneNotOnSeq=0, cntNoDesc=0; + private int skipLine=0; + private PrintWriter fhOutGff=null; + private int cntReadGene=0, cntReadMRNA=0, cntReadExon=0; + + // per gene + private String geneID="""",geneLine="""", gchr="""", gproteinAt="""", gmrnaAt=""""; + private String mrnaLine="""", mrnaID=""""; + private int cntThisGeneMRNA=0; + private Vector exonVec = new Vector (); + + private void rwAnno() { + if (inGffFileVec==null || inGffFileVec.size()==0) return; + try { + fhOutGff = new PrintWriter(new FileOutputStream(annoDir + outGffFile, false)); + fhOutGff.println(header); + + for (String file : inGffFileVec) { + rwAnno(file); + } + fhOutGff.close(); + + prt(String.format("" Use Gene %,d from %,d "", cntGene, cntReadGene)); + prt(String.format("" Use mRNA %,d from %,d "", cntMRNA, cntReadMRNA)); + prt(String.format("" Use Exon %,d from %,d "", cntExon, cntReadExon)); + prt(""Finish writing "" + annoDir + outGffFile + "" ""); + } + catch (Exception e) {die(e, ""rwAnno"");} + } + private void rwAnno(String file) { + try { + String line="""", type=""""; + + prt(""""); + prt(""Processing "" + file); + BufferedReader fhIn = openGZIP(file); if (!bSuccess) return; + + while ((line = fhIn.readLine()) != null) { + line = line.trim(); + if (line.startsWith(""#"") || line.startsWith(""!"") || line.trim().length()==0) continue; + + String [] tok = line.split(""\\t""); + if (tok.length!=9) { + skipLine++; + if (skipLine<10) prt(""Bad line: "" + line); + else die(""too many errors""); + continue; + } + + // Count everything here for summary + type = tok[2].trim(); // gene, mRNA, exon... + if (!allTypeCnt.containsKey(type)) allTypeCnt.put(type,1); + else allTypeCnt.put(type, allTypeCnt.get(type)+1); + + if (type.equals(geneType)) { + rwAnnoOut(fhOutGff); + rwAnnoGene(tok, line); + cntReadGene++; + } + else if (type.equals(mrnaType)) { + rwAnnoMRNA(tok, line); + cntReadMRNA++; cntThisGeneMRNA++; + } + else if (type.equals(cdsType)) { + rwAnnoCDS(tok, line); + } + else if (type.equals(exonType)) { + rwAnnoExon(tok, line); + cntReadExon++; + } + } + fhIn.close(); + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + + private void rwAnnoGene(String [] tok, String line) { + try { + cntGene++; + if (cntGene%PRT==0) System.err.print("" Process "" + cntGene + "" genes...\r""); + + // counts for gene + String [] typeAttrs = tok[8].trim().split("";""); + String biotype = getVal(biotypeAttrKey, typeAttrs); + if (!allGeneBiotypeCnt.containsKey(biotype)) allGeneBiotypeCnt.put(biotype,1); + else allGeneBiotypeCnt.put(biotype, allGeneBiotypeCnt.get(biotype)+1); + + String src = tok[1].trim(); // RefSeq, Gnomon.. + + if (!allGeneSrcCnt.containsKey(src)) allGeneSrcCnt.put(src,1); + else allGeneSrcCnt.put(src, allGeneSrcCnt.get(src)+1); + + if (!biotype.equals(biotypeAttr)) return; // protein-coding + + String idcol1 = tok[0]; // chromosome, scaffold, linkage group... + if (id2chr.containsKey(idcol1)) { + cntChrGeneAll++; + gchr = id2chr.get(idcol1); + cntChrGene.put(idcol1, cntChrGene.get(idcol1)+1); + } + else if (id2scaf.containsKey(idcol1)) { + cntScafGeneAll++; + gchr = id2scaf.get(idcol1); + cntScafGene.put(idcol1, cntScafGene.get(idcol1)+1); + } + else { + cntGeneNotOnSeq++; + return; + } + geneID = getVal(idAttrKey, typeAttrs); + String gid = geneID.replace(RMGENE,""""); + String attr = idAttrKey + ""="" + gid + "";"" + getKeyVal(nameAttrKey, typeAttrs); + + String desc = getVal(descAttrKey, typeAttrs).trim(); + if (desc==null || desc.equals("""")) { + cntNoDesc++; + } + else { + if (desc.contains(source)) desc = desc.substring(0, desc.lastIndexOf(source)); // CAS558 change to last + + if (desc.contains(""%"")) { // CAS548 add + for (String hex : hexMap.keySet()) { + if (desc.contains(hex)) desc = desc.replace(hex, hexMap.get(hex)); + } + } + attr += "";"" + DESC + desc; + } + + geneLine = ""###\n"" + gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + attr; + } + catch (Exception e) {die(e, ""rwAnnoGene"");} + } + // mRNA is not loaded into SyMAP, but needed for exon parentID + private void rwAnnoMRNA(String [] tok, String line) { + try { + if (!mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (!geneID.equals(pid)) return; + + //////// + mrnaID = getVal(idAttrKey, attrs); + gmrnaAt = "";"" + MRNAID + mrnaID.replace(RMTRAN,""""); + + String mid = idAttrKey + ""="" + mrnaID.replace(RMTRAN,""""); + String gid = parentAttrKey + ""="" + geneID.replace(RMGENE,""""); + String newAttrs = mid + "";"" + gid; + mrnaLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + + tok[4] + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + + cntMRNA++; + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + private void rwAnnoCDS(String [] tok, String line) { + try { + if (!ATTRPROT || mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + + if (mrnaID.equals(pid)) { + gproteinAt = "";"" + PROTEINID + getVal(cdsProteinAttrKey, attrs); + } + } + catch (Exception e) {die(e, ""rwAnnoMRNA"");} + } + /** Write genes and exons to file**/ + private void rwAnnoExon(String [] tok, String line) { + try { + if (mrnaID.equals("""")) return; + + String [] attrs = tok[8].split("";""); + String pid = getVal(parentAttrKey, attrs); + if (!mrnaID.equals(pid)) return; + + ////////////////// + String newAttrs = parentAttrKey + ""="" + mrnaID.replace(RMTRAN,""""); + + String nLine = gchr + ""\t"" + tok[1] + ""\t"" + tok[2] + ""\t"" + tok[3] + ""\t"" + tok[4] + + ""\t"" + tok[5] + ""\t"" + tok[6] + ""\t"" + tok[7] + ""\t"" + newAttrs; + exonVec.add(nLine); + cntExon++; + } + catch (Exception e) {die(e, ""rwAnnoExon"");} + } + private void rwAnnoOut( PrintWriter fhOutGff) { + try { + if (geneID.equals("""")) return; + if (mrnaID.equals("""")) return; + + gmrnaAt = gmrnaAt.replace(RMTRAN,""""); + gmrnaAt += "" ("" + cntThisGeneMRNA + "");""; + String line = geneLine + gmrnaAt + gproteinAt; + fhOutGff.println(line); + + fhOutGff.println(mrnaLine); + + for (String eline : exonVec) fhOutGff.println(eline); + + cntThisGeneMRNA=0; + geneID=geneLine=gchr=gproteinAt=gmrnaAt=mrnaID=mrnaLine=""""; + exonVec.clear(); + } + catch (Exception e) {die(e, ""rwAnnoOut"");} + } + + private String getVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return x[1]; + } + return """"; + } + private String getKeyVal(String key, String [] attrs) { + for (String s : attrs) { + String [] x = s.split(""=""); + if (x[0].equals(key)) return s; + } + return key + ""=no value""; + } + + /***************************************************************** + * Summary + */ + private void printSummary() { + prt("" ""); + if (VERBOSE) { + prt("">>Sequences ""); + if (cntChr>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntChr, nChr, ""Chromosomes"", chrLen)); + } + if (cntMtPt>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntMtPt, nMt, ""Mt/Pt"", mtptLen)); + } + if (cntScaf>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d (%,d < %,dbp)"", cntScaf,nScaf, ""Scaffolds"", scafLen, cntScafSmall, scafMaxLen)); + } + if (cntUnk>0) { + prt(String.format("" %,6d Output %-,6d %-11s %,15d"", cntUnk, nUnk, ""Unknown"", unkLen)); + } + if (inGffFileVec==null) return; + + prt("" ""); + prt("">>All Types (col 3) ("" + plus + "" are processed keywords)""); + for (String key : allTypeCnt.keySet()) { + boolean bKey = ATTRPROT && key.equals(cdsType); + String x = (key.equals(geneType) || key.equals(mrnaType) || key.equals(exonType)) || bKey ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allTypeCnt.get(key), x)); + } + + prt("">>All Gene Source (col 2)""); + for (String key :allGeneSrcCnt.keySet()) { + prt(String.format("" %-22s %,8d"", key, allGeneSrcCnt.get(key))); + } + + prt("">>All gene biotype= (col 8) ""); + for (String key : allGeneBiotypeCnt.keySet()) { + String x = (key.equals(biotypeAttr)) ? plus : """"; + prt(String.format("" %-22s %,8d %s"", key, allGeneBiotypeCnt.get(key), x)); + } + + if (cntNoDesc>0) { + prt("">>Description""); + prt(String.format("" %-22s %,8d"", ""None"", cntNoDesc)); + } + } + prt(String.format("">>Chromosome gene count %,d"", cntChrGeneAll)); + + for (String prt : chr2id.keySet()) { + String id = chr2id.get(prt); // sorted on prtName + int cnt = cntChrGene.get(id); + prt(String.format("" %-10s %-20s %,8d"", prt, id, cnt)); + } + + if (INCLUDESCAF) { + prt(String.format("">>Scaffold gene count %,d (list scaffolds with #genes>%d)"", cntScafGeneAll, traceNumGenes)); + int cntOne=0; + for (String key : cntScafGene.keySet()) { // sorted on idCol1, which is not scaffold order + int cnt = cntScafGene.get(key); + if (cnt>traceNumGenes) prt(String.format("" %-7s %-15s %,8d"", id2scaf.get(key), key, cnt)); + else cntOne++; + } + prt(String.format("" Scaffolds with <=%d gene (not listed) %,8d"", traceNumGenes, cntOne)); + prt(String.format("" Genes not included %,8d"", cntGeneNotOnSeq)); + } + else prt(String.format("" Genes not on Chromosome %,8d"", cntGeneNotOnSeq)); + } + /************************************************************ + * File stuff + */ + private boolean checkInitFiles() { + // find fasta and gff files + try { + if (projDir==null || projDir.trim().equals("""")) + return die(""No project directory""); + + File dir = new File(projDir); + if (!dir.isDirectory()) + return die(""The argument must be a directory. "" + projDir + "" is not a directory.""); + + File[] files = dir.listFiles(); + for (File f : files) { + if (f.isFile() && !f.isHidden()) { + String fname = f.getName(); + + if (fname.endsWith(faSuffix + "".gz"") || fname.endsWith(faSuffix)) inFaFileVec.add(projDir + ""/"" + fname); + else if (fname.endsWith(gffSuffix + "".gz"") || fname.endsWith(gffSuffix)) inGffFileVec.add(projDir + ""/"" +fname); + } + } + } + catch (Exception e) {die(e, ""Checking files"");} + + if (inFaFileVec.size()==0) + return die(""Project directory "" + projDir + "": no file ending with "" + faSuffix + "" or ""+ faSuffix + "".gz (i.e. Ensembl files)""); + if (inGffFileVec.size()==0) + prt(""Project directory "" + projDir + "": no file ending with "" + gffSuffix + "" or "" + gffSuffix + "".gz""); + + // Create sequence and annotation directories + if (!projDir.endsWith(""/"")) projDir += ""/""; + seqDir = projDir + seqDir; + createDir(true, seqDir); if (!bSuccess) return false; + + annoDir = projDir + annoDir; + createDir(false, annoDir); if (!bSuccess) return false; + + return true; + } + private void createLog(String [] args) { + if (args.length==0) return; + logFileName = args[0] + logFileName; + prt(""Log file to "" + logFileName); + + try { + logFile = new PrintWriter(new FileOutputStream(logFileName, false)); + } + catch (Exception e) {die(""Cannot open "" + logFileName); logFile=null;} + } + + private boolean createDir(boolean isSeq, String dir) { + File nDir = new File(dir); + if (nDir.exists()) { + String x = (isSeq) ? "" .fna and .fa "" : "" .gff and .gff3""; + prt(dir + "" exists - remove existing "" + x + "" files""); + deleteFilesInDir(isSeq, nDir); + return true; + } + else { + if (!nDir.mkdir()) { + die(""*** Failed to create directory '"" + nDir.getAbsolutePath() + ""'.""); + return false; + } + } + return true; + } + private void deleteFilesInDir(boolean isSeq, File dir) { + if (!dir.isDirectory()) return; + + String[] files = dir.list(); + + if (files==null) return; + + for (String fn : files) { + if (isSeq) { + if (fn.endsWith("".fna"") || fn.endsWith("".fa"")) { + new File(dir, fn).delete(); + } + } + else { + if (fn.endsWith("".gff"") || fn.endsWith("".gff3"")) { + new File(dir, fn).delete(); + } + } + } + } + private BufferedReader openGZIP(String file) { + try { + if (!file.endsWith("".gz"")) { + File f = new File (file); + if (f.exists()) return new BufferedReader ( new FileReader (f)); + else die(""Cannot open file "" + file); + } + else if (file.endsWith("".gz"")) { + FileInputStream fin = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fin); + InputStreamReader xover = new InputStreamReader(gzis); + return new BufferedReader(xover); + } + else die(""Do not recognize file suffix: "" + file); + } + catch (Exception e) {die(e, ""Cannot open file "" + file);} + return null; + } + + /****************************************************************** + * Args print and process + */ + private void checkArgs(String [] args) { + if (args.length==0 || args[0].equals(""-h"") || args[0].equals(""-help"") || args[0].equals(""help"")) { + System.out.println(""\nConvertEnsembl [-r] [-c] [-v] ""); + System.out.println( + "" the project directory must contain the FASTA file and the GFF is optional: \n"" + + "" FASTA file ending with .fa or .fa.gz e.g. Oryza_sativa.IRGSP-1.0.dna_sm.toplevel.fa.gz\n"" + + "" GFF file ending with .gff3 or .gff3.gz e.g. Oryza_sativa.IRGSP-1.0.45.chr.gff3.gz\n"" + + "" Options:\n"" + + "" -s include any sequence with the header contains 'scaffold'.\n"" + + "" -t include Mt and Pt chromosomes.\n"" + + "" -p include the protein name (1st CDS) in the attribute field.\n"" + + "" -v write header lines of ignored sequences [default false].\n"" + + ""\nSee https://csoderlund.github.io/SyMAP/convert for details.""); + System.exit(0); + } + + prt(""Parameters:""); + prt("" Project Directory: "" + args[0]); + projDir = args[0]; + + if (gapMinLen!=defGapLen) prt("" Gap size: "" + gapMinLen); // argument to Convert + if (prefixOnly!=null) prt("" Prefix Only: "" + prefixOnly); // set in main + if (bNumOnly) prt("" Only number, X, Y, Roman""); // set in main + + if (args.length>1) { + for (int i=1; i< args.length; i++) { + if (args[i].equals(""-v"")) { + VERBOSE=true; + prt("" Verbose ""); + traceNum=20; + } + else if (args[i].equals(""-s"")) { + INCLUDESCAF=true; + chrPrefix = chrPrefix2; + prt("" Include any sequence whose header line contains 'scaffold'""); + prt("" Uses prefixes Chr '"" + chrPrefix + ""' and Scaffold '"" + scafPrefix +""'""); + } + else if (args[i].equals(""-t"")) { + INCLUDEMtPt=true; + prt("" Include Mt and Pt chromosomes""); + } + else if (args[i].equals(""-p"")) { + ATTRPROT=true; + prt("" Include protein-id in attributes""); + } + } + } + } + private boolean die(Exception e, String msg) { + System.err.println(""Fatal error -- "" + msg); + e.printStackTrace(); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private boolean die(String msg) { + System.err.println(""Fatal error -- "" + msg); + if (!isToSymap) System.exit(-1); + bSuccess = false; + return false; + } + private void prt(String msg) { + System.out.println(msg); + if (logFile!=null) logFile.println(msg); + } +} +","Java" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/startup.sh",".sh","1790","60","#!/bin/bash +# This script is used to set up the development environment for the application. + +DB_CONTAINER_NAME=dev-postgres-$$ + +cleanup() { + echo ""Cleaning up docker container ($DB_CONTAINER_NAME)..."" + if [ ""$(docker ps -q -f name=$DB_CONTAINER_NAME)"" ]; then + docker stop $DB_CONTAINER_NAME + echo ""Container stopped and removed."" + elif [ ""$(docker ps -aq -f name=$DB_CONTAINER_NAME)"" ]; then + echo ""Container $DB_CONTAINER_NAME exists but is not running. Attempting removal..."" + docker rm $DB_CONTAINER_NAME + echo ""Container removed."" + else + echo ""Container $DB_CONTAINER_NAME not found or already removed."" + fi +} + +trap cleanup EXIT INT TERM + +echo ""Navigating to the application directory..."" +cd ./app || { + echo ""Failed to navigate to ./app"" + exit 1 +} + +echo ""Installing dependencies..."" +poetry install || { + echo ""Failed to install dependencies"" + exit 1 +} + +echo ""Starting PostgreSQL database ($DB_CONTAINER_NAME)..."" +docker run -d --rm --name=$DB_CONTAINER_NAME -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17-alpine || { + echo ""Failed to start PostgreSQL container"" + exit 1 +} + +echo ""Waiting for PostgreSQL database ($DB_CONTAINER_NAME) to be ready..."" + +if ! docker ps -q -f name=$DB_CONTAINER_NAME; then + echo ""ERROR: PostgreSQL container ($DB_CONTAINER_NAME) failed to start."" + echo ""--- Docker Logs ---"" + docker logs $DB_CONTAINER_NAME + echo ""--- End Docker Logs ---"" + exit 1 +fi + +echo ""PostgreSQL container is ready."" + +echo ""Running migrations..."" +poetry run alembic upgrade head + +echo ""Setting up the environment..."" +export CHARGEFW2_INSTALL_DIR=/opt/chargefw2 + +echo ""Starting the web server..."" +poetry run gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker main:web_app +","Shell" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/entrypoint.sh",".sh","464","16","#!/bin/bash + +# This script runs migrations before running the gunicorn server. +# It is used in the Dockerfile. + +cd /acc/app + +# run database migrations +alembic upgrade head + +# use gunicorn with 4 workers +# uvicorn.workers.UvicornWorker is used for async processing +# setting timeout to 1 hour for long lasting computations +# running on port 8000 +exec gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker --timeout 6000 --bind 0.0.0.0:8000 main:web_app +","Shell" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/__init__.py",".py","150","7","import sys +from pathlib import Path + +# Add the project root to Python path +project_root = Path(__file__).parent +sys.path.insert(0, str(project_root)) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/main.py",".py","2325","82","""""""Main module for the application."""""" + +import os +import shutil + +from dotenv import load_dotenv +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware + +from api.v1.container import Container +from api.v1.routes.charges import charges_router +from api.v1.routes.auth import auth_router +from api.v1.routes.files import files_router +from api.v1.middleware.logging import LoggingMiddleware +from api.v1.middleware.exceptions import http_exception_handler +from api.v1.middleware.user_loader import UserLoaderMiddleware + + +PREFIX = ""/v1"" + + +def move_example_files() -> None: + if not load_dotenv(): + raise EnvironmentError(""Could not load environment variables."") + + # Move example files to example directory + if not (examples_dir := os.environ.get(""ACC_EXAMPLES_DIR"")): + raise EnvironmentError(""ACC_EXAMPLES_DIR environment variable is not set."") + + if os.path.exists(examples_dir): + shutil.rmtree(examples_dir, ignore_errors=True) + + try: + os.makedirs(examples_dir, exist_ok=True) + shutil.copytree(""examples"", examples_dir, dirs_exist_ok=True) + except Exception as e: + raise EnvironmentError(f""Could not copy example files. {str(e)}"") from e + + +def create_app() -> FastAPI: + """"""Creates FastAPI apps with routers and middleware."""""" + + move_example_files() + + # Create DI container + container = Container() + + app = FastAPI( + title=""Atomic Charge Calculator III API"", + root_path=""/api"", + swagger_ui_parameters={""syntaxHighlight"": False}, + ) + + container.wire() + + app.add_middleware(LoggingMiddleware) + app.add_middleware(UserLoaderMiddleware) + app.add_middleware( + CORSMiddleware, + allow_origins=[ + ""http://localhost:5173"", + ""http://localhost"", + ""http://127.0.0.1:5173"", + ""http://127.0.0.1"", + os.environ.get(""ACC_BASE_URL"", """"), + ], + allow_credentials=True, + allow_methods=[""*""], + allow_headers=[""*""], + ) + + app.add_exception_handler(HTTPException, http_exception_handler) + + app.include_router(router=charges_router, prefix=PREFIX) + app.include_router(router=files_router, prefix=PREFIX) + app.include_router(router=auth_router, prefix=PREFIX) + + return app + + +web_app = create_app() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/database.py",".py","1089","43","""""""Database connection manager."""""" + +from contextlib import contextmanager +from sqlalchemy.orm import Session, sessionmaker, scoped_session + +from sqlalchemy import create_engine + + +class Database: + """"""Database connection and model manager."""""" + + def __init__(self, db_url: str): + self._engine = create_engine(db_url, future=True, pool_size=20, max_overflow=10) + self.session_factory = scoped_session( + sessionmaker( + bind=self._engine, + autoflush=False, + autocommit=False, + expire_on_commit=False, + ) + ) + + +class SessionManager: + """"""Database session manager."""""" + + def __init__(self, session_factory): + self._session_factory = session_factory + + @contextmanager + def session(self): + """"""Provide a transactional scope."""""" + + session: Session = self._session_factory() + try: + yield session + session.commit() + except Exception: + session.rollback() + raise + finally: + session.close() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/moleculeset_stats_repository.py",".py","1617","56","""""""This module provides a repository for calculation configs."""""" + +from sqlalchemy import select +from sqlalchemy.orm import joinedload, Session + + +from db.schemas.calculation import CalculationConfig +from db.schemas.stats import MoleculeSetStats + + +class MoleculeSetStatsRepository: + """"""Repository for managing MoleculeSetStats."""""" + + def get(self, session: Session, file_hash: str) -> MoleculeSetStats | None: + """"""Get info about a file based on file hash. + + Args: + file_hash (str): Hash of the file. + + Returns: + MoleculeSetStats | None: Information about the file or None if not found. + """""" + + statement = ( + select(MoleculeSetStats) + .options(joinedload(MoleculeSetStats.atom_type_counts)) + .execution_options(populate_existing=True) + .where(MoleculeSetStats.file_hash == file_hash) + ) + + info = (session.execute(statement)).scalars().first() + + return info + + def store(self, session: Session, info: MoleculeSetStats) -> CalculationConfig: + """"""Store info about a file in the database. + If a given config already exists, it is returned. + + Args: + config (CalculationConfig): Calculation config. + + Raises: + ValueError: If the calculation set to which the calculation config belongs is not found. + + Returns: + CalculationConfig: Stored calculation config. + """""" + + exists = self.get(session, info.file_hash) + + if exists is not None: + return exists + + session.add(info) + return info +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/calculation_repository.py",".py","2675","79","""""""This module provides a repository for calculations."""""" + +from sqlalchemy import and_, Select, func, select +from sqlalchemy.orm import joinedload, Session + + +from models.paging import PagedList +from models.calculation import CalculationsFilters + +from db.schemas.calculation import AdvancedSettings, Calculation, CalculationConfig +from db.repositories.calculation_set_repository import CalculationSetRepository + + +class CalculationRepository: + """"""Repository for managing calculation sets."""""" + + def __init__( + self, + set_repository: CalculationSetRepository, + ): + self.set_repository = set_repository + + def get(self, session: Session, filters: CalculationsFilters) -> Calculation | None: + """"""Get a single previous calculation by id. + + Args: + calculation_id (str): Calculation id to get. + + Returns: + Calculation: Calculation set. + """""" + + statement = ( + select(Calculation) + .join(CalculationConfig) + .join(AdvancedSettings) + .options(joinedload(Calculation.config), joinedload(Calculation.advanced_settings)) + .where( + and_( + Calculation.file_hash == filters.hash, + CalculationConfig.method == filters.method, + CalculationConfig.parameters == filters.parameters, + AdvancedSettings.read_hetatm == filters.read_hetatm, + AdvancedSettings.ignore_water == filters.ignore_water, + AdvancedSettings.permissive_types == filters.permissive_types, + ) + ) + ) + + calculation = (session.execute(statement)).unique().scalars().first() + return calculation + + def store(self, session: Session, calculation: Calculation) -> Calculation: + """"""Store a single calculation set in the database. + + Args: + calculation_set (Calculation): Calculation to store. + + Returns: + Calculation: Stored calculation set. + """""" + + session.add(calculation) + + return calculation + + def _paginate( + self, session: Session, statement: Select, page: int, page_size: int + ) -> PagedList[Calculation]: + total_statement = select(func.count()).select_from(statement) + items_statement = statement.limit(page_size).offset((page - 1) * page_size) + + total_count = (session.execute(total_statement)).scalar() + items = (session.execute(items_statement)).scalars(Calculation).all() + + return PagedList[Calculation]( + page=page, page_size=page_size, total_count=total_count, items=items + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/user_repository.py",".py","1119","44","from db.schemas.user import User +from db.database import SessionManager + +from sqlalchemy import select + + +class UserRepository: + """"""Repository for managing calculation sets."""""" + + def __init__(self, session_manager: SessionManager): + self.session_manager = session_manager + + def get(self, openid: str) -> User | None: + """"""Get user by their openid. + + Args: + openid (str): Openid of the user. + + Returns: + User | None: User with provided openid if exists, otherwise None. + """""" + + statement = select(User).where(User.openid == openid) + + with self.session_manager.session() as session: + user = (session.execute(statement)).scalars().first() + return user + + def store(self, user: User) -> User: + """"""Store user in the database. + + Args: + user (User): User to store. + + Returns: + User: Stored user. + """""" + + with self.session_manager.session() as session: + session.add(user) + session.commit() + session.refresh(user) + return user +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/calculation_config_repository.py",".py","1218","42","""""""This module provides a repository for calculation configs."""""" + +from sqlalchemy import and_, select +from sqlalchemy.orm import Session + + +from db.schemas.calculation import CalculationConfig +from db.repositories.calculation_set_repository import CalculationSetRepository + + +class CalculationConfigRepository: + """"""Repository for managing calculation configs."""""" + + def __init__( + self, + set_repository: CalculationSetRepository, + ): + self.set_repository = set_repository + + def get( + self, session: Session, method: str, parameters: str | None + ) -> CalculationConfig | None: + """"""Get a single calculation config matching the provided filters. + + Args: + method (str): Empirical method. + parameters (str | None): Method parameters (if any). + + Returns: + CalculationConfig | None: Calculation config or None if not found. + """""" + + statement = select(CalculationConfig).where( + and_( + CalculationConfig.method == method, + CalculationConfig.parameters == parameters, + ) + ) + + config = (session.execute(statement)).scalars().first() + return config +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/advanced_settings_repository.py",".py","1410","44","""""""This module provides a repository for calculation sets."""""" + +from sqlalchemy import and_, select +from sqlalchemy.orm import Session + + +from db.schemas.calculation import AdvancedSettings +from models.setup import AdvancedSettingsDto + + +class AdvancedSettingsRepository: + """"""Repository for managing calculation sets."""""" + + def get(self, session: Session, settings: AdvancedSettingsDto) -> AdvancedSettings | None: + """"""Get Advanced Calculation Settings from database. + + Args: + settings (AdvancedSettingsDto): Advanced calculation settings. + + Returns: + AdvancedSettings: Advanced calculation settings. + """""" + + statement = select(AdvancedSettings).where( + and_( + AdvancedSettings.ignore_water == settings.ignore_water, + AdvancedSettings.read_hetatm == settings.read_hetatm, + AdvancedSettings.permissive_types == settings.permissive_types, + ) + ) + + advanced_settings = (session.execute(statement)).unique().scalars(AdvancedSettings).first() + + return advanced_settings + + def store(self, session: Session, advanced_settings: AdvancedSettings) -> None: + """"""Store an Advanced Calculation Settings in the database. + + Args: + advanced_settings (AdvancedSettings): Advanced calculation settings. + """""" + + session.add(advanced_settings) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/repositories/calculation_set_repository.py",".py","3860","118","""""""This module provides a repository for calculation sets."""""" + +from dataclasses import dataclass +from typing import Literal + +from sqlalchemy import Select, func, select, and_ +from sqlalchemy.orm import joinedload, Session + + +from models.paging import PagedList, PagingFilters + +from db.schemas.calculation import CalculationSet + + +@dataclass +class CalculationSetFilters(PagingFilters): + """"""Filters for calculation sets."""""" + + order_by: str + order: Literal[""asc"", ""desc""] + user_id: str | None = None + + +class CalculationSetRepository: + """"""Repository for managing calculation sets."""""" + + def get_all( + self, session: Session, filters: CalculationSetFilters + ) -> PagedList[CalculationSet]: + """"""Get all previous calculations matching the provided filters. + + Args: + filters (PagingFilters): Filters for paging. + + Returns: + PagedList[CalculationSet]: Paged list of calculation sets. + """""" + + statement = ( + select(CalculationSet) + .options(joinedload(CalculationSet.configs)) + .options(joinedload(CalculationSet.advanced_settings)) + .options(joinedload(CalculationSet.molecule_set_stats)) + .order_by(getattr(getattr(CalculationSet, filters.order_by), filters.order)()) + # Return only sets having some calculations + .where(and_(CalculationSet.configs.any(), CalculationSet.user_id == filters.user_id)) + ) + + calculations = self._paginate(session, statement, filters.page, filters.page_size) + + return calculations + + def get(self, session: Session, calculation_id: str) -> CalculationSet | None: + """"""Get a single previous calculation by id. + + Args: + calculation_id (str): Calculation id to get. + + Returns: + CalculationSet: Calculation set. + """""" + + statement = ( + select(CalculationSet) + .options( + joinedload(CalculationSet.configs), + joinedload(CalculationSet.advanced_settings), + joinedload(CalculationSet.molecule_set_stats), + ) + .execution_options(populate_existing=True) + .where(CalculationSet.id == calculation_id) + ) + + calculation_set = (session.execute(statement)).unique().scalars(CalculationSet).first() + return calculation_set + + def delete(self, session: Session, calculation_id: str) -> None: + """"""Delete a single previous calculation by id. + + Args: + calculation_id (str): Calculation id to delete. + """""" + + statement = select(CalculationSet).where(CalculationSet.id == calculation_id) + + calculation_set = (session.execute(statement)).scalars(CalculationSet).first() + + if not calculation_set: + return + + session.delete(calculation_set) + + def store(self, session: Session, calculation_set: CalculationSet) -> None: + """"""Store a single calculation set in the database. + + Args: + calculation_set (CalculationSet): Calculation set to store. + + Returns: + CalculationSet: Stored calculation set. + """""" + + if self.get(session, calculation_set.id) is None: + session.add(calculation_set) + + def _paginate( + self, session: Session, statement: Select, page: int, page_size: int + ) -> PagedList[CalculationSet]: + total_statement = select(func.count()).select_from(statement) + items_statement = statement.limit(page_size).offset((page - 1) * page_size) + + total_count = (session.execute(total_statement)).unique().scalar() + items = (session.execute(items_statement)).unique().scalars(CalculationSet).all() + + return PagedList[CalculationSet]( + page=page, page_size=page_size, total_count=total_count, items=items + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/alembic/env.py",".py","2381","89","import os + +from dotenv import load_dotenv + +from logging.config import fileConfig + +from sqlalchemy import engine_from_config, pool + +from alembic import context + +from db.schemas import Base # noqa: F401 + +from db.schemas.calculation import * # noqa: F401 +from db.schemas.stats import * # noqa: F401 +from db.schemas.user import * # noqa: F401 + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +load_dotenv() +config.set_main_option(""sqlalchemy.url"", os.environ.get(""ACC_DB_URL"")) + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option(""my_important_option"") +# ... etc. + + +def run_migrations_offline() -> None: + """"""Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """""" + url = config.get_main_option(""sqlalchemy.url"") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={""paramstyle"": ""named""}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """"""Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """""" + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix=""sqlalchemy."", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/alembic/versions/aa87655da208_calculationsetstats_file_name.py",".py","1633","45","""""""CalculationSetStats file_name + +Revision ID: aa87655da208 +Revises: b55dbc463b4a +Create Date: 2025-04-20 10:53:30.659946 + +"""""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'aa87655da208' +down_revision: Union[str, None] = 'b55dbc463b4a' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """"""Upgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_unique_constraint(None, 'calculation_set_configs', ['calculation_set_id', 'config_id']) + op.add_column('calculation_set_stats', sa.Column('file_name', sa.VARCHAR(length=255), nullable=True)) + op.create_unique_constraint(None, 'calculation_set_stats', ['calculation_set_id', 'molecule_set_id']) + op.alter_column('calculations', 'file_name', + existing_type=sa.VARCHAR(length=100), + type_=sa.VARCHAR(length=255), + existing_nullable=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """"""Downgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('calculations', 'file_name', + existing_type=sa.VARCHAR(length=255), + type_=sa.VARCHAR(length=100), + existing_nullable=False) + op.drop_constraint(None, 'calculation_set_stats', type_='unique') + op.drop_column('calculation_set_stats', 'file_name') + op.drop_constraint(None, 'calculation_set_configs', type_='unique') + # ### end Alembic commands ### +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/alembic/versions/b55dbc463b4a_init.py",".py","4605","110","""""""init + +Revision ID: b55dbc463b4a +Revises: +Create Date: 2025-04-18 23:53:47.245166 + +"""""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'b55dbc463b4a' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """"""Upgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('advanced_settings', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('read_hetatm', sa.Boolean(), nullable=False), + sa.Column('ignore_water', sa.Boolean(), nullable=False), + sa.Column('permissive_types', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('read_hetatm', 'ignore_water', 'permissive_types') + ) + op.create_table('calculation_configs', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('method', sa.VARCHAR(length=20), nullable=False), + sa.Column('parameters', sa.VARCHAR(length=50), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('method', 'parameters') + ) + op.create_table('molecule_set_stats', + sa.Column('file_hash', sa.VARCHAR(length=100), nullable=False), + sa.Column('total_molecules', sa.Integer(), nullable=False), + sa.Column('total_atoms', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('file_hash') + ) + op.create_table('users', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('openid', sa.VARCHAR(length=100), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('atom_type_counts', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('symbol', sa.VARCHAR(length=10), nullable=False), + sa.Column('count', sa.Integer(), nullable=False), + sa.Column('molecule_set_id', sa.VARCHAR(length=100), nullable=False), + sa.ForeignKeyConstraint(['molecule_set_id'], ['molecule_set_stats.file_hash'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('calculation_sets', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('user_id', sa.Uuid(), nullable=True), + sa.Column('advanced_settings_id', sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint(['advanced_settings_id'], ['advanced_settings.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('calculations', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('file_name', sa.VARCHAR(length=100), nullable=False), + sa.Column('file_hash', sa.VARCHAR(length=100), nullable=False), + sa.Column('charges', sa.JSON(), nullable=False), + sa.Column('config_id', sa.Uuid(), nullable=False), + sa.Column('advanced_settings_id', sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint(['advanced_settings_id'], ['advanced_settings.id'], ), + sa.ForeignKeyConstraint(['config_id'], ['calculation_configs.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('calculation_set_configs', + sa.Column('calculation_set_id', sa.Uuid(), nullable=False), + sa.Column('config_id', sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint(['calculation_set_id'], ['calculation_sets.id'], ), + sa.ForeignKeyConstraint(['config_id'], ['calculation_configs.id'], ), + sa.PrimaryKeyConstraint('calculation_set_id', 'config_id'), + sa.UniqueConstraint('calculation_set_id', 'config_id') + ) + op.create_table('calculation_set_stats', + sa.Column('calculation_set_id', sa.Uuid(), nullable=False), + sa.Column('molecule_set_id', sa.VARCHAR(length=100), nullable=False), + sa.ForeignKeyConstraint(['calculation_set_id'], ['calculation_sets.id'], ), + sa.ForeignKeyConstraint(['molecule_set_id'], ['molecule_set_stats.file_hash'], ), + sa.PrimaryKeyConstraint('calculation_set_id', 'molecule_set_id'), + sa.UniqueConstraint('calculation_set_id', 'molecule_set_id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """"""Downgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('calculation_set_stats') + op.drop_table('calculation_set_configs') + op.drop_table('calculations') + op.drop_table('calculation_sets') + op.drop_table('atom_type_counts') + op.drop_table('users') + op.drop_table('molecule_set_stats') + op.drop_table('calculation_configs') + op.drop_table('advanced_settings') + # ### end Alembic commands ### +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/alembic/versions/2be8d29189d7_calculationsetstats_delete_cascade.py",".py","769","33","""""""CalculationSetStats delete cascade + +Revision ID: 2be8d29189d7 +Revises: aa87655da208 +Create Date: 2025-04-24 22:16:33.726789 + +"""""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '2be8d29189d7' +down_revision: Union[str, None] = 'aa87655da208' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """"""Upgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + """"""Downgrade schema."""""" + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/schemas/user.py",".py","606","23","import uuid + +import sqlalchemy as sa +from sqlalchemy.orm import Mapped, relationship, mapped_column + +from db.schemas import Base + + +class User(Base): + """"""User model. It only stores openid of the user."""""" + + __tablename__ = ""users"" + + id: Mapped[str] = mapped_column(sa.Uuid, primary_key=True, default=uuid.uuid4) + openid: Mapped[str] = mapped_column(sa.VARCHAR(100), nullable=False) + + calculation_sets = relationship( + ""CalculationSet"", back_populates=""user"", cascade=""all, delete-orphan"" + ) + + def __repr__(self) -> str: + return f"""" +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/schemas/__init__.py",".py","96","5","from sqlalchemy.orm import declarative_base + +Base = declarative_base() +metadata = Base.metadata +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/db/schemas/stats.py",".py","1907","53","import uuid + +import sqlalchemy as sa +from sqlalchemy.orm import Mapped, relationship, mapped_column + +from db.schemas import Base + + +class AtomTypeCount(Base): + """"""Atom type count database model."""""" + + __tablename__ = ""atom_type_counts"" + + id: Mapped[str] = mapped_column(sa.Uuid, primary_key=True, default=uuid.uuid4) + symbol: Mapped[str] = mapped_column(sa.VARCHAR(10), primary_key=False) + count: Mapped[int] = mapped_column(sa.Integer, nullable=False) + + molecule_set_id = mapped_column( + sa.VARCHAR(100), sa.ForeignKey(""molecule_set_stats.file_hash""), nullable=False + ) + molecule_set_stats = relationship(""MoleculeSetStats"", back_populates=""atom_type_counts"") + + def __repr__(self): + return f"""""" str: + return f"""" + + +class CalculationSetConfig(Base): + """"""M:N relationship table between CalculationSet and CalculationConfig"""""" + + __tablename__ = ""calculation_set_configs"" + + calculation_set_id: Mapped[str] = mapped_column( + sa.Uuid, sa.ForeignKey(""calculation_sets.id""), nullable=False, primary_key=True + ) + config_id: Mapped[str] = mapped_column( + sa.Uuid, sa.ForeignKey(""calculation_configs.id""), nullable=False, primary_key=True + ) + + def __repr__(self) -> str: + return f"""" + + __table_args__ = (sa.UniqueConstraint(""calculation_set_id"", ""config_id""),) + + +class CalculationConfig(Base): + """"""Calculation config database model. It represents a single calculation configuration."""""" + + __tablename__ = ""calculation_configs"" + + id: Mapped[str] = mapped_column(sa.Uuid, primary_key=True, default=uuid.uuid4) + method: Mapped[str] = mapped_column(sa.VARCHAR(20), nullable=False) + parameters: Mapped[str | None] = mapped_column(sa.VARCHAR(50), nullable=True) + + calculation_sets = relationship( + ""CalculationSet"", secondary=""calculation_set_configs"", back_populates=""configs"" + ) + calculations = relationship(""Calculation"", back_populates=""config"") + + def __repr__(self) -> str: + return ( + f"""" + ) + + __table_args__ = (sa.UniqueConstraint(""method"", ""parameters""),) + + def __eq__(self, other): + return self.method == other.method and self.parameters == other.parameters + + +class CalculationSetStats(Base): + """"""M:N relationship table between CalculationSet and MoleculeSetStats"""""" + + __tablename__ = ""calculation_set_stats"" + + calculation_set_id: Mapped[str] = mapped_column( + sa.Uuid, sa.ForeignKey(""calculation_sets.id""), primary_key=True + ) + molecule_set_id: Mapped[str] = mapped_column( + sa.VARCHAR(100), sa.ForeignKey(""molecule_set_stats.file_hash""), primary_key=True + ) + + file_name: Mapped[str] = mapped_column(sa.VARCHAR(255), nullable=True) + + calculation_set = relationship( + ""CalculationSet"", back_populates=""molecule_set_stats_associations"" + ) + molecule_set = relationship(""MoleculeSetStats"", back_populates=""calculation_set_associations"") + + def __repr__(self) -> str: + return f"""" + + __table_args__ = (sa.UniqueConstraint(""calculation_set_id"", ""molecule_set_id""),) + + +class Calculation(Base): + __tablename__ = ""calculations"" + + id: Mapped[str] = mapped_column(sa.Uuid, primary_key=True, default=uuid.uuid4) + file_name: Mapped[str] = mapped_column(sa.VARCHAR(255), nullable=False) + file_hash: Mapped[str] = mapped_column(sa.VARCHAR(100), nullable=False) + charges: Mapped[dict] = mapped_column(sa.JSON, nullable=False) + + config_id: Mapped[str] = mapped_column( + sa.Uuid, sa.ForeignKey(""calculation_configs.id""), nullable=False + ) + advanced_settings_id: Mapped[str] = mapped_column( + sa.Uuid, sa.ForeignKey(""advanced_settings.id""), nullable=False + ) + + config = relationship(""CalculationConfig"", back_populates=""calculations"") + advanced_settings = relationship(""AdvancedSettings"", back_populates=""calculations"") + + def __repr__(self) -> str: + return f"""" + + +class AdvancedSettings(Base): + __tablename__ = ""advanced_settings"" + + id: Mapped[str] = mapped_column(sa.Uuid, primary_key=True, default=uuid.uuid4) + read_hetatm: Mapped[bool] = mapped_column(sa.Boolean, nullable=False) + ignore_water: Mapped[bool] = mapped_column(sa.Boolean, nullable=False) + permissive_types: Mapped[bool] = mapped_column(sa.Boolean, nullable=False) + + calculation_sets = relationship(""CalculationSet"", back_populates=""advanced_settings"") + calculations = relationship(""Calculation"", back_populates=""advanced_settings"") + + def __repr__(self): + return f"""""" None: + page = page if page > 0 else PagedList._DEFAULT_PAGE + page_size = page_size if page_size > 0 else PagedList._DEFAULT_PAGE_SIZE + + total_pages = PagedList._get_total_pages(total_count, page_size) + + super().__init__( + items=items, + page=page, + page_size=page_size, + total_count=total_count, + total_pages=total_pages, + ) + + @staticmethod + def _get_total_pages(total_count: int, page_size: int) -> int: + """""" + Calculate the total number of pages. + + Returns: + int: Total number of pages. + """""" + return (total_count + page_size - 1) // page_size +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/models/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/models/molecule_info.py",".py","1307","48","from typing import Any + +from pydantic import BaseModel, ConfigDict +from pydantic.alias_generators import to_camel + + +class AtomTypeCount(BaseModel): + """"""Counts of atom types."""""" + + symbol: str + count: int + + def __init__(self, type_counts: dict[str, Any]) -> None: + super().__init__(symbol=type_counts.get(""symbol"", """"), count=type_counts.get(""count"", 0)) + + model_config = ConfigDict( + alias_generator=to_camel, + populate_by_name=True, + from_attributes=True, + ) + + +class MoleculeSetStats(BaseModel): + """"""Information about the molecules in the provided file."""""" + + total_molecules: int + total_atoms: int + atom_type_counts: list[AtomTypeCount] + + def __init__(self, info: dict[str, Any]) -> None: + super().__init__( + total_molecules=info.get(""total_molecules"", 0), + total_atoms=info.get(""total_atoms"", 0), + atom_type_counts=[AtomTypeCount(c) for c in info.get(""atom_type_counts"", [])], + ) + + @staticmethod + def default() -> ""MoleculeSetStats"": + return MoleculeSetStats( + info={""total_molecules"": 0, ""total_atoms"": 0, ""atom_type_counts"": []} + ) + + model_config = ConfigDict( + alias_generator=to_camel, + populate_by_name=True, + from_attributes=True, + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/models/calculation.py",".py","2427","91","""""""Calculation models"""""" + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Dict +import uuid + +from pydantic import BaseModel, ConfigDict +from pydantic.alias_generators import to_camel + +from models.paging import PagingFilters +from models.molecule_info import MoleculeSetStats + +from models.setup import AdvancedSettingsDto + +Charges = Dict[str, list[float]] + + +@dataclass +class CalculationsFilters: + """"""Filters for calculations retrieval"""""" + + hash: str + method: str + parameters: str | None = None + read_hetatm: bool = True + ignore_water: bool = False + permissive_types: bool = False + paging: PagingFilters = field(default_factory=lambda: PagingFilters(1, 10)) + + +class CalculationConfigDto(BaseModel): + """"""Calculation configuration data transfer object"""""" + + method: str | None = None + parameters: str | None = None + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + __hash__ = object.__hash__ + + +class CalculationDto(BaseModel): + """"""Calculation data transfer object"""""" + + file: str + file_hash: str + charges: Charges + config: CalculationConfigDto + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + + +class CalculationPreviewDto(BaseModel): + """"""Calculation preview data transfer object"""""" + + file: str + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + + +class CalculationSetDto(BaseModel): + """"""Calculation set data transfer object"""""" + + id: uuid.UUID + calculations: list[CalculationDto] + configs: list[CalculationConfigDto] + settings: AdvancedSettingsDto + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + + +class CalculationSetPreviewDto(BaseModel): + """"""Calculation set preview data transfer object"""""" + + id: uuid.UUID + files: dict[str, MoleculeSetStats] + configs: list[CalculationConfigDto] + settings: AdvancedSettingsDto + created_at: datetime + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + + +class CalculationResultDto(BaseModel): + """"""Result of charge calculation"""""" + + config: CalculationConfigDto + calculations: list[CalculationDto] + + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/models/method.py",".py","274","15","from dataclasses import dataclass +from typing import Literal + + +@dataclass(frozen=True) +class Method: + """"""Method model."""""" + + name: str + internal_name: str + full_name: str + publication: str | None + type: Literal[""2D"", ""3D"", ""other""] + has_parameters: bool +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/models/suitable_methods.py",".py","266","13","from dataclasses import dataclass + +from models.method import Method +from models.parameters import Parameters + + +@dataclass +class SuitableMethods: + """"""Result of suitable methods calculation."""""" + + methods: list[Method] + parameters: dict[str, list[Parameters]] +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/container.py",".py","3524","91","""""""Dependency injection container."""""" + +import os + +from dependency_injector import containers, providers +from dotenv import load_dotenv, find_dotenv + + +from db.database import Database, SessionManager +from db.repositories import advanced_settings_repository +from db.repositories.calculation_config_repository import CalculationConfigRepository +from db.repositories.calculation_repository import CalculationRepository +from db.repositories.calculation_set_repository import CalculationSetRepository +from db.repositories.user_repository import UserRepository +from db.repositories.moleculeset_stats_repository import MoleculeSetStatsRepository + +from integrations.chargefw2.chargefw2 import ChargeFW2Local +from integrations.io.io import IOLocal + +from services.calculation_storage import CalculationStorageService +from services.chargefw2 import ChargeFW2Service +from services.file_storage import FileStorageService +from services.io import IOService +from services.logging.file_logger import FileLogger +from services.mmcif import MmCIFService +from services.oidc import OIDCService + + +load_dotenv(find_dotenv()) + + +class Container(containers.DeclarativeContainer): + """"""IoC container for the application."""""" + + wiring_config = containers.WiringConfiguration(packages=[""api"", ""services""]) + + # integrations + chargefw2 = providers.Singleton(ChargeFW2Local) + io = providers.Singleton(IOLocal) + + # database + db = providers.Singleton(Database, db_url=os.environ.get(""ACC_DB_URL"")) + session_manager = providers.Singleton( + SessionManager, session_factory=db.provided.session_factory + ) + + # repositories + set_repository = providers.Factory(CalculationSetRepository) + calculation_repository = providers.Factory(CalculationRepository, set_repository=set_repository) + config_repository = providers.Factory( + CalculationConfigRepository, set_repository=set_repository + ) + user_repository = providers.Factory(UserRepository, session_manager=session_manager) + stats_repository = providers.Factory(MoleculeSetStatsRepository) + advanced_settings_repository = providers.Factory( + advanced_settings_repository.AdvancedSettingsRepository, + ) + + # services + logger_service = providers.Singleton(FileLogger) + io_service = providers.Singleton(IOService, logger=logger_service, io=io) + mmcif_service = providers.Singleton(MmCIFService, logger=logger_service, io=io_service) + storage_service = providers.Singleton( + CalculationStorageService, + logger=logger_service, + set_repository=set_repository, + calculation_repository=calculation_repository, + config_repository=config_repository, + stats_repository=stats_repository, + advanced_settings_repository=advanced_settings_repository, + session_manager=session_manager, + ) + file_storage_service = providers.Singleton( + FileStorageService, + logger=logger_service, + io=io_service, + session_manager=session_manager, + storage_service=storage_service, + ) + chargefw2_service = providers.Singleton( + ChargeFW2Service, + chargefw2=chargefw2, + logger=logger_service, + io=io_service, + mmcif_service=mmcif_service, + calculation_storage=storage_service, + max_workers=int(os.environ.get(""ACC_MAX_WORKERS"") or 4), + max_concurrent_calculations=int(os.environ.get(""ACC_MAX_CONCURRENT_CALCULATIONS"") or 4), + ) + oidc_service = providers.Singleton(OIDCService, logger=logger_service) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/constants.py",".py","226","8","""""""Api related constants."""""" + +# Allowed file types for computation +ALLOWED_FILE_TYPES = [""cif"", ""mol2"", ""pdb"", ""mmcif"", ""sdf""] + +# Extension of output cif files containing computed charges +CHARGES_OUTPUT_EXTENSION = "".fw2.cif"" +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/exceptions.py",".py","668","21","""""""Custom HTTP exceptions for the application."""""" + +from typing import Any +from fastapi import HTTPException, status + + +class BadRequestError(HTTPException): + """"""Exception for 400 Bad Request errors."""""" + + def __init__( + self, status_code: int, detail: str, headers: dict[str, Any] | None = None + ) -> None: + super().__init__(status_code=status_code, detail=detail, headers=headers) + + +class NotFoundError(HTTPException): + """"""Exception for 404 Not Found errors."""""" + + def __init__(self, detail: str, headers: dict[str, Any] | None = None) -> None: + super().__init__(status_code=status.HTTP_404_NOT_FOUND, detail=detail, headers=headers) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/routes/files.py",".py","11562","338","""""""File manipulation routes."""""" + +import asyncio +import traceback + +import pathlib + +from typing import Annotated, Literal +from fastapi import Depends, Path, Query, Request, UploadFile, status +from fastapi.responses import FileResponse +from fastapi.routing import APIRouter +from dependency_injector.wiring import inject, Provide + +from api.v1.constants import ALLOWED_FILE_TYPES +from api.v1.container import Container +from api.v1.schemas.response import Response, ResponseError +from api.v1.schemas.file import QuotaResponse, UploadResponse, FileResponse as FileResponseModel +from api.v1.exceptions import BadRequestError, NotFoundError + +from models.paging import PagedList + + +from services.file_storage import FileStorageService +from services.chargefw2 import ChargeFW2Service +from services.calculation_storage import CalculationStorageService +from services.io import IOService + +files_router = APIRouter(prefix=""/files"", tags=[""files""]) + +# --- Public API handlers --- + + +@files_router.post( + ""/upload"", + description=""Stores the provided files on disk and returns their hashes that can be used for further operations. "" + + f""Allowed file types are {', '.join(ALLOWED_FILE_TYPES)}."", + responses={ + 413: { + ""description"": ""File too large."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": { + ""success"": False, + ""message"": ""Unable to upload files. One or more files are too large."", + } + } + }, + }, + 400: { + ""description"": ""Invalid file type."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": { + ""success"": False, + ""message"": f""Invalid file type. Allowed file types are {', '.join(ALLOWED_FILE_TYPES)}"", + } + } + }, + }, + }, +) +@inject +async def upload( + request: Request, + files: list[UploadFile], + io: IOService = Depends(Provide[Container.io_service]), + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[list[UploadResponse]]: + """"""Stores the provided files on disk and returns the computation id."""""" + + def clear_stored_files(files: list[str]) -> None: + for file in files: + io.remove_file(file) + + try: + io.ensure_upload_files_provided(files) + io.ensure_upload_files_sizes_valid(files) + io.ensure_uploaded_file_types_valid(files) + + upload_size_b = sum((file.size or 0) for file in files) + user_id = str(request.state.user.id) if request.state.user is not None else None + + io.ensure_quota_not_exceeded(upload_size_b, user_id) + + workdir = io.get_file_storage_path(user_id) + io.create_dir(workdir) + + stored_files = await asyncio.gather( + *[io.store_upload_file(file, workdir) for file in files] + ) + + for [path, file_hash] in stored_files: + try: + info = await chargefw2.info(path) + except RuntimeError: + # Remove files that were uploaded if an error occurs + clear_stored_files([path for [path, _] in stored_files]) + _, filename = io.parse_filename(pathlib.Path(path).name) + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f""Unable to load molecules from file '{filename}'."", + ) + + storage_service.store_file_info(file_hash, info) + + data = [ + UploadResponse(file=io.parse_filename(pathlib.Path(name).name)[1], file_hash=file_hash) + for [name, file_hash] in stored_files + ] + + return Response(data=data) + except BadRequestError as e: + raise e + except Exception as e: + traceback.print_exc() + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Error uploading files."", + ) from e + + +@files_router.get( + ""/download/computation/{computation_id}"", + responses={ + 200: {""description"": ""Successful response."", ""content"": {""application/zip"": {}}}, + 404: { + ""description"": ""Computation not found"", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Computation not found.""} + } + }, + }, + 400: { + ""description"": ""Error downloading charges."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Error downloading charges.""} + } + }, + }, + }, +) +@inject +async def download_charges( + request: Request, + computation_id: Annotated[str, Path(description=""UUID of the computation."")], + io: IOService = Depends(Provide[Container.io_service]), +) -> FileResponse: + """"""Returns a zip file with all charges for the provided computation."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + charges_path = io.get_charges_path(computation_id, user_id) + if not io.path_exists(charges_path): + raise FileNotFoundError() + + archive_path = io.zip_charges(charges_path) + + return FileResponse(path=archive_path, media_type=""application/zip"") + except FileNotFoundError as e: + raise NotFoundError(detail=f""Computation '{computation_id}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error downloading charges."" + ) from e + + +@files_router.get( + ""/download/file/{file_hash}"", + responses={ + 404: { + ""description"": ""File not found."", + ""model"": ResponseError, + ""content"": { + ""application/json"": {""example"": {""success"": False, ""message"": ""File not found.""}} + }, + }, + 400: { + ""description"": ""Error downloading file."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Error downloading file.""} + } + }, + }, + }, +) +@inject +async def download_file( + request: Request, + file_hash: Annotated[str, Path(description=""Hash of the file to download."")], + io: IOService = Depends(Provide[Container.io_service]), +) -> FileResponse: + """"""Returns a zip file with all charges for the provided computation."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + file_path = io.get_filepath(file_hash, user_id) + if not io.path_exists(file_path or """"): + raise FileNotFoundError() + + return FileResponse(path=file_path or """", media_type=""application/octet-stream"") + except FileNotFoundError as e: + raise NotFoundError(detail=f""File '{file_hash}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error downloading file."" + ) from e + + +# --- Route handlers used by ACC II Web --- + + +@files_router.get(path="""", include_in_schema=False) +@inject +async def get_files( + request: Request, + page: Annotated[int, Query(description=""Page number"", ge=1)] = 1, + page_size: Annotated[int, Query(description=""Number of items per page"", ge=1)] = 10, + order_by: Annotated[ + Literal[""name"", ""uploaded_at"", ""size""], Query(description=""Order by"") + ] = ""uploaded_at"", + search: Annotated[str, Query(description=""Search term"")] = """", + order: Annotated[Literal[""asc"", ""desc""], Query(description=""Order direction."")] = ""desc"", + storage_service: FileStorageService = Depends(Provide[Container.file_storage_service]), +) -> Response[PagedList[FileResponseModel]]: + """"""Returns the list of files uploaded by the user.."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is None: + raise BadRequestError( + status_code=status.HTTP_403_FORBIDDEN, + detail=""You need to be logged in to get files."", + ) + + try: + data = storage_service.get_files( + order_by=order_by, + order=order, + page=page, + page_size=page_size, + search=search, + user_id=user_id, + ) + + return Response(data=data) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Error getting files."", + ) from e + + +@files_router.get(""/download/examples/{example_id}"", include_in_schema=False) +@inject +async def download_example( + example_id: Annotated[str, Path(description=""ID of the example."", example=""phenols"")], + io: IOService = Depends(Provide[Container.io_service]), +) -> FileResponse: + try: + charges_path = io.get_example_path(example_id) + if not io.path_exists(charges_path): + raise FileNotFoundError() + + archive_path = io.zip_charges(charges_path) + + return FileResponse(path=archive_path, media_type=""application/zip"") + except FileNotFoundError as e: + raise NotFoundError(detail=f""Example '{example_id}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while downloading example."", + ) from e + + +@files_router.get(""/quota"", include_in_schema=False) +@inject +async def get_quota( + request: Request, + io: IOService = Depends(Provide[Container.io_service]), +) -> Response[QuotaResponse]: + """"""Returns the quota of the user."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is None: + raise BadRequestError( + status_code=status.HTTP_403_FORBIDDEN, + detail=""You need to be logged in to see quota."", + ) + + try: + used, available, quota = io.get_quota(user_id) + return Response(data=QuotaResponse(used_space=used, available_space=available, quota=quota)) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Error getting files."", + ) from e + + +@files_router.delete(""/{file_hash}"", include_in_schema=False) +@inject +async def delete_file( + request: Request, + file_hash: Annotated[str, Path(description=""UUID of the file to delete."")], + io: IOService = Depends(Provide[Container.io_service]), +) -> Response[None]: + """"""Deletes all files uploaded by the user."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is None: + raise BadRequestError( + status_code=status.HTTP_403_FORBIDDEN, + detail=""You need to be logged in to delete files."", + ) + + try: + io.remove_file(file_hash, user_id) + return Response(data=None) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Error deleting files."", + ) from e +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/routes/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/routes/auth.py",".py","4363","136","""""""Life Science auth routes implementing the OpenID Connect protocol."""""" + +import urllib +import urllib.parse + +import httpx +from api.v1.container import Container +from api.v1.schemas.response import Response +from api.v1.schemas.auth import TokenResponse +from db.schemas.user import User +from db.repositories.user_repository import UserRepository +from dependency_injector.wiring import Provide, inject +from fastapi import Depends, HTTPException, Request, status +from fastapi.responses import RedirectResponse +from fastapi.routing import APIRouter +from services.oidc import OIDCService + + +auth_router = APIRouter(prefix=""/auth"", tags=[""auth""], include_in_schema=False) + + +@auth_router.get(""/login"", tags=[""login""]) +@inject +async def login(oidc_service: OIDCService = Depends(Provide[Container.oidc_service])): + """"""Initiate the OIDC authentication flow."""""" + + config = await oidc_service.get_oidc_config() + auth_endpoint = config[""authorization_endpoint""] + + params = { + ""response_type"": ""code"", + ""client_id"": oidc_service.client_id, + ""scope"": ""openid"", + ""redirect_uri"": oidc_service.redirect_url, + } + query = urllib.parse.urlencode(params) + + return RedirectResponse(f""{auth_endpoint}?{query}"") + + +@auth_router.get(""/logout"", tags=[""logout""]) +@inject +async def logout( + request: Request, oidc_service: OIDCService = Depends(Provide[Container.oidc_service]) +): + """"""Log out the user."""""" + + config = await oidc_service.get_oidc_config() + token = request.cookies.get(""access_token"") + redirect_uri = oidc_service.base_url + + response = RedirectResponse(redirect_uri) + + # end_session_endpoint prompts user to end the session on the LS side + if ""end_session_endpoint"" in config: + end_session_endpoint = config[""end_session_endpoint""] + params = { + ""client_id"": oidc_service.client_id, + ""post_logout_redirect_uri"": redirect_uri, + } + + if token: + params[""id_token_hint""] = token + + query = urllib.parse.urlencode(params) + response = RedirectResponse(f""{end_session_endpoint}?{query}"") + + response.delete_cookie(""access_token"", secure=True, httponly=True, path=""/"") + + return response + + +@auth_router.get(""/callback"", tags=[""callback""]) +@inject +async def auth_callback( + code: str, + oidc_service: OIDCService = Depends(Provide[Container.oidc_service]), + user_repository: UserRepository = Depends(Provide[Container.user_repository]), +): + """"""Handle the callback from the OIDC provider. This function is triggered after succcessful LS login."""""" + + config = await oidc_service.get_oidc_config() + token_endpoint = config[""token_endpoint""] + + async with httpx.AsyncClient() as client: + response = await client.post( + token_endpoint, + data={ + ""grant_type"": ""authorization_code"", + ""code"": code, + ""redirect_uri"": oidc_service.redirect_url, + }, + headers={""Content-Type"": ""application/x-www-form-urlencoded""}, + auth=httpx.BasicAuth( + username=oidc_service.client_id, + password=oidc_service.client_secret, + ), + ) + + if response.status_code != 200: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=f""Failed to get token: {response.text}"", + ) + + tokens = TokenResponse(**response.json()) + + payload = await oidc_service.verify_token(tokens.access_token) + + if not payload: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=""Failed to verify token"", + ) + + # create user if does not exist + openid = payload[""sub""] + user = user_repository.get(openid) + if user is None: + user = User(openid=openid) + user_repository.store(user) + + # set session cookie + response = RedirectResponse(url=oidc_service.base_url) + response.set_cookie(""access_token"", tokens.access_token, secure=True, httponly=True) + + return response + + +@auth_router.get(""/verify"", tags=[""verify""]) +async def verify(request: Request): + """"""Verifies if user is logged in."""""" + + user = request.state.user + return Response(data={""isAuthenticated"": user is not None}) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/routes/charges.py",".py","26318","697","""""""Charge calculation routes."""""" + +import uuid + + +from typing import Annotated, Literal +from fastapi import Depends, HTTPException, Path, Query, Request, status +from fastapi.responses import FileResponse +from fastapi.routing import APIRouter +from dependency_injector.wiring import inject, Provide + +from api.v1.exceptions import BadRequestError, NotFoundError +from api.v1.schemas.response import Response, ResponseError + +from models.calculation import ( + CalculationConfigDto, + CalculationResultDto, + CalculationSetPreviewDto, +) +from models.method import Method +from models.molecule_info import MoleculeSetStats +from models.paging import PagedList +from models.parameters import Parameters +from models.suitable_methods import SuitableMethods + +from db.repositories.calculation_set_repository import CalculationSetFilters + +from api.v1.container import Container +from api.v1.schemas.charges import ( + BestParametersRequest, + CalculateChargesRequest, + SetupRequest, + StatsRequest, + SuitableMethodsRequest, +) + +from models.setup import AdvancedSettingsDto + +from services.calculation_storage import CalculationStorageService +from services.mmcif import MmCIFService +from services.io import IOService +from services.chargefw2 import ChargeFW2Service + +charges_router = APIRouter(prefix=""/charges"", tags=[""charges""]) + +# --- Public API handlers --- + + +@charges_router.get(""/methods/available"") +@inject +async def available_methods( + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[list[Method]]: + """"""Returns the list of available methods for charge calculation."""""" + + try: + methods = chargefw2.get_available_methods() + return Response[list[Method]](data=methods) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Error getting available methods."", + ) from e + + +@charges_router.post(""/methods/suitable"") +@inject +async def suitable_methods( + request: Request, + data: SuitableMethodsRequest, + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[SuitableMethods]: + """""" + Returns suitable methods for the provided computation. + + fileHashes: List of file hashes to get suitable methods for. + permissiveTypes: Use similar parameters for similar atom/bond types if no exact match is found. + """""" + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + suitable = await chargefw2.get_suitable_methods( + data.file_hashes, data.permissive_types, user_id + ) + return Response(data=suitable) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error getting suitable methods."" + ) from e + + +@charges_router.get( + ""/parameters/{method_name}/available"", + responses={ + 404: { + ""description"": ""Method not found."", + ""model"": ResponseError, + ""content"": { + ""application/json"": {""example"": {""success"": False, ""message"": ""Method not found.""}} + }, + }, + 400: { + ""description"": ""Error getting available parameters."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Error getting available parameters.""} + } + }, + }, + }, +) +@inject +async def available_parameters( + method_name: Annotated[ + str, + Path( + description="""""" + Method name to get parameters for. + One of the available methods (list can be received from GET ""/api/v1/methods/available""). + """""" + ), + ], + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[list[Parameters]]: + """"""Returns the list of available parameters for the provided method."""""" + + methods = chargefw2.get_available_methods() + if not any(method.internal_name == method_name for method in methods): + raise BadRequestError( + status_code=status.HTTP_404_NOT_FOUND, + detail=f""Method '{method_name}' not found."", + ) + + try: + parameters = await chargefw2.get_available_parameters(method_name) + return Response[list[Parameters]](data=parameters) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f""Error getting available parameters for method '{method_name}'."", + ) from e + + +@charges_router.post( + ""/parameters/best"", + responses={ + 404: { + ""description"": ""Method not found."", + ""model"": ResponseError, + ""content"": { + ""application/json"": {""example"": {""success"": False, ""message"": ""Method not found.""}} + }, + }, + 400: { + ""description"": ""Error getting best parameters."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Error getting best parameters.""} + } + }, + }, + }, +) +@inject +async def best_parameters( + data: BestParametersRequest, + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), + io_service: IOService = Depends(Provide[Container.io_service]), +) -> Response[Parameters]: + """""" + Returns the best parameters for the provided method and file. + + methodName: Method name to get the best parameters for. + fileHash: File hashes to get suitable methods for. + permissiveTypes: Use similar parameters for similar atom/bond types if no exact match is found. + """""" + + methods = chargefw2.get_available_methods() + if not any(method.internal_name == data.method_name for method in methods): + raise BadRequestError( + status_code=status.HTTP_404_NOT_FOUND, + detail=f""Method '{data.method_name}' not found."", + ) + + file_path = io_service.get_filepath(data.file_hash) + + if file_path is None: + raise BadRequestError( + status_code=status.HTTP_404_NOT_FOUND, + detail=f""File '{data.file_hash}' not found."", + ) + + try: + parameters = await chargefw2.get_best_parameters( + data.method_name, file_path, data.permissive_types + ) + return Response[Parameters](data=parameters) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f""Error getting best parameters for method '{data.method_name}'."", + ) from e + + +@charges_router.post( + ""/stats"", + responses={ + 404: { + ""description"": ""File not found."", + ""model"": ResponseError, + ""content"": { + ""application/json"": {""example"": {""success"": False, ""message"": ""File not found.""}} + }, + }, + 400: { + ""description"": ""Error getting file information."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": {""success"": False, ""message"": ""Error getting file information.""} + } + }, + }, + }, +) +@inject +async def info( + request: Request, + data: StatsRequest, + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), + io_service: IOService = Depends(Provide[Container.io_service]), +) -> Response[MoleculeSetStats]: + """""" + Returns information about the provided file. + Number of molecules, total atoms and individual atoms. + + fileHash: File hashes to get suitable methods for. + """""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + filepath = io_service.get_filepath(data.file_hash, user_id) + + if filepath is None: + raise FileNotFoundError() + + info_data = await chargefw2.info(filepath) + + return Response(data=info_data) + except FileNotFoundError as e: + raise NotFoundError(detail=""File not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error getting file information."" + ) from e + + +@charges_router.post( + ""/calculate"", + responses={ + 200: { + ""description"": ""Charges calculated successfully."", + ""content"": { + ""application/json"": { + ""example"": { + ""success"": True, + ""data"": { + ""computationId"": ""0b9ee9e0-bd69-409d-a3af-3bf11666ee86"", + ""results"": [ + { + ""calculations"": [ + { + ""file"": ""file_name.cif"", + ""fileHash"": ""4d689a346c6e852f21e3083025d827d7ba165c7c468d8a3c970216e9365fb3bd"", + ""charges"": { + ""molecule1"": [0.1, 0.2], + ""molecule2"": [0.3, 0.4], + }, + ""config"": { + ""method"": ""sqeqp"", + ""parameters"": ""SQEqp_10_Schindler2021_CCD_gen"", + }, + } + ], + } + ], + }, + } + } + }, + }, + 413: { + ""description"": ""Unable to calculate charges. Calculation is too large."", + ""model"": ResponseError, + ""content"": { + ""application/json"": { + ""example"": { + ""success"": False, + ""message"": ""Unable to calculate charges. Calculation is too large."", + } + } + }, + }, + 400: { + ""description"": ""No files provided."", + ""model"": ResponseError, + ""content"": { + ""application/json"": {""example"": {""success"": False, ""message"": ""No files provided.""}} + }, + }, + }, +) +@inject +async def calculate_charges( + request: Request, + data: CalculateChargesRequest, + response_format: Annotated[ + Literal[""charges"", ""none""], Query(description=""Output format."") + ] = ""charges"", + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), + mmcif_service: MmCIFService = Depends(Provide[Container.mmcif_service]), + io_service: IOService = Depends(Provide[Container.io_service]), +): + """""" + Calculates partial atomic charges for files in the provided directory. + Returns a list of dictionaries with charges (decimal numbers). + If no config is provided, the most suitable method and its parameters will be used. + + configs: List of combinations of suitable methods and parameters. + fileHashes: List of file hashes to calculate charges for. + + settings: + + readHetatm: Read HETATM records from PDB/mmCIF files. + ignoreWater: Discard water molecules from PDB/mmCIF files. + permissiveTypes: Use similar parameters for similar atom/bond types if no exact match is found. + + """""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is not None: + _, available_b, quota_b = io_service.get_quota(user_id) + if available_b <= 0: + quota_mb = quota_b / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=""Unable to calculate charges. Quota exceeded. "" + + f""Maximum storage space is {quota_mb} MB."", + ) + + computation_id = data.computation_id or str(uuid.uuid4()) + calculation_set = storage_service.get_calculation_set(computation_id) + + if not data.file_hashes and calculation_set is None: + # if no file hashes provided and computation has not been set up + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""No file hashes provided."", + ) + + settings = calculation_set.advanced_settings if calculation_set is not None else data.settings + + if settings is None: + settings = AdvancedSettingsDto() + + try: + io_service.prepare_inputs(user_id, computation_id, data.file_hashes) + + if not data.file_hashes: + # get all files if none provided and computation has already been set up + inputs_path = io_service.get_inputs_path(computation_id, user_id) + data.file_hashes = [ + io_service.parse_filename(file)[0] for file in io_service.listdir(inputs_path) + ] + + if not data.file_hashes: + # no files found and provided + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""No file hashes provided."", + ) + + data.file_hashes = list(set(data.file_hashes)) + + total_size = sum( + io_service.get_file_size(file_hash, user_id) or 0 for file_hash in data.file_hashes + ) + + if total_size > io_service.max_file_size: + max_file_size_mb = io_service.max_file_size / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=""Unable to calculate charges. Calculation is too large. "" + + f""Maximum allowed size is {max_file_size_mb} MB."", + ) + + configs = data.configs + if not configs: + # use most suitable method and parameters if none provided + suitable = await chargefw2.get_computation_suitable_methods(computation_id, user_id) + + if len(suitable.methods) == 0: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""No suitable methods found."" + ) + + method_name = suitable.methods[0].internal_name + parameters = suitable.parameters.get(method_name, []) + parameters_name = parameters[0].internal_name if len(parameters) > 0 else None + + configs = [CalculationConfigDto(method=method_name, parameters=parameters_name)] + + # split calculations into those that need to be calculated and those that are cached + to_calculate, cached = storage_service.filter_existing_calculations( + settings, data.file_hashes, configs + ) + calculations = await chargefw2.calculate_charges( + computation_id, settings, to_calculate, user_id + ) + + # add cached items to results + for result in calculations: + if result.config in cached: + result.calculations.extend(cached[result.config]) + + calculations.extend( + [ + CalculationResultDto(config=config, calculations=results) + for config, results in cached.items() + ] + ) + + storage_service.store_calculation_results(computation_id, settings, calculations, user_id) + await chargefw2.save_charges(settings, computation_id, calculations, user_id) + _ = mmcif_service.write_to_mmcif(user_id, computation_id, calculations) + + if user_id is None: + # free guest compute space if needed + io_service.free_guest_compute_space() + + if response_format == ""none"": + return Response(data=computation_id) + + return Response(data={""computationId"": computation_id, ""results"": calculations}) + except BadRequestError as e: + raise e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=f""Error calculating charges. {str(e)}"" + ) from e + + +# --- Route handlers used by ACC II Web --- + + +@charges_router.post(""/{computation_id}/methods/suitable"", include_in_schema=False) +@inject +async def computation_suitable_methods( + request: Request, + computation_id: Annotated[str, Path(description=""UUID of the computation."")], + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[SuitableMethods]: + """"""Returns suitable methods for the provided computation."""""" + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + data = await chargefw2.get_computation_suitable_methods( + computation_id, + user_id, + ) + return Response(data=data) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error getting suitable methods."" + ) from e + + +@charges_router.post(""/setup"", include_in_schema=False) +@inject +async def setup( + request: Request, + config: SetupRequest, + io_service: IOService = Depends(Provide[Container.io_service]), + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), +): + """"""Prepares input for computation so it can be run later."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is not None: + _, available_b, quota_b = io_service.get_quota(user_id) + if available_b <= 0: + quota_mb = quota_b / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=""Unable to set up calculation. Quota would be exceeded. "" + + f""Maximum storage space is {quota_mb} MB."", + ) + + total_size = sum( + io_service.get_file_size(file_hash, user_id) or 0 for file_hash in config.file_hashes + ) + + if total_size > io_service.max_file_size: + max_file_size_mb = io_service.max_file_size / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=""Unable to set up calculation. Calculation is too large. "" + + f""Maximum allowed size is {max_file_size_mb} MB."", + ) + + computation_id = str(uuid.uuid4()) + + if config.settings is None: + config.settings = AdvancedSettingsDto() + + try: + io_service.prepare_inputs(user_id, computation_id, config.file_hashes) + storage_service.setup_calculation( + computation_id, config.settings, config.file_hashes, user_id + ) + return Response(data=computation_id) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error setting up calculation."" + ) from e + + +# chemical/x-cif +@charges_router.get(""/{computation_id}/mmcif"", include_in_schema=False) +@inject +async def get_mmcif( + request: Request, + computation_id: Annotated[str, Path(description=""UUID of the computation."")], + molecule: Annotated[str | None, Query(description=""Molecule name."")] = None, + io: IOService = Depends(Provide[Container.io_service]), + mmcif_service: MmCIFService = Depends(Provide[Container.mmcif_service]), + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), +) -> FileResponse: + """"""Returns a mmcif file for the provided molecule in the computation."""""" + + user_id = str(request.state.user.id) if request.state.user is not None else None + + # this is a workaround because molstar is not able to send cookies when fetching mmcif + set_exists = storage_service.get_calculation_set(computation_id) + if set_exists is not None and set_exists.user_id is not None: + user_id = str(set_exists.user_id) + + try: + charges_path = io.get_charges_path(computation_id, user_id) + mmcif_path = mmcif_service.get_molecule_mmcif(charges_path, molecule) + return FileResponse(path=mmcif_path) + except FileNotFoundError as e: + raise NotFoundError(detail=f""MMCIF file for molecule '{molecule}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while getting MMCIF data."", + ) from e + + +@charges_router.get(""/examples/{example_id}/mmcif"", include_in_schema=False) +@inject +async def get_example_mmcif( + example_id: Annotated[str, Path(description=""ID of the example."", example=""phenols"")], + molecule: Annotated[str | None, Query(description=""Molecule name."")] = None, + io: IOService = Depends(Provide[Container.io_service]), + mmcif_service: MmCIFService = Depends(Provide[Container.mmcif_service]), +) -> FileResponse: + """"""Returns a mmcif file for the provided molecule in the example."""""" + try: + examples_path = io.get_example_path(example_id) + mmcif_path = mmcif_service.get_molecule_mmcif(examples_path, molecule) + return FileResponse(path=mmcif_path) + except FileNotFoundError as e: + raise NotFoundError( + detail=f""MMCIF file for molecule '{molecule}' in example '{example_id}' not found."" + ) from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while getting MMCIF data."", + ) from e + + +@charges_router.get(""/{computation_id}/molecules"", include_in_schema=False) +@inject +async def get_molecules( + request: Request, + computation_id: Annotated[str, Path(description=""UUID of the computation."")], + io: IOService = Depends(Provide[Container.io_service]), + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[list[str]]: + """"""Returns the list of molecules in the provided computation."""""" + user_id = str(request.state.user.id) if request.state.user is not None else None + + try: + charges_path = io.get_charges_path(computation_id, user_id) + molecules = chargefw2.get_calculation_molecules(charges_path) + return Response(data=sorted(molecules)) + except FileNotFoundError as e: + raise NotFoundError(detail=f""Computation '{computation_id}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while getting molecules."", + ) from e + + +@charges_router.get(""/examples/{example_id}/molecules"", include_in_schema=False) +@inject +async def get_example_molecules( + example_id: Annotated[str, Path(description=""Id of the example."", example=""phenols"")], + io: IOService = Depends(Provide[Container.io_service]), + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), +) -> Response[list[str]]: + """"""Returns the list of molecules in the provided computation."""""" + try: + charges_path = io.get_example_path(example_id) + molecules = chargefw2.get_calculation_molecules(charges_path) + return Response(data=sorted(molecules)) + except FileNotFoundError as e: + raise NotFoundError(detail=f""Example '{example_id}' not found."") from e + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while getting molecules."", + ) from e + + +@charges_router.get(""/calculations"", include_in_schema=False) +@inject +async def get_calculations( + request: Request, + page: Annotated[int, Query(description=""Page number."")] = 1, + page_size: Annotated[int, Query(description=""Number of items per page."")] = 10, + order_by: Annotated[Literal[""created_at""], Query(description=""Order by field."")] = ""created_at"", + order: Annotated[Literal[""asc"", ""desc""], Query(description=""Order direction."")] = ""desc"", + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), +) -> Response[PagedList[CalculationSetPreviewDto]]: + """"""Returns all calculations stored in the database."""""" + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=""You need to be logged in to get calculations."", + ) + + try: + filters = CalculationSetFilters( + order=order, order_by=order_by, page=page, page_size=page_size, user_id=user_id + ) + calculations = storage_service.get_calculations(filters) + return Response(data=calculations) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""Error getting calculations."" + ) from e + + +@charges_router.delete(""/{computation_id}"", include_in_schema=False) +@inject +async def delete_calculation( + request: Request, + computation_id: Annotated[str, Path(description=""UUID of the computation."")], + chargefw2: ChargeFW2Service = Depends(Provide[Container.chargefw2_service]), + storage_service: CalculationStorageService = Depends(Provide[Container.storage_service]), +) -> Response[None]: + """"""Deletes the computation."""""" + user_id = str(request.state.user.id) if request.state.user is not None else None + + if user_id is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=""You need to be logged in to delete calculations."", + ) + + exists = storage_service.get_calculation_set(computation_id) + + if not exists or str(exists.user_id) != user_id: + raise NotFoundError(detail=""Computation not found."") + + try: + chargefw2.delete_calculation(computation_id, user_id) + return Response(data=None) + except Exception as e: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=""Something went wrong while deleting computation."", + ) from e +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/response.py",".py","352","18","""""""Response schemas for API endpoints."""""" + +from api.v1.schemas.base_response import BaseResponseSchema + + +class Response[T](BaseResponseSchema): + """"""Response schema for a single item."""""" + + success: bool = True + data: T + + +class ResponseError(BaseResponseSchema): + """"""Response schema for errors."""""" + + success: bool = False + message: str +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/base_response.py",".py","386","15","""""""Base response schema for all responses."""""" + +from pydantic import BaseModel, ConfigDict +from pydantic.alias_generators import to_camel + + +class BaseResponseSchema(BaseModel): + """"""Base schema. Also converts snake_case to camelCase property names."""""" + + model_config = ConfigDict( + alias_generator=to_camel, + populate_by_name=True, + from_attributes=True, + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/file.py",".py","593","29","import datetime +from models.molecule_info import MoleculeSetStats +from .base_response import BaseResponseSchema + + +class UploadResponse(BaseResponseSchema): + """"""Response schema for uploading a file(s)."""""" + + file: str + file_hash: str + + +class FileResponse(BaseResponseSchema): + """"""Response schema for listing files."""""" + + file_hash: str + file_name: str + size: int + stats: MoleculeSetStats + uploaded_at: datetime.datetime + + +class QuotaResponse(BaseResponseSchema): + """"""Response schema for getting quota."""""" + + used_space: int + available_space: int + quota: int +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/auth.py",".py","191","12","from pydantic import BaseModel + + +class TokenResponse(BaseModel): + """"""JWT Token response."""""" + + access_token: str + token_type: str + expires_in: int + scope: str + id_token: str +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/schemas/charges.py",".py","1063","40","from pydantic import BaseModel, ConfigDict, Field +from pydantic.alias_generators import to_camel +from pydantic.json_schema import SkipJsonSchema + +from models.calculation import CalculationConfigDto +from models.setup import AdvancedSettingsDto + + +class BaseRequestModel(BaseModel): + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, from_attributes=True) + + +class SuitableMethodsRequest(BaseRequestModel): + file_hashes: list[str] + permissive_types: bool = True + + +class StatsRequest(BaseRequestModel): + file_hash: str + + +class BestParametersRequest(BaseRequestModel): + method_name: str + file_hash: str + permissive_types: bool = True + + +class CalculateChargesRequest(BaseRequestModel): + configs: list[CalculationConfigDto] + file_hashes: list[str] + settings: AdvancedSettingsDto | None = None + + # exclude computation_id from docs + computation_id: SkipJsonSchema[str | None] = Field(None, exclude=True) + + +class SetupRequest(BaseRequestModel): + file_hashes: list[str] + settings: AdvancedSettingsDto | None +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/middleware/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/middleware/exceptions.py",".py","495","15","""""""Provides exception handlers for HTTP exceptions."""""" + +from fastapi import HTTPException, Request +from fastapi.responses import JSONResponse + +from api.v1.schemas.response import ResponseError + + +async def http_exception_handler(_: Request, exception: HTTPException): + """"""Handle HTTP exceptions and return a JSON response with the error message."""""" + return JSONResponse( + status_code=exception.status_code, + content=ResponseError(message=exception.detail).model_dump(), + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/middleware/user_loader.py",".py","1523","44","""""""Provides user loader middleware for the application."""""" + +from typing import Awaitable, Callable + + +from api.v1.container import Container +from db.repositories.user_repository import UserRepository +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import Response + +from services.logging.base import LoggerBase +from services.oidc import OIDCService + +RequestResponseEndpoint = Callable[[Request], Awaitable[Response]] + + +class UserLoaderMiddleware(BaseHTTPMiddleware): + """"""Middleware used for + 1. verifying token + 2. loading user from the database + 3. setting it to the request state."""""" + + def __init__(self, app): + super().__init__(app) + self.logger: LoggerBase = Container.logger_service() + self.oidc_service: OIDCService = Container.oidc_service() + self.user_repository: UserRepository = Container.user_repository() + + async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: + request.state.user = None + cookie = request.cookies.get(""access_token"") + + if cookie: + payload = await self.oidc_service.verify_token(cookie) + if payload: + openid = payload[""sub""] + self.logger.info(f""Request contains valid token, loading user {openid}."") + user = self.user_repository.get(openid) + request.state.user = user + + response = await call_next(request) + return response +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/api/v1/middleware/logging.py",".py","1228","38","""""""Provides logging middleware for the application."""""" + +from datetime import timedelta +from timeit import default_timer as timer +from typing import Awaitable, Callable +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import Response + +from api.v1.container import Container + +from services.logging.base import LoggerBase + +RequestResponseEndpoint = Callable[[Request], Awaitable[Response]] + + +class LoggingMiddleware(BaseHTTPMiddleware): + """"""Middleware for logging requests and responses."""""" + + def __init__(self, app): + super().__init__(app) + self.logger: LoggerBase = Container.logger_service() + + async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: + self.logger.info( + message=f""Request from {request.client.host}: {request.method} {request.url}"" + ) + + start = timer() + response = await call_next(request) + end = timer() + + self.logger.info( + message=f""Response for {request.client.host}: {request.method} {request.url} finished with code {response.status_code} in {timedelta(seconds=end - start)}"" + ) + + return response +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/mmcif.py",".py","4998","139","import os +import pathlib + +from gemmi import cif + +from api.v1.constants import CHARGES_OUTPUT_EXTENSION +from models.calculation import CalculationResultDto + +from services.io import IOService +from services.logging.base import LoggerBase + + +class MmCIFService: + """"""Service for handling mmCIF file operations."""""" + + def __init__(self, logger: LoggerBase, io: IOService): + self.logger = logger + self.io = io + + def write_to_mmcif( + self, user_id: str | None, computation_id: str, calculations: list[CalculationResultDto] + ) -> dict: + """"""Write charges to mmcif files with names corresponding to the input molecules. + + Args: + data (dict): Data to write + calculations (list[ChargeCalculationResult]): List of calculations to write. + + Returns: + dict: Dictionary with ""molecules"" and ""configs"" keys. + """""" + + data = self._transform_calculation_data(calculations) + + configs = data[""configs""] + molecules = list(data[""molecules""]) + for molecule in molecules: + self._write_molecule_to_mmcif(user_id, computation_id, molecule, data) + + return {""molecules"": molecules, ""configs"": configs} + + def get_molecule_mmcif(self, path: str, molecule: str | None) -> str: + """"""Returns a mmcif file for the provided molecule in the provided computation. + + Args: + computation_id (str): Computation id. + molecule (str | None): Molecule name. Will return the first one if not provided. + + Raises: + FileNotFoundError: If the provided path or molecule does not exist. + + Returns: + str: Path to the mmcif file. + """""" + + if not self.io.path_exists(path): + raise FileNotFoundError() + + if molecule is None: + molecules = [ + file for file in self.io.listdir(path) if file.endswith(CHARGES_OUTPUT_EXTENSION) + ] + + if len(molecules) == 0: + raise FileNotFoundError() + + return str(pathlib.Path(path) / molecules[0]) + + path = str(pathlib.Path(path) / f""{molecule.lower()}{CHARGES_OUTPUT_EXTENSION}"") + if not self.io.path_exists(path): + raise FileNotFoundError() + + return path + + def _transform_calculation_data(self, calculations: list[CalculationResultDto]) -> dict: + """"""Transforms input data to a 'molecule-focused' format"""""" + transformed = { + ""molecules"": {}, + ""configs"": [ + { + ""method"": calculation.config.method, + ""parameters"": calculation.config.parameters, + } + for calculation in calculations + ], + } + + for calculation in calculations: + for calculation_part in calculation.calculations: + for molecule, charges in calculation_part.charges.items(): + if molecule not in transformed[""molecules""]: + transformed[""molecules""][molecule] = {""charges"": []} + + transformed[""molecules""][molecule][""charges""].append(charges) + + return transformed + + def _write_molecule_to_mmcif( + self, user_id: str | None, computation_id: str, molecule: str, data: dict + ) -> str: + configs = data[""configs""] + charges = data[""molecules""][molecule][""charges""] + + charges_path = self.io.get_charges_path(computation_id, user_id) + output_file_path = os.path.join(charges_path, f""{molecule.lower()}.fw2.cif"") + + document = cif.read_file(output_file_path) + block = document.sole_block() + + sb_ncbr_partial_atomic_charges_meta_prefix = ""_sb_ncbr_partial_atomic_charges_meta."" + sb_ncbr_partial_atomic_charges_prefix = ""_sb_ncbr_partial_atomic_charges."" + sb_ncbr_partial_atomic_charges_meta_attributes = [""id"", ""type"", ""method""] + sb_ncbr_partial_atomic_charges_attributes = [""type_id"", ""atom_id"", ""charge""] + + block.find_mmcif_category(sb_ncbr_partial_atomic_charges_meta_prefix).erase() + block.find_mmcif_category(sb_ncbr_partial_atomic_charges_prefix).erase() + + metadata_loop = block.init_loop( + sb_ncbr_partial_atomic_charges_meta_prefix, + sb_ncbr_partial_atomic_charges_meta_attributes, + ) + + for type_id, config in enumerate(configs): + method_name = config[""method""] + parameters_name = config[""parameters""] + metadata_loop.add_row( + [f""{type_id + 1}"", ""'empirical'"", f""'{method_name}/{parameters_name}'""] + ) + + charges_loop = block.init_loop( + sb_ncbr_partial_atomic_charges_prefix, sb_ncbr_partial_atomic_charges_attributes + ) + + for type_id, charges in enumerate(charges): + for atom_id, charge in enumerate(charges): + charges_loop.add_row([f""{type_id + 1}"", f""{atom_id + 1}"", f""{charge: .4f}""]) + + block.write_file(output_file_path) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/chargefw2.py",".py","14560","418","""""""ChargeFW2 service module."""""" + +import asyncio +import os +from pathlib import Path +import traceback + +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +from typing import Tuple + + +# Temporary solution to get Molecules class +from chargefw2 import Molecules + +from models.calculation import ( + CalculationDto, + CalculationConfigDto, + CalculationResultDto, +) +from models.molecule_info import MoleculeSetStats +from models.method import Method +from models.parameters import Parameters +from models.setup import AdvancedSettingsDto +from models.suitable_methods import SuitableMethods + +from integrations.chargefw2.base import ChargeFW2Base + +from api.v1.constants import CHARGES_OUTPUT_EXTENSION + + +from services.io import IOService +from services.logging.base import LoggerBase +from services.mmcif import MmCIFService +from services.calculation_storage import CalculationStorageService + + +class ChargeFW2Service: + """"""ChargeFW2 service."""""" + + def __init__( + self, + chargefw2: ChargeFW2Base, + logger: LoggerBase, + io: IOService, + mmcif_service: MmCIFService, + calculation_storage: CalculationStorageService, + max_workers: int = 4, + max_concurrent_calculations: int = 4, + ): + self.chargefw2 = chargefw2 + self.logger = logger + self.io = io + self.mmcif_service = mmcif_service + self.calculation_storage = calculation_storage + self.executor = ThreadPoolExecutor(max_workers) + self.semaphore = asyncio.Semaphore(max_concurrent_calculations) + + async def _run_in_executor(self, func, *args, executor=None): + loop = asyncio.get_event_loop() + return await loop.run_in_executor( + self.executor if executor is None else executor, func, *args + ) + + # Method related operations + def get_available_methods(self) -> list[Method]: + """"""Get available methods for charge calculation."""""" + + try: + self.logger.info(""Getting available methods."") + methods = self.chargefw2.get_available_methods() + + return methods + except Exception as e: + self.logger.error(f""Error getting available methods: {e}"") + raise e + + async def get_suitable_methods( + self, file_hashes: list[str], permissive_types: bool = True, user_id: str | None = None + ) -> SuitableMethods: + """"""Get suitable methods for charge calculation based on file hashes."""""" + + try: + self.logger.info(f""Getting suitable methods for file hashes '{file_hashes}'"") + + return await self._find_suitable_methods(file_hashes, permissive_types, user_id) + except Exception as e: + self.logger.error( + f""Error getting suitable methods for file hashes '{file_hashes}': {e}"" + ) + raise e + + async def get_computation_suitable_methods( + self, computation_id: str, user_id: str | None + ) -> SuitableMethods: + """"""Get suitable methods for charge calculation based on files in the provided directory."""""" + + try: + self.logger.info(f""Getting suitable methods for computation '{computation_id}'"") + + calculation_set = self.calculation_storage.get_calculation_set(computation_id) + + settings = AdvancedSettingsDto() + if calculation_set is not None: + settings = calculation_set.advanced_settings + + workdir = self.io.get_inputs_path(computation_id, user_id) + file_hashes = [self.io.parse_filename(file)[0] for file in self.io.listdir(workdir)] + + return await self._find_suitable_methods( + file_hashes, settings.permissive_types, user_id + ) + except Exception as e: + self.logger.error( + f""Error getting suitable methods for computation '{computation_id}': {e}"" + ) + raise e + + async def _find_suitable_methods( + self, file_hashes: list[str], permissive_types: bool, user_id: str | None + ) -> SuitableMethods: + """"""Helper method to find suitable methods for calculation."""""" + + suitable_methods = Counter() + workdir = self.io.get_file_storage_path(user_id) + + dir_contents = self.io.listdir(workdir) + for file_hash in file_hashes: + file = next( + (f for f in dir_contents if self.io.parse_filename(f)[0] == file_hash), None + ) + if file is None: + self.logger.warn(f""File with hash {file_hash} not found in {workdir}, skipping."") + continue + + input_file = os.path.join(workdir, file) + molecules = await self.read_molecules(input_file, True, False, permissive_types) + methods: list[tuple[Method, list[Parameters]]] = await self._run_in_executor( + self.chargefw2.get_suitable_methods, molecules + ) + for method, parameters in methods: + if not parameters or len(parameters) == 0: + suitable_methods[(method,)] += 1 + else: + for p in parameters: + suitable_methods[(method, p)] += 1 + + all_valid = [ + pair for pair in suitable_methods if suitable_methods[pair] == len(file_hashes) + ] + + # Remove duplicates from methods + tmp = {} + for data in all_valid: + tmp[data[0]] = None + + methods = list(tmp.keys()) + + parameters = defaultdict(list) + for pair in all_valid: + if len(pair) == 2: + parameters[pair[0]].append(pair[1]) + + parameters_with_metadata = { + method.internal_name: params for method, params in parameters.items() + } + return SuitableMethods(methods=methods, parameters=parameters_with_metadata) + + async def get_available_parameters(self, method: str) -> list[Parameters]: + """"""Get available parameters for charge calculation method."""""" + + try: + self.logger.info(f""Getting available parameters for method {method}."") + parameters = await self._run_in_executor( + self.chargefw2.get_available_parameters, method + ) + + return parameters + except Exception as e: + self.logger.error(f""Error getting available parameters for method {method}: {e}"") + raise e + + async def get_best_parameters( + self, method: str, file_path: str, permissive_types: bool = True + ) -> Parameters: + """"""Get best parameters for charge calculation method."""""" + + try: + molecules = await self.read_molecules(file_path) + + self.logger.info(f""Getting best parameters for method {method}."") + parameters = await self._run_in_executor( + self.chargefw2.get_best_parameters, molecules, method, permissive_types + ) + + return parameters + except Exception as e: + self.logger.error(f""Error getting best parameters for method {method}: {e}"") + raise e + + async def read_molecules( + self, + file_path: str, + read_hetatm: bool = True, + ignore_water: bool = False, + permissive_types: bool = False, + ) -> Molecules: + """"""Load molecules from a file"""""" + try: + self.logger.info(f""Loading molecules from file {file_path}."") + molecules = await self._run_in_executor( + self.chargefw2.molecules, file_path, read_hetatm, ignore_water, permissive_types + ) + + return molecules + except Exception as e: + self.logger.error(f""Error loading molecules from file {file_path}: {e}"") + raise e + + async def calculate_charges( + self, + computation_id: str, + settings: AdvancedSettingsDto, + data: Tuple[CalculationConfigDto, list[str]], + user_id: str | None, + ) -> list[CalculationResultDto]: + """"""Calculate charges for provided files. + + Args: + computation_id (str): Computation id. + data (Tuple[CalculationConfigDto, list[str]]): Dictionary of configs and file_hashes. + user_id (str): User id making the calculation. + + Returns: + ChargeCalculationResult: List of successful calculations. + Failed calculations are skipped. + """""" + + calculations = await asyncio.gather( + *[ + self._calculate_charges(user_id, computation_id, settings, config, file_hashes) + for config, file_hashes in data.items() + ], + return_exceptions=False, + ) + configs = [calculation.config for calculation in calculations] + + await self.io.store_configs(computation_id, configs, user_id) + + return calculations + + async def _calculate_charges( + self, + user_id: str | None, + computation_id: str, + settings: AdvancedSettingsDto, + config: CalculationConfigDto, + file_hashes: list[str], + ) -> CalculationResultDto: + """"""Calculate charges for provided files."""""" + + self.logger.info( + f""Calculating charges with method {config.method} and parameters {config.parameters}."" + ) + + workdir = self.io.get_file_storage_path(user_id) + + async def process_file( + file_hash: str, config: CalculationConfigDto + ) -> CalculationDto | None: + file_name = next( + ( + file + for file in self.io.listdir(workdir) + if self.io.parse_filename(file)[0] == file_hash + ), + None, + ) + + if file_name is None: + self.logger.warn(f""File with hash {file_hash} not found in {workdir}, skipping."") + return + + async with self.semaphore: + charges_dir = self.io.get_charges_path(computation_id, user_id) + self.io.create_dir(charges_dir) + + full_path = os.path.join(workdir, file_name) + file_name = self.io.parse_filename(file_name)[1] + + molecules = await self.read_molecules( + full_path, + settings.read_hetatm, + settings.ignore_water, + settings.permissive_types, + ) + + charges = await self._run_in_executor( + self.chargefw2.calculate_charges, + molecules, + config.method, + config.parameters, + charges_dir, + ) + + result = CalculationDto( + file=file_name, file_hash=file_hash, charges=charges, config=config + ) + + return result + + try: + calculations = [ + calculation + for calculation in await asyncio.gather( + *[process_file(file_hash, config) for file_hash in file_hashes], + return_exceptions=False, + ) + if calculation is not None + ] + config_dto = CalculationConfigDto( + method=config.method, + parameters=config.parameters, + ) + + return CalculationResultDto( + config=config_dto, + calculations=calculations, + ) + except Exception as e: + self.logger.error(f""Error calculating charges: {traceback.format_exc()}"") + raise e + + async def save_charges( + self, + settings: AdvancedSettingsDto, + computation_id: str, + results: list[CalculationResultDto], + user_id: str | None, + ) -> None: + workdir = self.io.get_file_storage_path(user_id) + charges_dir = self.io.get_charges_path(computation_id, user_id) + self.io.create_dir(charges_dir) + + for result in results: + for calculation in result.calculations: + file_path = str(Path(workdir) / f""{calculation.file_hash}_{calculation.file}"") + molecules = await self.read_molecules( + file_path, + settings.read_hetatm, + settings.ignore_water, + settings.permissive_types, + ) + config = calculation.config + await self._run_in_executor( + self.chargefw2.save_charges, + calculation.charges, + molecules, + config.method, + config.parameters, + charges_dir, + ) + + async def info(self, path: str) -> MoleculeSetStats: + """"""Get information about the provided file."""""" + + try: + self.logger.info(f""Getting info for file {path}."") + + molecules = await self.read_molecules(path) + info = molecules.info() + + return MoleculeSetStats(info.to_dict()) + except Exception as e: + self.logger.error(f""Error getting info for file {path}: {traceback.format_exc()}"") + raise e + + def get_calculation_molecules(self, path: str) -> list[str]: + """"""Returns molecules stored in the provided path. + + Args: + path (str): Path to computation results. + + Raises: + FileNotFoundError: If the provided path does not exist. + + Returns: + list[str]: List of molecule names. + """""" + if not self.io.path_exists(path): + raise FileNotFoundError() + + molecule_files = [ + file for file in self.io.listdir(path) if file.endswith(CHARGES_OUTPUT_EXTENSION) + ] + molecules = [file.replace(CHARGES_OUTPUT_EXTENSION, """") for file in molecule_files] + + return molecules + + def delete_calculation(self, computation_id: str, user_id: str) -> None: + """"""Delete the provided computation (from database and filesystem). + + Args: + computation_id (str): Computation id. + user_id (str): User id. + + Raises: + e: Error deleting computation. + """""" + try: + self.calculation_storage.delete_calculation_set(computation_id) + self.io.delete_computation(computation_id, user_id) + except Exception as e: + self.logger.error( + f""Error deleting computation {computation_id}: {traceback.format_exc()}"" + ) + raise e +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/io.py",".py","19889","561","""""""Service for handling file operations."""""" + +import datetime +import json +import os +from pathlib import Path +import traceback +from typing import Tuple + +from dotenv import load_dotenv +from fastapi import UploadFile, status + +from api.v1.exceptions import BadRequestError +from api.v1.constants import ALLOWED_FILE_TYPES +from models.calculation import CalculationConfigDto + +from integrations.io.base import IOBase +from services.logging.base import LoggerBase + +load_dotenv() + + +class IOService: + """"""Service for handling file operations."""""" + + def __init__(self, io: IOBase, logger: LoggerBase): + self.io = io + self.logger = logger + + self.workdir = Path(os.environ.get(""ACC_DATA_DIR"", """")) + self.examples_dir = Path(os.environ.get(""ACC_EXAMPLES_DIR"", """")) + + self.user_quota = int(os.environ.get(""ACC_USER_STORAGE_QUOTA_BYTES"", 0)) + self.guest_file_quota = int(os.environ.get(""ACC_GUEST_FILE_STORAGE_QUOTA_BYTES"", 0)) + self.guest_compute_quota = int(os.environ.get(""ACC_GUEST_COMPUTE_STORAGE_QUOTA_BYTES"", 0)) + + self.max_file_size = int(os.environ.get(""ACC_MAX_FILE_SIZE_BYTES"", 0)) + self.max_upload_size = int(os.environ.get(""ACC_MAX_UPLOAD_SIZE_BYTES"", 0)) + + self._ensure_env_set() + + def create_dir(self, path: str) -> None: + """"""Create directory based on path."""""" + + if self.io.path_exists(path): + return + + self.logger.info(f""Creating directory {path}"") + + try: + self.io.mkdir(path) + except Exception as e: + self.logger.error(f""Unable to create directory '{path}': {traceback.format_exc()}"") + raise e + + def cp(self, path_from: str, path_to: str) -> str: + """"""Copy file from source to destination."""""" + + self.logger.info(f""Copying from {path_from} to {path_to}."") + + try: + path = self.io.cp(path_from, path_to) + return path + except Exception as e: + self.logger.error( + f""Unable to copy '{path_from}' to '{path_to}': {traceback.format_exc()}"" + ) + raise e + + async def store_upload_file(self, file: UploadFile, directory: str) -> tuple[str, str]: + """"""Store uploaded file in the provided directory."""""" + self.logger.info(f""Storing file {file.filename}."") + + try: + return await self.io.store_upload_file(file, directory) + except Exception as e: + self.logger.error(f""Error storing file {file.filename}: {traceback.format_exc()}"") + raise e + + def remove_file(self, file_hash: str, user_id: str | None = None) -> None: + """"""Remove file with provided hash. + + Args: + file_hash (str): File hash. + user_id (str | None): User id. + + Raises: + e: Error removing file. + """""" + + self.logger.info(f""Removing file {file_hash}."") + + try: + path = self.get_filepath(file_hash, user_id) + if path: + self.io.rm(path) + except Exception as e: + self.logger.error(f""Error removing file {file_hash}: {traceback.format_exc()}"") + raise e + + def zip_charges(self, directory: str) -> str: + """"""Create archive from directory."""""" + + self.logger.info(f""Creating archive from {directory}."") + + try: + archive_dir = Path(directory) / ""archive"" + self.io.mkdir(str(archive_dir)) + + for extension in [""cif"", ""pqr"", ""txt"", ""mol2""]: + self.io.mkdir(str(archive_dir / extension)) + + for file in self.io.listdir(directory): + extension = file.rsplit(""."", 1)[-1] + file_path = str(Path(directory) / file) + + if extension in [""pqr"", ""txt"", ""mol2""]: + new_name = self.parse_filename(file)[-1] # removing hash from filename + self.io.cp(file_path, str(Path(archive_dir) / extension / new_name)) + elif extension == ""cif"": + self.io.cp(file_path, str(Path(archive_dir) / extension)) + + return self.io.zip(str(archive_dir), str(archive_dir)) + except Exception as e: + self.logger.error(f""Error creating archive from {directory}: {traceback.format_exc()}"") + raise e + + def listdir(self, directory: str) -> list[str]: + """"""List directory contents."""""" + return self.io.listdir(directory) + + def path_exists(self, path: str) -> bool: + """"""Check if path exists."""""" + + return self.io.path_exists(path) + + def get_storage_path(self, user_id: str | None) -> str: + """"""Get path to user storage."""""" + + if user_id is not None: + path = self.workdir / ""user"" / user_id + else: + path = self.workdir / ""guest"" + + return str(path) + + def get_file_storage_path(self, user_id: str | None = None) -> str: + """"""Get path to file storage. + + Args: + user_id (str | None, optional): Id of user. Defaults to None. + + Returns: + str: Path to users file storage if user_id is provided. + Path to guest file storage if user_id is None. + """""" + if user_id is not None: + path = self.workdir / ""user"" / user_id / ""files"" + else: + path = self.workdir / ""guest"" / ""files"" + + return str(path) + + def get_computations_path(self, user_id: str | None = None) -> str: + """"""Get path to computations directory. + + Args: + user_id (str | None, optional): Id of user. Defaults to None. + + Returns: + str: Returns path to computations directory of a given (users/guest) user. + """""" + + if user_id is not None: + path = self.workdir / ""user"" / user_id / ""computations"" + else: + path = self.workdir / ""guest"" / ""computations"" + + return str(path) + + def get_computation_path(self, computation_id: str, user_id: str | None = None) -> str: + """"""Get path to computation directory. + + Args: + computation_id (str): Id of computation. + user_id (str | None, optional): Id of user. Defaults to None. + + Returns: + str: Returns path to computation directory of a given (users/guest) computation. + """""" + + if user_id is not None: + path = self.workdir / ""user"" / user_id / ""computations"" / computation_id + else: + path = self.workdir / ""guest"" / ""computations"" / computation_id + + return str(path) + + def get_inputs_path(self, computation_id: str, user_id: str | None = None) -> str: + """"""Get path to inputs of a provided computation. + + Args: + computation_id (str): Id of computation. + user_id (str | None, optional): Id of user. Defaults to None. + + Returns: + str: Returns path to input of a given (users/guest) computation. + """""" + + if user_id is not None: + path = self.workdir / ""user"" / user_id / ""computations"" / computation_id / ""input"" + else: + path = self.workdir / ""guest"" / ""computations"" / computation_id / ""input"" + + return str(path) + + def get_charges_path(self, computation_id: str, user_id: str | None = None) -> str: + """"""Get path to charges directory of a provided computation. + + Args: + computation_id (str): Id of the computation. + file (str): Name of the file. + user_id (str | None, optional): Id of the user. Defaults to None. + + Returns: + str: Path to charges directory of a given (users/guest) computation. + """""" + + if user_id is not None: + path = self.workdir / ""user"" / user_id / ""computations"" / computation_id / ""charges"" + else: + path = self.workdir / ""guest"" / ""computations"" / computation_id / ""charges"" + + return str(path) + + def get_example_path(self, example_id: str) -> str: + """"""Get path to example directory."""""" + path = self.examples_dir / example_id + return str(path) + + def prepare_inputs( + self, user_id: str | None, computation_id: str, file_hashes: list[str] + ) -> None: + """"""Prepare input files for computation."""""" + + inputs_path = self.get_inputs_path(computation_id, user_id) + files_path = self.get_file_storage_path(user_id) + self.create_dir(inputs_path) + self.create_dir(files_path) + + for file_hash in file_hashes: + file_name = next( + ( + file + for file in self.listdir(files_path) + if self.parse_filename(file)[0] == file_hash + ), + None, + ) + + if not file_name: + self.logger.warn( + f""File with hash {file_hash} not found in {inputs_path}, skipping."" + ) + continue + + src_path = str(Path(files_path) / file_name) + dst_path = str(Path(inputs_path) / file_name) + try: + self.io.symlink(src_path, dst_path) + except Exception as e: + self.logger.warn( + f""Unable to create symlink from {src_path} to {dst_path}: {str(e)}"" + ) + + async def store_configs( + self, + computation_id: str, + configs: list[CalculationConfigDto], + user_id: str | None = None, + ) -> None: + """"""Store configs for computation to a json file."""""" + + self.logger.info(f""Storing configs for computation. {computation_id}"") + + try: + path = Path(self.get_computation_path(computation_id, user_id)) + config_path = str(path / ""configs.json"") + await self.io.write_file( + config_path, json.dumps([config.model_dump() for config in configs], indent=4) + ) + except Exception as e: + self.logger.error(f""Unable to store configs: {traceback.format_exc()}"") + raise e + + def get_filepath(self, file_hash: str, user_id: str | None = None) -> str | None: + """"""Get path to file with provided hash. + + Args: + file_hash (str): File hash. + user_id (str | None): User id. + + Returns: + str: Path to file. + """""" + + try: + path = Path(self.get_file_storage_path(user_id)) + for file in self.listdir(str(path)): + curr_hash, _ = self.parse_filename(file) + if curr_hash == file_hash: + return str(path / file) + + return None + except Exception as e: + self.logger.error(f""Unable to get file path: {traceback.format_exc()}"") + raise e + + def get_last_modification( + self, file_hash: str, user_id: str | None = None + ) -> datetime.datetime | None: + """"""Get last modification time of file with provided hash. + + Args: + file_hash (str): File hash. + user_id (str | None): User id. + + Returns: + datetime.datetime | None: Last modification time. + """""" + + try: + path = self.get_filepath(file_hash, user_id) + return self.io.last_modified(path) + except Exception as e: + self.logger.error(f""Unable to get last modification time: {traceback.format_exc()}"") + raise e + + def get_file_size(self, file_hash: str, user_id: str | None) -> int | None: + """"""Get size of file with provided hash. + + Args: + file_hash (str): File hash. + user_id (str | None): User id. + + Returns: + int | None: File size. + """""" + + try: + path = self.get_filepath(file_hash, user_id) + return self.io.file_size(path) + except Exception as e: + self.logger.error(f""Unable to get file size: {traceback.format_exc()}"") + raise e + + def free_guest_file_space(self, amount_to_free: int) -> None: + """"""Free guest file space. + + Args: + amount_to_free (int): Amount to free in bytes. + """""" + + path = self.get_file_storage_path() + + self.logger.info(f""Freeing {amount_to_free} bytes of guest file space."") + + available_to_free = self.io.dir_size(path) + has_to_free = self.guest_file_quota - available_to_free < amount_to_free + + if not has_to_free: + self.logger.info(""Guest file space is sufficient. No need to free space."") + return + + if available_to_free < amount_to_free: + # This case should not happen as max allowed file size is checked beforehand + self.logger.error( + f""Unable to free {amount_to_free} bytes of guest file space. "" + + f""Only {available_to_free} bytes available."" + ) + raise ValueError(""Not enough space to free."") + + files = sorted(self.listdir(path), key=lambda x: self.io.last_modified(str(Path(path) / x))) + + while amount_to_free > 0 and len(files) > 0: + file = files.pop(0) + file_path = str(Path(path) / file) + + try: + amount_to_free -= self.io.file_size(file_path) + self.io.rm(file_path) + except Exception as e: + self.logger.error(f""Unable to delete file {file_path}: {traceback.format_exc()}"") + raise e + + def free_guest_compute_space(self) -> None: + """"""Removes old computations to free guest compute space, if it exceeds the quota."""""" + + path = self.get_computations_path() + + available_to_free = self.io.dir_size(path) + amount_to_free = available_to_free - self.guest_compute_quota + + if amount_to_free <= 0: + self.logger.info(""Guest compute space is sufficient. No need to free space."") + return + + self.logger.info(f""Freeing {amount_to_free} bytes of guest compute space."") + + computations = sorted( + self.listdir(path), key=lambda x: self.io.last_modified(str(Path(path) / x)) + ) + + while amount_to_free > 0 and len(computations) > 0: + computation = computations.pop(0) + computation_path = str(Path(path) / computation) + + try: + amount_to_free -= self.io.dir_size(computation_path) + self.io.rmdir(computation_path) + except Exception as e: + self.logger.error( + f""Unable to delete computation {computation_path}: {traceback.format_exc()}"" + ) + raise e + + def delete_computation(self, computation_id: str, user_id: str) -> None: + """"""Delete the provided computation from the filesystem. + + Args: + computation_id (str): Computation id. + user_id (str): User id. + + Raises: + e: Error deleting computation. + """""" + try: + self.io.rmdir(self.get_computation_path(computation_id, user_id)) + except Exception as e: + self.logger(f""Error deleting computation {computation_id}: {traceback.format_exc()}"") + raise e + + def parse_filename(self, filename: str) -> Tuple[str, str]: + """"""Parse filename to get file hash and name. + + Args: + filename (str): Filename in format _. + + Raises: + ValueError: If filename is not in the correct format. + + Returns: + Tuple[str, str]: Tuple with file hash and name. + """""" + + sha256_hash_length = 64 + parts = filename.split(""_"", 1) + + if (len(parts) != 2) or (len(parts[0]) != sha256_hash_length): + self.logger.error(f""Invalid filename format (_): {filename}"") + raise ValueError(""Invalid filename format."") + + file_hash, file_name = parts + + return file_hash, file_name + + def get_quota(self, user_id: str | None = None) -> Tuple[int, int, int]: + """"""Get user storage quota. + + Args: + user_id (str): User id. + + Returns: + Tuple[int, int, int]: Tuple with used space, available space and quota. + """""" + + storage_dir = Path(self.get_storage_path(user_id)) + quota = self.user_quota if user_id else self.guest_file_quota + self.guest_compute_quota + + used_space = self.io.dir_size(storage_dir) + available_space = quota - used_space + + return used_space, available_space, quota + + def ensure_upload_files_provided(self, files: list[UploadFile]) -> None: + if len(files) == 0: + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, detail=""No files provided."" + ) + + def ensure_upload_files_sizes_valid(self, files: list[UploadFile]) -> None: + if any((file.size or 0) > self.max_file_size for file in files): + max_file_size_mb = self.max_file_size / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=""Unable to upload files. One or more files are too large. "" + + f""Maximum allowed size is {max_file_size_mb} MB."", + ) + + upload_size_b = sum((file.size or 0) for file in files) + + if upload_size_b > self.max_upload_size: + max_upload_size_mb = self.max_upload_size / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=""Unable to upload files. Maximum upload size exceeded. "" + + f""Maximum upload size is {max_upload_size_mb} MB."", + ) + + def ensure_uploaded_file_types_valid(self, files: list[UploadFile]) -> None: + if not all(self._is_ext_valid(file.filename or """") for file in files): + raise BadRequestError( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f""Invalid file type. Allowed file types are {', '.join(ALLOWED_FILE_TYPES)}"", + ) + + def ensure_quota_not_exceeded(self, upload_size_b: int, user_id: str | None = None) -> None: + if user_id is not None: + _, available_b, quota_b = self.get_quota(user_id) + + if upload_size_b > available_b: + quota_mb = quota_b / 1024 / 1024 + raise BadRequestError( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=""Unable to upload files. Quota exceeded. "" + + f""Maximum storage space is {quota_mb} MB."", + ) + else: + _, available, _ = self.get_quota() + if upload_size_b > available: + self.free_guest_file_space(upload_size_b) + + def _is_ext_valid(self, filename: str) -> bool: + return any(filename.endswith(f"".{ext}"") for ext in ALLOWED_FILE_TYPES) + + def _ensure_env_set(self) -> None: + if not self.workdir.name: + raise EnvironmentError(""ACC_DATA_DIR environment variable is not set."") + + if not self.examples_dir.name: + raise EnvironmentError(""ACC_EXAMPLES_DIR environment variable is not set."") + + if not self.user_quota: + raise EnvironmentError(""ACC_USER_STORAGE_QUOTA_BYTES environment variable is not set."") + + if not self.guest_file_quota: + raise EnvironmentError( + ""ACC_GUEST_FILE_STORAGE_QUOTA_BYTES environment variable is not set."" + ) + + if not self.guest_compute_quota: + raise EnvironmentError( + ""ACC_GUEST_COMPUTE_STORAGE_QUOTA_BYTES environment variable is not set."" + ) + + if not self.max_file_size: + raise EnvironmentError(""ACC_MAX_FILE_SIZE_BYTES environment variable is not set."") + + if not self.max_upload_size: + raise EnvironmentError(""ACC_MAX_UPLOAD_SIZE_BYTES environment variable is not set."") +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/oidc.py",".py","4371","136","""""""OIDC service module."""""" + +import os + +import httpx + +from cachetools import TTLCache +from dotenv import load_dotenv + +from jose import JWTError, jwt + +from services.logging.base import LoggerBase + + +class OIDCService: + """"""Service for handling OIDC operations."""""" + + def __init__(self, logger: LoggerBase): + self.logger = logger + + self.config_cache = TTLCache(maxsize=1, ttl=3600) + self.jwks_cache = TTLCache(maxsize=1, ttl=3600) + + load_dotenv() + + self.base_url = os.environ.get(""OIDC_BASE_URL"", """") + self.discovery_url = os.environ.get(""OIDC_DISCOVERY_URL"", """") + self.redirect_url = os.environ.get(""OIDC_REDIRECT_URL"", """") + self.client_id = os.environ.get(""OIDC_CLIENT_ID"", """") + self.client_secret = os.environ.get(""OIDC_CLIENT_SECRET"", """") + self.audience = os.environ.get(""OIDC_REDIRECT_URL"", """") + + self._ensure_env_set() + + async def get_oidc_config(self) -> dict: + """"""Get the OIDC configuration from the discovery endpoint or cache, if available. + + Returns: + dict: OIDC configuration. + """""" + + if ""config"" not in self.config_cache: + async with httpx.AsyncClient() as client: + response = await client.get(self.discovery_url) + response.raise_for_status() + self.config_cache[""config""] = response.json() + + return self.config_cache.get(""config"", {}) + + async def get_jwks(self) -> dict: + """"""Get the JWKs from the discovery endpoint or cache, if available. + + Returns: + dict: JWKs. + """""" + + if ""jwks"" not in self.jwks_cache: + config = await self.get_oidc_config() + jwks_uri = config[""jwks_uri""] + + async with httpx.AsyncClient() as client: + response = await client.get(jwks_uri) + response.raise_for_status() + self.jwks_cache[""jwks""] = response.json() + + return self.jwks_cache.get(""jwks"", {}) + + async def verify_token(self, token: str) -> dict | None: + """"""Verify the token and return the claims. + + Args: + token (str): The token to verify. + + Returns: + dict | None: The claims of the token or None if the token is invalid. + """""" + try: + unverified_header = jwt.get_unverified_header(token) + kid = unverified_header.get(""kid"") + if not kid: + self.logger.warn(""No 'kid' in token header."") + return None + + jwks = await self.get_jwks() + + rsa_key = {} + for key in jwks[""keys""]: + if key[""kid""] == kid: + # https://auth0.com/docs/secure/tokens/json-web-tokens/json-web-key-set-properties + rsa_key = { + ""kty"": key[""kty""], + ""kid"": key[""kid""], + ""use"": key[""use""], + ""n"": key[""n""], + ""e"": key[""e""], + } + + if not rsa_key: + return None + + config = await self.get_oidc_config() + + payload = jwt.decode( + token, + rsa_key, + algorithms=[""RS256""], + audience=self.client_id, + issuer=config[""issuer""], + ) + return payload + except JWTError as e: + self.logger.warn(f""Invalid token: {str(e)}"") + return None + except Exception as e: + self.logger.error(f""Error verifying token: {str(e)}"") + return None + + def _ensure_env_set(self) -> None: + if not self.base_url: + raise EnvironmentError(""OIDC_BASE_URL environment variable is not set"") + + if not self.discovery_url: + raise EnvironmentError(""OIDC_DISCOVERY_URL environment variable is not set"") + + if not self.redirect_url: + raise EnvironmentError(""OIDC_REDIRECT_URL environment variable is not set"") + + if not self.client_id: + raise EnvironmentError(""OIDC_CLIENT_ID environment variable is not set"") + + if not self.client_secret: + raise EnvironmentError(""OIDC_CLIENT_SECRET environment variable is not set"") + + if not self.audience: + raise EnvironmentError(""OIDC_REDIRECT_URL environment variable is not set"") +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/calculation_storage.py",".py","16609","433","import traceback +from typing import Tuple + +from sqlalchemy.orm import Session + +from models.calculation import ( + CalculationConfigDto, + CalculationDto, + CalculationResultDto, + CalculationSetPreviewDto, + CalculationsFilters, +) +from models.paging import PagedList +from models.molecule_info import MoleculeSetStats +from db.schemas.calculation import ( + AdvancedSettings, + Calculation, + CalculationConfig, + CalculationSet, + CalculationSetStats, +) +from db.schemas.stats import AtomTypeCount, MoleculeSetStats as MoleculeSetStatsModel + +from db.repositories.calculation_config_repository import CalculationConfigRepository +from db.repositories.calculation_repository import CalculationRepository +from db.repositories.calculation_set_repository import ( + CalculationSetFilters, + CalculationSetRepository, +) +from db.repositories.moleculeset_stats_repository import MoleculeSetStatsRepository + +from models.setup import AdvancedSettingsDto +from db.repositories.advanced_settings_repository import AdvancedSettingsRepository +from db.database import SessionManager +from services.logging.base import LoggerBase + + +class CalculationStorageService: + """"""Service for manipulating calculations in the database."""""" + + def __init__( + self, + logger: LoggerBase, + set_repository: CalculationSetRepository, + calculation_repository: CalculationRepository, + config_repository: CalculationConfigRepository, + stats_repository: MoleculeSetStatsRepository, + advanced_settings_repository: AdvancedSettingsRepository, + session_manager: SessionManager, + ): + self.set_repository = set_repository + self.calculation_repository = calculation_repository + self.config_repository = config_repository + self.stats_repository = stats_repository + self.advanced_settings_repository = advanced_settings_repository + self.session_manager = session_manager + self.logger = logger + + def get_info(self, session: Session, file_hash: str) -> MoleculeSetStats | None: + # Getting info manually due to lazy loading issue + + info = self.stats_repository.get(session, file_hash) + + if info is None: + return None + + info_dict = { + ""total_molecules"": info.total_molecules, + ""total_atoms"": info.total_atoms, + ""atom_type_counts"": [vars(count) for count in info.atom_type_counts], + } + + return MoleculeSetStats(info_dict) + + def get_calculations( + self, filters: CalculationSetFilters + ) -> PagedList[CalculationSetPreviewDto]: + """"""Get calculations from database based on filters."""""" + + try: + with self.session_manager.session() as session: + self.logger.info(""Getting calculations from database."") + calculations_list = self.set_repository.get_all(session, filters) + calculations_list.items = [ + CalculationSetPreviewDto.model_validate( + { + ""id"": calculation_set.id, + ""files"": { + stats_assoc.file_name: self.get_info( + session, stats_assoc.molecule_set_id + ) + for stats_assoc in calculation_set.molecule_set_stats_associations + }, + ""configs"": calculation_set.configs, + ""settings"": AdvancedSettingsDto.model_validate( + vars(calculation_set.advanced_settings) + ), + ""created_at"": calculation_set.created_at, + } + ) + for calculation_set in calculations_list.items + ] + + return PagedList[CalculationSetPreviewDto].model_validate(calculations_list) + except Exception as e: + self.logger.error(f""Error getting calculations from database: {traceback.format_exc()}"") + raise e + + def get_calculation_set(self, computation_id: str) -> CalculationSet | None: + """"""Get calculation set from database."""""" + + try: + self.logger.info(f""Getting calculation set {computation_id}."") + with self.session_manager.session() as session: + return self.set_repository.get(session, computation_id) + except Exception as e: + self.logger.error( + f""Error getting calculation set {computation_id}: {traceback.format_exc()}"" + ) + raise e + + def store_file_info(self, file_hash: str, info: MoleculeSetStats) -> MoleculeSetStats: + """"""Store file info to database."""""" + + try: + with self.session_manager.session() as session: + self.logger.info(f""Storing stats of file with hash '{file_hash}'."") + info_model = MoleculeSetStatsModel( + file_hash=file_hash, + total_molecules=info.total_molecules, + total_atoms=info.total_atoms, + atom_type_counts=[ + AtomTypeCount(symbol=count.symbol, count=count.count) + for count in info.atom_type_counts + ], + ) + + return self.stats_repository.store(session, info_model) + except Exception as e: + self.logger.error( + f""Error storing stats of file with hash '{file_hash}': "" + + f""{traceback.format_exc()}"" + ) + raise e + + def store_calculation_results( + self, + computation_id: str, + settings: AdvancedSettingsDto, + results: list[CalculationResultDto], + user_id: str | None, + ) -> None: + try: + self.logger.info(f""Storing calculation results for computation {computation_id}."") + + with self.session_manager.session() as session: + settings_entity = self._get_or_create_advanced_settings(session, settings) + calculation_set = self._get_or_create_calculation_set( + session, computation_id, user_id, settings_entity + ) + + calculations = [] + added_stats = set() + + for result in results: + config_entity = self._get_or_create_config( + session, result.config, calculation_set + ) + + new_calculations, files = self._process_calculations( + session, result, config_entity, settings_entity + ) + calculations.extend(new_calculations) + + self._add_molecule_stats(session, calculation_set, files, added_stats) + + for calculation in calculations: + self.calculation_repository.store(session, calculation) + + self.set_repository.store(session, calculation_set) + + except Exception as e: + self.logger.error( + f""Error storing calculation results for computation {computation_id}."" + ) + raise e + + def setup_calculation( + self, + computation_id: str, + settings: AdvancedSettingsDto, + file_hashes: list[str], + user_id: str | None, + ) -> None: + """"""Setup calculation in database."""""" + + try: + self.logger.info(""Setting up calculation."") + + with self.session_manager.session() as session: + settings_entity = self._get_or_create_advanced_settings(session, settings) + + calculation_set = CalculationSet( + id=computation_id, + user_id=user_id, + advanced_settings=settings_entity, + ) + + for file_hash in file_hashes: + calculation_set.molecule_set_stats.append( + self.stats_repository.get(session, file_hash) + ) + + self.set_repository.store(session, calculation_set) + except Exception as e: + self.logger.error(f""Error setting up calculation: {traceback.format_exc()}"") + raise e + + def filter_existing_calculations( + self, + settings: AdvancedSettingsDto, + file_hashes: list[str], + configs: list[CalculationConfigDto], + ) -> Tuple[ + dict[str, list[CalculationConfigDto]], dict[CalculationConfigDto, list[CalculationDto]] + ]: + """"""Returns a list of hashes and configs that are not in the database."""""" + + to_calculate = {} + cached = {} + + try: + self.logger.info(""Filtering existing calculations."") + + with self.session_manager.session() as session: + for config in configs: + for file_hash in file_hashes: + filters = CalculationsFilters( + hash=file_hash, + method=config.method, + parameters=config.parameters, + read_hetatm=settings.read_hetatm, + ignore_water=settings.ignore_water, + permissive_types=settings.permissive_types, + ) + + existing_calculation = self.calculation_repository.get(session, filters) + if existing_calculation is None: + if config not in to_calculate: + to_calculate[config] = [] + + to_calculate[config].append(file_hash) + else: + if config not in cached: + cached[config] = [] + + cached[config].append( + CalculationDto( + file=existing_calculation.file_name, + file_hash=existing_calculation.file_hash, + charges=existing_calculation.charges, + config=config, + ), + ) + self.logger.info( + f""Existing calculation found for file '{file_hash}', skipping."" + ) + + return to_calculate, cached + except Exception as e: + self.logger.error(f""Error filtering existing calculations: {traceback.format_exc()}"") + raise e + + def get_calculation_results(self, computation_id: str) -> list[CalculationResultDto]: + """"""Get calculation results from database."""""" + + try: + self.logger.info(f""Getting calculation results for computation {computation_id}."") + with self.session_manager.session() as session: + calculation_set = self.set_repository.get(session, computation_id) + + if not calculation_set: + return [] + + result = [ + CalculationResultDto( + config=CalculationConfigDto.model_validate(config), + calculations=[ + CalculationDto.model_validate(calculation) + for calculation in calculation_set.calculations + if calculation.config == config + ], + ) + for config in calculation_set.configs + ] + + return result + + except Exception as e: + self.logger.error( + f""Error getting calculation results for computation {computation_id}: {traceback.format_exc()}"" + ) + raise e + + def delete_calculation_set(self, computation_id: str) -> None: + """"""Delete calculation set from database."""""" + + try: + self.logger.info(f""Deleting calculation set {computation_id}."") + with self.session_manager.session() as session: + self.set_repository.delete(session, computation_id) + except Exception as e: + self.logger.error( + f""Error deleting calculation set {computation_id}: {traceback.format_exc()}"" + ) + raise e + + def _get_or_create_advanced_settings( + self, session: Session, settings: AdvancedSettingsDto + ) -> AdvancedSettings: + """"""Get existing settings or create new."""""" + + settings_entity = self.advanced_settings_repository.get(session, settings) + if settings_entity is None: + settings_entity = AdvancedSettings( + ignore_water=settings.ignore_water, + read_hetatm=settings.read_hetatm, + permissive_types=settings.permissive_types, + ) + self.advanced_settings_repository.store(session, settings_entity) + return settings_entity + + def _get_or_create_calculation_set( + self, + session: Session, + computation_id: str, + user_id: str | None, + settings_entity: AdvancedSettings, + ) -> CalculationSet: + """"""Get existing calculation set or create new."""""" + + calculation_set = self.set_repository.get(session, computation_id) + if calculation_set is None: + calculation_set = CalculationSet( + id=computation_id, + user_id=user_id, + advanced_settings=settings_entity, + ) + self.set_repository.store(session, calculation_set) + + return calculation_set + + def _get_or_create_config( + self, session: Session, config: CalculationConfigDto, calculation_set: CalculationSet + ) -> CalculationConfig: + """"""Get existing config or create new."""""" + + existing_config = self.config_repository.get(session, config.method, config.parameters) + + if existing_config is None: + config_entity = CalculationConfig(method=config.method, parameters=config.parameters) + else: + config_entity = existing_config + + if config_entity not in calculation_set.configs: + calculation_set.configs.append(config_entity) + + return config_entity + + def _process_calculations( + self, + session: Session, + result: CalculationResultDto, + config_entity: CalculationConfig, + settings_entity: AdvancedSettings, + ) -> tuple[list[Calculation], dict[str, str]]: + """"""Process calculation results and return new calculations and files (file_hash -> file)."""""" + + new_calculations = [] + files = {} + + for calculation in result.calculations: + files[calculation.file_hash] = calculation.file + + calculation_exists = self.calculation_repository.get( + session, + CalculationsFilters( + hash=calculation.file_hash, + method=calculation.config.method, + parameters=calculation.config.parameters, + read_hetatm=settings_entity.read_hetatm, + ignore_water=settings_entity.ignore_water, + permissive_types=settings_entity.permissive_types, + ), + ) + + if calculation_exists is None: + new_calculations.append( + Calculation( + file_name=calculation.file, + file_hash=calculation.file_hash, + charges=calculation.charges, + config=config_entity, + advanced_settings=settings_entity, + ) + ) + + return new_calculations, files + + def _add_molecule_stats( + self, + session: Session, + calculation_set: CalculationSet, + files: dict[str, str], + added_stats: set[str], + ) -> None: + file_hashes = set(files.keys()) + new_file_hashes = file_hashes - added_stats + + for file_hash in new_file_hashes: + stats = self.stats_repository.get(session, file_hash) + + if stats is None: + # This should never happen + continue + + association = CalculationSetStats( + molecule_set_id=stats.file_hash, + file_name=files.get(stats.file_hash), + ) + calculation_set.molecule_set_stats_associations.append(association) + added_stats.add(stats.file_hash) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/file_storage.py",".py","2594","73","from datetime import datetime +from pathlib import Path +from typing import Literal +from db.database import SessionManager +from api.v1.schemas.file import FileResponse +from models.paging import PagedList +from models.molecule_info import MoleculeSetStats +from services.calculation_storage import CalculationStorageService +from services.io import IOService +from services.logging.base import LoggerBase + + +class FileStorageService: + """"""Service for manipulating files in the database and filesystem."""""" + + def __init__( + self, + logger: LoggerBase, + io: IOService, + session_manager: SessionManager, + storage_service: CalculationStorageService, + ): + self.io = io + self.storage_service = storage_service + self.session_manager = session_manager + self.logger = logger + + def get_files( + self, + order_by: Literal[""name"", ""size"", ""uploaded_at""], + order: Literal[""asc"", ""desc""], + page: int, + page_size: int, + search: str, + user_id: str, + ) -> PagedList[FileResponse]: + workdir = self.io.get_file_storage_path(user_id) + files = [self.io.parse_filename(Path(name).name) for name in self.io.listdir(workdir)] + + is_reverse = order == ""desc"" + + match order_by: + case ""name"": + files.sort(key=lambda x: x[-1], reverse=is_reverse) + case ""size"": + files.sort(key=lambda x: self.io.get_file_size(x[0], user_id), reverse=is_reverse) + case ""uploaded_at"" | _: + files.sort( + key=lambda x: self.io.get_last_modification(x[0], user_id), reverse=is_reverse + ) + + if search != """": + files = [file for file in files if search.casefold() in file[1].casefold()] + + page_start = (page - 1) * page_size + page_end = page * page_size + + with self.session_manager.session() as session: + items = [ + FileResponse( + file_name=name, + file_hash=file_hash, + size=self.io.get_file_size(file_hash, user_id) or 0, + stats=self.storage_service.get_info(session, file_hash) + or MoleculeSetStats.default(), + uploaded_at=self.io.get_last_modification(file_hash, user_id) or datetime.min, + ) + for [file_hash, name] in files[page_start:page_end] + ] + + data = PagedList(page=page, page_size=page_size, total_count=len(files), items=items) + return data +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/logging/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/logging/file_logger.py",".py","1006","41","""""""Service for logging to file."""""" + +import logging +import os + +from dotenv import load_dotenv +from services.logging.base import LoggerBase + +load_dotenv() + + +class FileLogger(LoggerBase): + """"""Service for logging to file."""""" + + logdir = os.environ.get(""ACC_LOG_DIR"") + + def __init__(self, file_name: str = ""logs.log"") -> None: + super().__init__() + self.file_name = file_name + + if not os.path.isdir(self.logdir): + os.makedirs(self.logdir) + + logging.basicConfig( + filename=os.path.join(self.logdir, self.file_name), + level=logging.INFO, + filemode=""a+"", + format=""%(asctime)s [%(levelname)s] %(message)s"", + ) + + self.logger = logging.getLogger(__name__) + + def info(self, message: str) -> None: + return self.logger.info(message) + + def warn(self, message: str) -> None: + return self.logger.warning(message) + + def error(self, message: str) -> None: + return self.logger.error(message) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/services/logging/base.py",".py","819","35","""""""Base class for logging service."""""" + +from abc import ABC, abstractmethod + + +class LoggerBase(ABC): + """"""Service for logging"""""" + + @abstractmethod + def info(self, message: str) -> None: + """"""Logs the provided message with 'info' level. + + Args: + message (str): Text to be logged. + """""" + raise NotImplementedError() + + @abstractmethod + def warn(self, message: str) -> None: + """"""Logs the provided message with 'warning' level. + + Args: + message (str): Text to be logged. + """""" + raise NotImplementedError() + + @abstractmethod + def error(self, message: str) -> None: + """"""Logs the provided message with 'info' level. + + Args: + message (str): Text to be logged._ + """""" + raise NotImplementedError() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/chargefw2/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/chargefw2/chargefw2.py",".py","6006","169","""""""ChargeFW2 service for a direct interaction (via bindings) with the ChargeFW2 framework."""""" + +from typing import Dict +import chargefw2 + +from models.method import Method +from models.parameters import Parameters + +from integrations.chargefw2.base import ChargeFW2Base + + +class ChargeFW2Local(ChargeFW2Base): + """"""Service for a direct interaction (via bindings) with the ChargeFW2 framework."""""" + + def molecules( + self, + file_path: str, + read_hetatm: bool = True, + ignore_water: bool = False, + permissive_types: bool = False, + ) -> chargefw2.Molecules: + """"""Load molecules from a file + + Args: + file_path (str): Path from which to load molecules. + Returns: + chargefw2.Molecules: Parsed molecules + """""" + return chargefw2.Molecules(file_path, read_hetatm, ignore_water, permissive_types) + + def get_available_methods(self) -> list[Method]: + """"""Get all available methods. + + Returns: + list[str]: List of method names. + """""" + methods = chargefw2.get_available_methods() + return [ + Method( + internal_name=method.internal_name, + name=method.name, + full_name=method.full_name, + publication=method.publication, + type=method.type, + has_parameters=method.has_parameters, + ) + for method in methods + ] + + def get_available_parameters(self, method: str) -> list[Parameters]: + """"""Get all parameters available for provided method. + + Args: + method (str): Method name. + + Returns: + list[str]: List of parameter names. + """""" + parameters_list = chargefw2.get_available_parameters(method) + return [ + Parameters( + full_name=parameters.full_name, + internal_name=parameters.internal_name, + method=parameters.method, + publication=parameters.publication, + ) + for parameters in parameters_list + ] + + def get_best_parameters( + self, molecules: chargefw2.Molecules, method: str, permissive_types: bool + ) -> Parameters | None: + """"""Get best parameters for provided method. + + Args: + method (str): Method name. + molecules (chargefw2.Molecules): Set of molecules. + permissive_types (bool): Use similar parameters for similar atom/bond types if no exact match is found. + + Returns: + Parameters | None: Best Parameters for provided method. + + """""" + parameters = chargefw2.get_best_parameters(molecules, method, permissive_types) + + if parameters is None: + return None + + return Parameters( + full_name=parameters.full_name, + internal_name=parameters.internal_name, + method=parameters.method, + publication=parameters.publication, + ) + + def get_suitable_methods( + self, molecules: chargefw2.Molecules + ) -> list[tuple[Method, list[Parameters]]]: + """"""Get methods and parameters that are suitable for a given set of molecules. + + Args: + molecules (chargefw2.Molecules): Set of molecules. + + Returns: + list[tuple[str, list[str]]]: List of tuples containing method name and parameters for that method. + """""" + + suitable = chargefw2.get_suitable_methods(molecules) + result = [] + for method, parameters_list in suitable: + method_obj = Method( + internal_name=method.internal_name, + full_name=method.full_name, + name=method.name, + publication=method.publication, + type=method.type, + has_parameters=method.has_parameters, + ) + parameters_obj = [ + Parameters( + full_name=parameters.full_name, + internal_name=parameters.internal_name, + method=parameters.method, + publication=parameters.publication, + ) + for parameters in parameters_list + ] + result.append((method_obj, parameters_obj)) + + return result + + def calculate_charges( + self, + molecules: chargefw2.Molecules, + method_name: str, + parameters_name: str | None = None, + chg_out_dir: str = ""."", + ) -> Dict[str, list[float]]: + """"""Calculate partial atomic charges for a given molecules and method. + + Args: + molecules (chargefw2.Molecules): Set of molecules. + method_name (str): Method name to be used. + parameters_name (Optional[str], optional): Parameters to be used with provided method. Defaults to None. + + Returns: + Dict[str, list[float]]: Dictionary with molecule names as keys and list of charges (floats) as values. + """""" + return chargefw2.calculate_charges(molecules, method_name, parameters_name, chg_out_dir) + + def save_charges( + self, + charges: Dict[str, list[float]], + molecules: chargefw2.Molecules, + method_name: str, + parameters_name: str | None = None, + chg_out_dir: str | None = None, + ) -> None: + """"""Save charges for a given molecules and method. + + Args: + charges (Dict[str, list[float]]): Dictionary with molecule names as keys and list of charges (floats) as values. + molecules (chargefw2.Molecules): Set of molecules. + method_name (str): Method name to be used. + parameters_name (Optional[str], optional): Parameters to be used with provided method. Defaults to None. + chg_out_dir (Optional[str], optional): Path to the directory where to save the charges. Defaults to current working directory. + """""" + chargefw2.save_charges(charges, molecules, method_name, parameters_name, chg_out_dir) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/chargefw2/base.py",".py","4292","126","""""""Base class for ChargeFW2 integration."""""" + +from typing import Dict +from abc import ABC, abstractmethod + +from models.calculation import Charges +from chargefw2 import Molecules +from models.method import Method +from models.parameters import Parameters + + +class ChargeFW2Base(ABC): + """"""Service for interaction with the ChargeFW2 framework."""""" + + @abstractmethod + def molecules( + self, + file_path: str, + read_hetatm: bool = True, + ignore_water: bool = False, + permissive_types: bool = True, + ) -> Molecules: + """"""Load molecules from a file + + Args: + file_path (str): File path from which to load molecules. + read_hetatm (bool, optional): Read HETATM records from PDB/mmCIF files. Defaults to True. + ignore_water (bool, optional): Discard water molecules from PDB/mmCIF files. Defaults to False. + permissive_types (bool, optional): Use similar parameters for similar atom/bond types if no exact match is found. Defaults to False. + + Returns: + Molecules: Parsed molecules + """""" + raise NotImplementedError() + + @abstractmethod + def get_available_methods( + self, + ) -> list[Method]: + """"""Get all available methods. + + Returns: + list[str]: List of method names. + """""" + raise NotImplementedError() + + @abstractmethod + def get_available_parameters(self, method: str) -> list[Parameters]: + """"""Get all parameters available for provided method. + + Args: + method (str): Method name. + + Returns: + list[str]: List of parameter names. + """""" + raise NotImplementedError() + + @abstractmethod + def get_best_parameters( + self, molecules: Molecules, method: str, permissive_types: bool + ) -> Parameters: + """"""Get best parameters for provided method. + + Args: + method (str): Method name. + molecules (chargefw2.Molecules): Set of molecules. + permissive_types (bool): Use similar parameters for similar atom/bond types if no exact match is found. + + Returns: + Parameters: Best Parameters for provided method. + + """""" + raise NotImplementedError() + + @abstractmethod + def get_suitable_methods(self, molecules: Molecules) -> list[tuple[Method, list[Parameters]]]: + """"""Get methods and parameters that are suitable for a given set of molecules. + + Args: + molecules (chargefw2.Molecules): Set of molecules. + + Returns: + list[tuple[str, list[str]]]: List of tuples containing method name and parameters for that method. + """""" + raise NotImplementedError() + + @abstractmethod + def calculate_charges( + self, + molecules: Molecules, + method_name: str, + parameters_name: str | None = None, + chg_out_dir: str | None = None, + ) -> Charges: + """"""Calculate partial atomic charges for a given molecules and method. + + Args: + molecules (chargefw2.Molecules): Set of molecules. + method_name (str): Method name to be used. + parameters_name (Optional[str], optional):Parameters to be used with provided method. Defaults to None. + + Returns: + Dict[str, list[float]]: Dictionary with molecule names as keys and list of charges (floats) as values. + """""" + raise NotImplementedError() + + def save_charges( + self, + charges: Dict[str, list[float]], + molecules: Molecules, + method_name: str, + parameters_name: str | None = None, + chg_out_dir: str | None = None, + ) -> None: + """"""Save charges for a given molecules and method. + + Args: + charges (Dict[str, list[float]]): Dictionary with molecule names as keys and list of charges (floats) as values. + molecules (chargefw2.Molecules): Set of molecules. + method_name (str): Method name to be used. + parameters_name (Optional[str], optional): Parameters to be used with provided method. Defaults to None. + chg_out_dir (Optional[str], optional): Path to the directory where to save the charges. Defaults to current working directory. + """""" + raise NotImplementedError() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/io/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/io/io.py",".py","3224","108","""""""Module for IO operations."""""" + +import datetime +import hashlib +import os +import pathlib +import shutil + + +import aiofiles +from dotenv import load_dotenv +from fastapi import UploadFile + +from .base import IOBase + +load_dotenv() + + +class IOLocal(IOBase): + """"""Local IO operations."""""" + + def mkdir(self, path: str) -> str: + os.makedirs(path, exist_ok=True) + return path + + def rmdir(self, path: str) -> None: + shutil.rmtree(path) + + def rm(self, path: str) -> None: + os.remove(path) + + def cp(self, path_src: str, path_dst: str) -> str: + return shutil.copy(path_src, path_dst) + + def symlink(self, path_src: str, path_dst: str) -> None: + os.symlink(path_src, path_dst) + + def last_modified(self, path: str) -> datetime.datetime: + ppath = pathlib.Path(path) + if ppath.exists(): + timestamp = ppath.lstat().st_mtime + return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) + + return 0.0 + + def dir_size(self, path: str) -> int: + # Also checking if path exsits since broken symlinks will throw an error + return sum(p.lstat().st_size if p.exists() else 0 for p in pathlib.Path(path).rglob(""*"")) + + def file_size(self, path: str) -> int: + # Also checking if path exsits since broken symlinks will throw an error + ppath = pathlib.Path(path) + return ppath.lstat().st_size if ppath.exists() else 0 + + def zip(self, path: str, destination: str) -> str: + return shutil.make_archive(destination, ""zip"", path) + + def listdir(self, directory: str = ""."") -> list[str]: + try: + return os.listdir(directory) + except FileNotFoundError: + return [] + + async def store_upload_file(self, file: UploadFile, directory: str) -> tuple[str, str]: + tmp_path: str = os.path.join(directory, IOBase.get_unique_filename(file.filename or ""file"")) + hasher = hashlib.sha256() + chunk_size = 1024 * 1024 # 1 MB + + async with aiofiles.open(tmp_path, ""wb"") as out_file: + while content := await file.read(chunk_size): + unix_content = content.replace(b""\r"", b"""") + await out_file.write(unix_content) + hasher.update(unix_content) + + # add hash to file name + file_hash = hasher.hexdigest() + new_filename = os.path.join(directory, f""{file_hash}_{file.filename}"") + os.rename(tmp_path, new_filename) + + return new_filename, file_hash + + async def write_file(self, path: str, content: str) -> None: + """"""Writes content to a file. + + Args: + path (str): Path to the file. + content (str): Content to write to the file. + """""" + + async with aiofiles.open(path, ""w"") as out_file: + await out_file.write(content) + + async def read_file(self, path: str) -> str: + """"""Reads content from a file. + + Args: + path (str): Path to the file. + + Returns: + str: Content of the file. + """""" + + async with aiofiles.open(path, ""r"") as in_file: + return await in_file.read() + + def path_exists(self, path: str) -> bool: + return os.path.exists(path) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/app/integrations/io/base.py",".py","4469","169","""""""Base class for the file system interaction service."""""" + +from abc import ABC, abstractmethod +import datetime +import os +import uuid + +from fastapi import UploadFile + + +class IOBase(ABC): + """"""Service for interaction with the file system."""""" + + @abstractmethod + def mkdir(self, path: str) -> str: + """"""Creates directory. + + Args: + path (str): Path to the directory which will be created. + + Returns: + str: Path to the created directory. + """""" + raise NotImplementedError() + + @abstractmethod + def rmdir(self, path: str) -> None: + """"""Removes directory. + + Args: + path (str): Path to the directory which will be removed. + """""" + raise NotImplementedError() + + @abstractmethod + def rm(self, path: str) -> None: + """"""Removes file. + + Args: + path (str): Path to the file which will be removed. + """""" + raise NotImplementedError() + + @abstractmethod + def last_modified(self, path: str) -> datetime.datetime: + """"""Returns the last modified time of a file. + + Args: + path (str): Path to the file. + + Returns: + datetime.datetime: Last modified utc timestamp. + """""" + raise NotImplementedError() + + @abstractmethod + def dir_size(self, path: str) -> int: + """"""Returns the size of a directory. + + Args: + path (str): Path to the directory. + + Returns: + int: Size of the directory in bytes. + """""" + raise NotImplementedError() + + @abstractmethod + def file_size(self, path: str) -> int: + """"""Returns the size of a file. + + Args: + path (str): Path to the file. + + Returns: + int: Size of the file in bytes. + """""" + raise NotImplementedError() + + @abstractmethod + def cp(self, path_src: str, path_dst: str) -> str: + """"""Copies file from 'path_src' to 'path_dst'. + + Args: + path_src (str): Location of a file to copy. + path_dst (str): Where to copy the file. + + Returns: + str: Path to the copied file. + """""" + raise NotImplementedError() + + @abstractmethod + def symlink(self, path_src: str, path_dst: str) -> None: + """"""Creates a symlink from path_src to path_dst. + + Args: + path_src (str): Location of a file to symlink. + path_dst (str): Where to symlink the file. + """""" + raise NotImplementedError() + + @abstractmethod + def zip(self, path: str, destination: str) -> str: + """"""Zips the provided directory. + + Args: + path (str): Path to directory to zip. + destination (str): Where to store the zipped directory (without extension). + + Returns: + str: Path to the zipped directory. + """""" + raise NotImplementedError() + + @abstractmethod + def listdir(self, directory: str = ""."") -> list[str]: + """"""Lists contents of the provided directory. + + Args: + directory (str): Directory to list. + + Returns: + str: List containing the names of the entries in the provided directory. + """""" + raise NotImplementedError() + + @abstractmethod + async def store_upload_file(self, file: UploadFile, directory: str) -> tuple[str, str]: + """"""Stores the provided file on disk. + + Args: + file (UploadFile): File to be stored. + directory (str): Path to an existing directory. + + Returns: + tuple[str, str]: Tuple containing path to the file and hash of the file contents. + """""" + raise NotImplementedError() + + @abstractmethod + async def write_file(self, path: str, content: str) -> None: + """"""Writes content to a file. + + Args: + path (str): Path to the file. + content (str): Content to write to the file. + """""" + raise NotImplementedError() + + @abstractmethod + def path_exists(self, path: str) -> bool: + """"""Check if the provided path exists. + + Args: + path (str): Path to verify. + + Returns: + bool: True if the path exists, otherwise False. + """""" + raise NotImplementedError() + + @staticmethod + def get_unique_filename(filename: str) -> str: + """"""Generate unique filename."""""" + + base, ext = os.path.splitext(filename) + return f""{str(uuid.uuid4())}_{base}{ext}"" +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/conftest.py",".py","150","7","import sys +from pathlib import Path + +# Add the project root to Python path +project_root = Path(__file__).parent +sys.path.insert(0, str(project_root)) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/services/test_calculation_storage.py",".py","15915","468","import pytest +from unittest.mock import Mock, MagicMock, patch +from datetime import datetime + +from models.calculation import ( + CalculationConfigDto, + CalculationDto, + CalculationResultDto, + CalculationSetPreviewDto, +) +from models.paging import PagedList +from models.molecule_info import MoleculeSetStats +from models.setup import AdvancedSettingsDto +from db.schemas.user import User # noqa: F401 +from db.schemas.calculation import ( + AdvancedSettings, + Calculation, + CalculationConfig, + CalculationSet, + CalculationSetStats, +) +from db.schemas.stats import ( + AtomTypeCount as AtomTypeCountModel, + MoleculeSetStats as MoleculeSetStatsModel, +) +from db.repositories.calculation_set_repository import CalculationSetFilters +from services.calculation_storage import CalculationStorageService + + +@pytest.fixture +def logger_mock(): + return Mock() + + +@pytest.fixture +def set_repository_mock(): + return Mock() + + +@pytest.fixture +def calculation_repository_mock(): + return Mock() + + +@pytest.fixture +def config_repository_mock(): + return Mock() + + +@pytest.fixture +def stats_repository_mock(): + return Mock() + + +@pytest.fixture +def advanced_settings_repository_mock(): + return Mock() + + +@pytest.fixture +def session_manager_mock(): + session = MagicMock() + + context_manager = MagicMock() + context_manager.__enter__.return_value = session + + session_manager = Mock() + session_manager.session.return_value = context_manager + return session_manager + + +@pytest.fixture +def service( + logger_mock, + set_repository_mock, + calculation_repository_mock, + config_repository_mock, + stats_repository_mock, + advanced_settings_repository_mock, + session_manager_mock, +): + return CalculationStorageService( + logger=logger_mock, + set_repository=set_repository_mock, + calculation_repository=calculation_repository_mock, + config_repository=config_repository_mock, + stats_repository=stats_repository_mock, + advanced_settings_repository=advanced_settings_repository_mock, + session_manager=session_manager_mock, + ) + + +@pytest.fixture +def sample_molecule_set_stats(): + return MoleculeSetStatsModel( + file_hash=""hash123"", + total_molecules=10, + total_atoms=100, + atom_type_counts=[ + AtomTypeCountModel(symbol=""C"", count=50), + AtomTypeCountModel(symbol=""H"", count=30), + AtomTypeCountModel(symbol=""O"", count=20), + ], + ) + + +@pytest.fixture +def sample_advanced_settings(): + return AdvancedSettingsDto( + read_hetatm=True, + ignore_water=False, + permissive_types=True, + ) + + +@pytest.fixture +def sample_advanced_settings_entity(): + return AdvancedSettings( + read_hetatm=True, + ignore_water=False, + permissive_types=True, + ) + + +@pytest.fixture +def sample_calculation_config(): + return CalculationConfigDto(method=""method1"", parameters=""params1"") + + +@pytest.fixture +def sample_calculation_config_entity(): + return CalculationConfig(method=""method1"", parameters=""params1"") + + +@pytest.fixture +def sample_calculation_result(sample_calculation_config): + return CalculationResultDto( + config=sample_calculation_config, + calculations=[ + CalculationDto( + file=""file1.mol"", + file_hash=""hash123"", + charges={}, + config=sample_calculation_config, + ) + ], + ) + + +@pytest.fixture +def sample_calculation_set(sample_advanced_settings_entity, sample_calculation_config_entity): + calculation_set = CalculationSet( + id=""d55a7af3-d1ee-4884-bce0-805efd5e1e64"", + user_id=""user123"", + created_at=datetime.now(), + advanced_settings=sample_advanced_settings_entity, + configs=[sample_calculation_config_entity], + molecule_set_stats_associations=[ + CalculationSetStats(molecule_set_id=""hash123"", file_name=""file1.mol"") + ], + ) + + return calculation_set + + +class TestCalculationStorageService: + def test_get_info( + self, + service, + session_manager_mock, + stats_repository_mock, + sample_molecule_set_stats, + ): + """"""Test get_info method returns a value."""""" + + session = session_manager_mock.session().__enter__() + stats_repository_mock.get.return_value = sample_molecule_set_stats + + result = service.get_info(session, ""hash123"") + + stats_repository_mock.get.assert_called_once_with(session, ""hash123"") + assert result is not None + assert result.total_molecules == 10 + assert result.total_atoms == 100 + assert len(result.atom_type_counts) == 3 + assert result.atom_type_counts[0].symbol == ""C"" + assert result.atom_type_counts[0].count == 50 + + def test_get_info_none(self, service, session_manager_mock, stats_repository_mock): + """"""Test get_info method returns None when no value is found."""""" + + session = session_manager_mock.session().__enter__() + stats_repository_mock.get.return_value = None + + result = service.get_info(session, ""nonexistent"") + + stats_repository_mock.get.assert_called_once_with(session, ""nonexistent"") + assert result is None + + def test_get_calculations( + self, + service, + session_manager_mock, + set_repository_mock, + sample_calculation_set, + stats_repository_mock, + ): + """"""Test get_calculations method returns a PagedList of CalculationSetPreviewDtos."""""" + + set_repository_mock.get_all.return_value = PagedList(items=[sample_calculation_set]) + + molecule_set_stats = MoleculeSetStats( + { + ""total_molecules"": 10, + ""total_atoms"": 100, + ""atom_type_counts"": [ + {""symbol"": ""C"", ""count"": 50}, + {""symbol"": ""H"", ""count"": 30}, + {""symbol"": ""O"", ""count"": 20}, + ], + } + ) + + with patch.object(service, ""get_info"", return_value=molecule_set_stats): + filters = CalculationSetFilters( + page=1, page_size=10, order_by=""created_at"", order=""desc"" + ) + result = service.get_calculations(filters) + + set_repository_mock.get_all.assert_called_once_with( + session_manager_mock.session().__enter__(), filters + ) + assert isinstance(result, PagedList) + assert len(result.items) == 1 + assert isinstance(result.items[0], CalculationSetPreviewDto) + assert str(result.items[0].id) == ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + assert len(result.items[0].files) == 1 + assert ""file1.mol"" in result.items[0].files + + def test_get_calculation_set( + self, + service, + session_manager_mock, + set_repository_mock, + sample_calculation_set, + ): + """"""Test get_calculation_set method returns a calculation set."""""" + + set_repository_mock.get.return_value = sample_calculation_set + + result = service.get_calculation_set(""d55a7af3-d1ee-4884-bce0-805efd5e1e64"") + + set_repository_mock.get.assert_called_once_with( + session_manager_mock.session().__enter__(), ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + ) + assert result == sample_calculation_set + + def test_store_file_info(self, service, session_manager_mock, stats_repository_mock): + """"""Test store_file_info method stores a MoleculeSetStats object."""""" + + molecule_set_stats = MoleculeSetStats( + { + ""total_molecules"": 10, + ""total_atoms"": 100, + ""atom_type_counts"": [ + {""symbol"": ""C"", ""count"": 50}, + {""symbol"": ""H"", ""count"": 30}, + {""symbol"": ""O"", ""count"": 20}, + ], + } + ) + + stats_repository_mock.store.return_value = molecule_set_stats + + result = service.store_file_info(""hash123"", molecule_set_stats) + + assert stats_repository_mock.store.call_count == 1 + store_arg = stats_repository_mock.store.call_args[0][1] + assert store_arg.file_hash == ""hash123"" + assert store_arg.total_molecules == 10 + assert store_arg.total_atoms == 100 + assert len(store_arg.atom_type_counts) == 3 + assert result == molecule_set_stats + + def test_store_calculation_results_new_set( + self, + service, + session_manager_mock, + set_repository_mock, + calculation_repository_mock, + advanced_settings_repository_mock, + config_repository_mock, + stats_repository_mock, + sample_advanced_settings, + sample_advanced_settings_entity, + sample_calculation_result, + sample_calculation_config_entity, + ): + """"""Test store_calculation_results method stores a new calculation set."""""" + + session = session_manager_mock.session().__enter__() + + set_repository_mock.get.return_value = None + advanced_settings_repository_mock.get.return_value = sample_advanced_settings_entity + config_repository_mock.get.return_value = sample_calculation_config_entity + stats_repository_mock.get.return_value = MoleculeSetStatsModel( + file_hash=""hash123"", total_molecules=10, total_atoms=100, atom_type_counts=[] + ) + calculation_repository_mock.get.return_value = None + + service.store_calculation_results( + ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"", + sample_advanced_settings, + [sample_calculation_result], + ""user123"", + ) + + set_repository_mock.get.assert_called_once_with( + session, ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + ) + advanced_settings_repository_mock.get.assert_called_once() + config_repository_mock.get.assert_called_once_with(session, ""method1"", ""params1"") + assert set_repository_mock.store.call_count == 2 + assert calculation_repository_mock.store.call_count == 1 + + calc_arg = calculation_repository_mock.store.call_args[0][1] + assert calc_arg.file_name == ""file1.mol"" + assert calc_arg.file_hash == ""hash123"" + assert calc_arg.config == sample_calculation_config_entity + + def test_store_calculation_results_existing_set( + self, + service, + session_manager_mock, + set_repository_mock, + calculation_repository_mock, + advanced_settings_repository_mock, + config_repository_mock, + stats_repository_mock, + sample_advanced_settings, + sample_advanced_settings_entity, + sample_calculation_result, + sample_calculation_config_entity, + sample_calculation_set, + ): + """"""Test store_calculation_results method updates an existing calculation set."""""" + + session = session_manager_mock.session().__enter__() + + set_repository_mock.get.return_value = sample_calculation_set + advanced_settings_repository_mock.get.return_value = sample_advanced_settings_entity + config_repository_mock.get.return_value = sample_calculation_config_entity + stats_repository_mock.get.return_value = MoleculeSetStatsModel( + file_hash=""hash123"", total_molecules=10, total_atoms=100, atom_type_counts=[] + ) + calculation_repository_mock.get.return_value = None + + service.store_calculation_results( + ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"", + sample_advanced_settings, + [sample_calculation_result], + ""user123"", + ) + + set_repository_mock.get.assert_called_once_with( + session, ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + ) + set_repository_mock.store.assert_called_once_with(session, sample_calculation_set) + assert calculation_repository_mock.store.call_count == 1 + + def test_setup_calculation( + self, + service, + session_manager_mock, + set_repository_mock, + advanced_settings_repository_mock, + stats_repository_mock, + sample_advanced_settings, + sample_advanced_settings_entity, + ): + """"""Test setup_calculation method creates a new calculation set."""""" + + session = session_manager_mock.session().__enter__() + advanced_settings_repository_mock.get.return_value = sample_advanced_settings_entity + stats_repository_mock.get.return_value = MoleculeSetStatsModel( + file_hash=""hash123"", total_molecules=10, total_atoms=100, atom_type_counts=[] + ) + + service.setup_calculation( + ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"", sample_advanced_settings, [""hash123""], ""user123"" + ) + + advanced_settings_repository_mock.get.assert_called_once() + stats_repository_mock.get.assert_called_once_with(session, ""hash123"") + set_repository_mock.store.assert_called_once() + + calc_set_arg = set_repository_mock.store.call_args[0][1] + assert calc_set_arg.id == ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + assert calc_set_arg.user_id == ""user123"" + assert calc_set_arg.advanced_settings == sample_advanced_settings_entity + assert len(calc_set_arg.molecule_set_stats) == 1 + + def test_filter_existing_calculations( + self, + service, + session_manager_mock, + calculation_repository_mock, + sample_advanced_settings, + sample_calculation_config, + ): + """"""Test filter_existing_calculations method correctly filters calculations."""""" + + # for the first file+config combination, return None (not in DB) + # for the second file+config combination, return an existing calculation + def mock_get_side_effect(session, filters): + if filters.hash == ""hash123"": + return None + else: + calculation = Calculation( + file_name=""file2.mol"", + file_hash=""hash456"", + charges={}, + config=CalculationConfig(method=""method1"", parameters=""params1""), + advanced_settings=AdvancedSettings( + read_hetatm=True, ignore_water=False, permissive_types=True + ), + ) + return calculation + + calculation_repository_mock.get.side_effect = mock_get_side_effect + + to_calculate, cached = service.filter_existing_calculations( + sample_advanced_settings, [""hash123"", ""hash456""], [sample_calculation_config] + ) + + assert len(to_calculate) == 1 + assert sample_calculation_config in to_calculate + assert to_calculate[sample_calculation_config] == [""hash123""] + + assert len(cached) == 1 + assert sample_calculation_config in cached + assert len(cached[sample_calculation_config]) == 1 + assert cached[sample_calculation_config][0].file_hash == ""hash456"" + + def test_get_calculation_results_not_found( + self, service, session_manager_mock, set_repository_mock + ): + """"""Test get_calculation_results method returns an empty list when no value is found."""""" + + session = session_manager_mock.session().__enter__() + set_repository_mock.get.return_value = None + + results = service.get_calculation_results(""nonexistent"") + + set_repository_mock.get.assert_called_once_with(session, ""nonexistent"") + assert results == [] + + def test_delete_calculation_set(self, service, session_manager_mock, set_repository_mock): + """"""Test delete_calculation_set method deletes a calculation_set."""""" + + session = session_manager_mock.session().__enter__() + + service.delete_calculation_set(""d55a7af3-d1ee-4884-bce0-805efd5e1e64"") + + set_repository_mock.delete.assert_called_once_with( + session, ""d55a7af3-d1ee-4884-bce0-805efd5e1e64"" + ) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/services/test_io_service.py",".py","26144","664","import datetime +import json +from pathlib import Path +from unittest.mock import AsyncMock, Mock, patch +import pytest + +from app.models.calculation import CalculationConfigDto +from app.services.io import IOService + + +@pytest.fixture +def async_io_mock(): + return AsyncMock() + + +@pytest.fixture +def io_mock(): + return Mock() + + +@pytest.fixture +def logger_mock(): + return Mock() + + +@pytest.fixture +def io_service(io_mock, logger_mock): + return IOService(io_mock, logger_mock) + + +@pytest.fixture +def async_io_service(async_io_mock, logger_mock): + return IOService(async_io_mock, logger_mock) + + +@pytest.fixture +def test_data(): + return { + ""user_id"": ""test-user-id"", + ""computation_id"": ""test-computation-id"", + ""file_hash"": ""a"" * 64, # sha256 + ""filename"": f""{'' * 64}_test-file-name"", + } + + +class TestIOService: + def test_create_dir(self, io_service, io_mock, logger_mock): + """"""Test creating a directory."""""" + test_path = ""/path/to/test/dir"" + io_mock.path_exists.return_value = False + + io_service.create_dir(test_path) + + io_mock.mkdir.assert_called_once_with(test_path) + logger_mock.info.assert_called_once() + + def test_create_dir_exception(self, io_service, io_mock, logger_mock): + """"""Test handling exceptions when creating a directory."""""" + test_path = ""/path/to/test/dir"" + io_mock.path_exists.return_value = False + + io_mock.mkdir.side_effect = Exception(""Directory creation failed"") + + with pytest.raises(Exception): + io_service.create_dir(test_path) + + logger_mock.error.assert_called_once() + + def test_cp(self, io_service, io_mock, logger_mock): + """"""Test copying a file."""""" + path_from = ""/source/path"" + path_to = ""/destination/path"" + expected_path = ""/destination/path/file.txt"" + + io_mock.cp.return_value = expected_path + + result = io_service.cp(path_from, path_to) + + io_mock.cp.assert_called_once_with(path_from, path_to) + assert result == expected_path + logger_mock.info.assert_called_once() + + def test_cp_exception(self, io_service, io_mock, logger_mock): + """"""Test handling exceptions when copying a file."""""" + path_from = ""/source/path"" + path_to = ""/destination/path"" + + io_mock.cp.side_effect = Exception(""File copy failed"") + + with pytest.raises(Exception): + io_service.cp(path_from, path_to) + + logger_mock.error.assert_called_once() + + def test_remove_file(self, io_service, io_mock, logger_mock, test_data): + """"""Test removing a file."""""" + filepath = f""/test/path/{test_data['filename']}"" + with patch.object(io_service, ""get_filepath"", return_value=filepath): + io_service.remove_file(test_data[""file_hash""], test_data[""user_id""]) + + io_mock.rm.assert_called_once_with(filepath) + logger_mock.info.assert_called_once() + + def test_remove_file_not_found(self, io_service, io_mock, test_data): + """"""Test handling when file to remove is not found."""""" + with patch.object(io_service, ""get_filepath"", return_value=None): + io_service.remove_file(test_data[""file_hash""], test_data[""user_id""]) + + io_mock.rm.assert_not_called() + + def test_remove_file_exception(self, io_service, io_mock, logger_mock, test_data): + """"""Test handling exceptions when removing a file."""""" + filepath = f""/test/path/{test_data['filename']}"" + with patch.object(io_service, ""get_filepath"", return_value=filepath): + io_mock.rm.side_effect = Exception(""Failed to remove file"") + + with pytest.raises(Exception): + io_service.remove_file(test_data[""file_hash""], test_data[""user_id""]) + + logger_mock.error.assert_called_once() + + def test_zip_charges(self, io_service, io_mock): + """"""Test creating an archive from directory."""""" + directory = ""/test/directory"" + archive_path = ""/test/directory/archive"" + expected_result = f""{archive_path}.zip"" + + io_mock.listdir.return_value = [ + ""hash1_file1.pqr"", + ""hash1_file2.txt"", + ""hash1_file3.mol2"", + ""hash1_file4.cif"", + ] + io_mock.zip.return_value = expected_result + + with patch.object(io_service, ""parse_filename"", return_value=(""hash"", ""filename"")): + result = io_service.zip_charges(directory) + + assert io_mock.mkdir.call_count == 5 # archive dir + 4 extension dirs + + assert io_mock.cp.call_count == len(io_mock.listdir.return_value) + + io_mock.zip.assert_called_once_with(archive_path, archive_path) + assert result == expected_result + + def test_zip_charges_exception(self, io_service, io_mock, logger_mock): + """"""Test handling exceptions when creating an archive."""""" + directory = ""/test/directory"" + io_mock.path_exists.return_value = False + + io_mock.mkdir.side_effect = Exception(""Failed to create directory"") + + with pytest.raises(Exception): + io_service.zip_charges(directory) + + logger_mock.error.assert_called_once() + + def test_listdir(self, io_service, io_mock): + """"""Test listing directory contents."""""" + directory = ""/test/directory"" + expected_files = [""file1.txt"", ""file2.txt""] + + io_mock.listdir.return_value = expected_files + + result = io_service.listdir(directory) + + io_mock.listdir.assert_called_once_with(directory) + assert result == expected_files + + def test_path_exists(self, io_service, io_mock): + """"""Test checking if path exists."""""" + path = ""/test/path"" + + # path exists + io_mock.path_exists.return_value = True + result = io_service.path_exists(path) + + io_mock.path_exists.assert_called_once_with(path) + assert result is True + + # path doesn't exist + io_mock.path_exists.reset_mock() + io_mock.path_exists.return_value = False + result = io_service.path_exists(path) + + io_mock.path_exists.assert_called_once_with(path) + assert result is False + + def test_get_storage_path(self, io_service): + """"""Test getting storage path."""""" + # logged in user + user_id = ""test_user"" + result = io_service.get_storage_path(user_id) + expected = str(io_service.workdir / ""user"" / user_id) + assert result == expected + + # guest user + result = io_service.get_storage_path(None) + expected = str(io_service.workdir / ""guest"") + assert result == expected + + def test_get_file_storage_path(self, io_service): + """"""Test getting file storage path."""""" + # logged in user + user_id = ""test_user"" + result = io_service.get_file_storage_path(user_id) + expected = str(io_service.workdir / ""user"" / user_id / ""files"") + assert result == expected + + # guest user + result = io_service.get_file_storage_path(None) + expected = str(io_service.workdir / ""guest"" / ""files"") + assert result == expected + + def test_get_computations_path(self, io_service): + """"""Test getting computations path."""""" + # logged in user + user_id = ""test_user"" + result = io_service.get_computations_path(user_id) + expected = str(io_service.workdir / ""user"" / user_id / ""computations"") + assert result == expected + + # guest user + result = io_service.get_computations_path(None) + expected = str(io_service.workdir / ""guest"" / ""computations"") + assert result == expected + + def test_get_computation_path(self, io_service): + """"""Test getting computation path."""""" + computation_id = ""test_comp"" + + # logged in user + user_id = ""test_user"" + result = io_service.get_computation_path(computation_id, user_id) + expected = str(io_service.workdir / ""user"" / user_id / ""computations"" / computation_id) + assert result == expected + + # guest user + result = io_service.get_computation_path(computation_id, None) + expected = str(io_service.workdir / ""guest"" / ""computations"" / computation_id) + assert result == expected + + def test_get_inputs_path(self, io_service): + """"""Test getting inputs path."""""" + computation_id = ""test_comp"" + + # logged in user + user_id = ""test_user"" + result = io_service.get_inputs_path(computation_id, user_id) + expected = str( + io_service.workdir / ""user"" / user_id / ""computations"" / computation_id / ""input"" + ) + assert result == expected + + # guest user + result = io_service.get_inputs_path(computation_id, None) + expected = str(io_service.workdir / ""guest"" / ""computations"" / computation_id / ""input"") + assert result == expected + + def test_get_charges_path(self, io_service): + """"""Test getting charges path."""""" + computation_id = ""test_comp"" + + # logged in user + user_id = ""test_user"" + result = io_service.get_charges_path(computation_id, user_id) + expected = str( + io_service.workdir / ""user"" / user_id / ""computations"" / computation_id / ""charges"" + ) + assert result == expected + + # guest user + result = io_service.get_charges_path(computation_id, None) + expected = str(io_service.workdir / ""guest"" / ""computations"" / computation_id / ""charges"") + assert result == expected + + def test_get_example_path(self, io_service): + """"""Test getting example path."""""" + example_id = ""test_example"" + + result = io_service.get_example_path(example_id) + expected = str(io_service.examples_dir / example_id) + + assert result == expected + + def test_prepare_inputs(self, io_service, io_mock, test_data): + """"""Test preparing input files for computation."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + file_hashes = [test_data[""file_hash""]] + + inputs_path = ""/test/inputs/path"" + files_path = ""/test/files/path"" + with ( + patch.object(io_service, ""get_inputs_path"", return_value=inputs_path), + patch.object(io_service, ""get_file_storage_path"", return_value=files_path), + ): + io_mock.listdir.return_value = [test_data[""filename""]] + with patch.object( + io_service, ""parse_filename"", return_value=(test_data[""file_hash""], ""test_file.txt"") + ): + io_service.prepare_inputs(user_id, computation_id, file_hashes) + + src_path = str(Path(files_path) / test_data[""filename""]) + dst_path = str(Path(inputs_path) / test_data[""filename""]) + io_mock.symlink.assert_called_once_with(src_path, dst_path) + + def test_prepare_inputs_file_not_found(self, io_service, io_mock, logger_mock, test_data): + """"""Test preparing inputs when file is not found."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + file_hashes = [test_data[""file_hash""]] + + inputs_path = ""/test/inputs/path"" + files_path = ""/test/files/path"" + with ( + patch.object(io_service, ""get_inputs_path"", return_value=inputs_path), + patch.object(io_service, ""get_file_storage_path"", return_value=files_path), + ): + io_mock.listdir.return_value = [] + + io_service.prepare_inputs(user_id, computation_id, file_hashes) + + logger_mock.warn.assert_called_once() + io_mock.symlink.assert_not_called() + + @pytest.mark.asyncio + async def test_store_configs(self, async_io_service, async_io_mock, test_data): + """"""Test storing configs for computation."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + configs = [ + CalculationConfigDto(method=""method1"", parameters=""param1""), + CalculationConfigDto(method=""method2"", parameters=""param2""), + CalculationConfigDto(method=""method2"", parameters=None), + ] + + comp_path = ""/test/computation/path"" + with patch.object(async_io_service, ""get_computation_path"", return_value=comp_path): + await async_io_service.store_configs(computation_id, configs, user_id) + + config_path = str(Path(comp_path) / ""configs.json"") + expected_content = json.dumps([config.model_dump() for config in configs], indent=4) + async_io_mock.write_file.assert_called_once_with(config_path, expected_content) + + @pytest.mark.asyncio + async def test_store_configs_exception( + self, async_io_service, async_io_mock, logger_mock, test_data + ): + """"""Test handling exceptions when storing configs."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + configs = [CalculationConfigDto(method=""method1"", parameters=""param1"")] + + comp_path = ""/test/computation/path"" + with patch.object(async_io_service, ""get_computation_path"", return_value=comp_path): + async_io_mock.write_file.side_effect = Exception(""Failed to write file"") + + with pytest.raises(Exception): + await async_io_service.store_configs(computation_id, configs, user_id) + + logger_mock.error.assert_called_once() + + def test_get_filepath(self, io_service, io_mock, test_data): + """"""Test getting filepath for a file hash."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + filename = test_data[""filename""] + + storage_path = ""/test/files/path"" + with patch.object(io_service, ""get_file_storage_path"", return_value=storage_path): + io_mock.listdir.return_value = [filename] + + with patch.object( + io_service, ""parse_filename"", return_value=(file_hash, ""test_file.txt"") + ): + result = io_service.get_filepath(file_hash, user_id) + + expected_path = str(Path(storage_path) / filename) + assert result == expected_path + + def test_get_filepath_not_found(self, io_service, io_mock, logger_mock, test_data): + """"""Test getting filepath when file hash is not found."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + + storage_path = ""/test/files/path"" + with patch.object(io_service, ""get_file_storage_path"", return_value=storage_path): + io_mock.listdir.return_value = [""other_hash_file.txt""] + + with patch.object( + io_service, ""parse_filename"", return_value=(""other_hash"", ""file.txt"") + ): + result = io_service.get_filepath(file_hash, user_id) + + assert result is None + + def test_get_filepath_exception(self, io_service, io_mock, logger_mock, test_data): + """"""Test handling exceptions when getting filepath."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + + storage_path = ""/test/files/path"" + with patch.object(io_service, ""get_file_storage_path"", return_value=storage_path): + io_mock.listdir.side_effect = Exception(""Failed to list directory"") + + with pytest.raises(Exception): + io_service.get_filepath(file_hash, user_id) + + logger_mock.error.assert_called_once() + + def test_get_last_modification(self, io_service, io_mock, test_data): + """"""Test getting last modification time."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + file_path = f""/test/path/{test_data['filename']}"" + expected_time = datetime.datetime.now() + + with patch.object(io_service, ""get_filepath"", return_value=file_path): + io_mock.last_modified.return_value = expected_time + + result = io_service.get_last_modification(file_hash, user_id) + + io_mock.last_modified.assert_called_once_with(file_path) + assert result == expected_time + + def test_get_last_modification_exception(self, io_service, io_mock, logger_mock, test_data): + """"""Test handling exceptions when getting last modification time."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + file_path = f""/test/path/{test_data['filename']}"" + + with patch.object(io_service, ""get_filepath"", return_value=file_path): + io_mock.last_modified.side_effect = Exception(""Failed to get last modification time"") + + with pytest.raises(Exception): + io_service.get_last_modification(file_hash, user_id) + + logger_mock.error.assert_called_once() + + def test_get_file_size(self, io_service, io_mock, test_data): + """"""Test getting file size."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + file_path = f""/test/path/{test_data['filename']}"" + expected_size = 1024 + + with patch.object(io_service, ""get_filepath"", return_value=file_path): + io_mock.file_size.return_value = expected_size + + result = io_service.get_file_size(file_hash, user_id) + + io_mock.file_size.assert_called_once_with(file_path) + assert result == expected_size + + def test_get_file_size_exception(self, io_service, io_mock, logger_mock, test_data): + """"""Test handling exceptions when getting file size."""""" + file_hash = test_data[""file_hash""] + user_id = test_data[""user_id""] + file_path = f""/test/path/{test_data['filename']}"" + + with patch.object(io_service, ""get_filepath"", return_value=file_path): + io_mock.file_size.side_effect = Exception(""Failed to get file size"") + + with pytest.raises(Exception): + io_service.get_file_size(file_hash, user_id) + + logger_mock.error.assert_called_once() + + def test_free_guest_file_space_no_need(self, io_service, io_mock, logger_mock): + """"""Test freeing guest file space when there's enough space."""""" + path = ""/test/guest/files"" + amount_to_free = 1000 + + with patch.object(io_service, ""get_file_storage_path"", return_value=path): + # sufficient space + io_mock.dir_size.return_value = 1000 # currently using 1000 bytes + io_service.guest_file_quota = 10000 + + io_service.free_guest_file_space(amount_to_free) + + io_mock.rm.assert_not_called() + logger_mock.info.assert_called_with( + ""Guest file space is sufficient. No need to free space."" + ) + + def test_free_guest_file_space_success(self, io_service, io_mock, logger_mock): + """"""Test successfully freeing guest file space."""""" + path = ""/test/guest/files"" + amount_to_free = 1000 + + with patch.object(io_service, ""get_file_storage_path"", return_value=path): + # insufficient space + io_mock.dir_size.return_value = 2000 # currently using 2000 bytes + io_service.guest_file_quota = 2500 + + files = [""file1.txt"", ""file2.txt""] + io_mock.listdir.return_value = files + io_mock.last_modified.side_effect = [ + datetime.datetime(2023, 1, 1), # file1 is older + datetime.datetime(2023, 1, 2), # file2 is newer + ] + io_mock.file_size.return_value = 1000 # each file is 1000 bytes + + io_service.free_guest_file_space(amount_to_free) + + # oldest file was deleted + io_mock.rm.assert_called_once_with(str(Path(path) / ""file1.txt"")) + + def test_free_guest_file_space_not_enough_space(self, io_service, io_mock, logger_mock): + """"""Test freeing guest file space when there's not enough space to free."""""" + path = ""/test/guest/files"" + amount_to_free = 3000 + + with patch.object(io_service, ""get_file_storage_path"", return_value=path): + # insufficient space + io_mock.dir_size.return_value = 2000 # currently using 2000 bytes + io_service.guest_file_quota = 1000 # quota is smaller than used space + + with pytest.raises(ValueError, match=""Not enough space to free.""): + io_service.free_guest_file_space(amount_to_free) + + def test_free_guest_compute_space_no_need(self, io_service, io_mock, logger_mock): + """"""Test freeing guest compute space when there's enough space."""""" + path = ""/test/guest/computations"" + + with patch.object(io_service, ""get_computations_path"", return_value=path): + # insufficient space + io_mock.dir_size.return_value = 1000 # currently using 1000 bytes + io_service.guest_compute_quota = 2000 + + io_service.free_guest_compute_space() + + # Check no computations were deleted + io_mock.rmdir.assert_not_called() + logger_mock.info.assert_called_with( + ""Guest compute space is sufficient. No need to free space."" + ) + + def test_free_guest_compute_space_success(self, io_service, io_mock, logger_mock): + """"""Test successfully freeing guest compute space."""""" + path = ""/test/guest/computations"" + + with patch.object(io_service, ""get_computations_path"", return_value=path): + # insufficient space + io_mock.dir_size.return_value = 3000 # currently using 3000 bytes + io_service.guest_compute_quota = 2000 + + computations = [""comp1"", ""comp2""] + io_mock.listdir.return_value = computations + io_mock.last_modified.side_effect = [ + datetime.datetime(2023, 1, 1), # comp1 is older + datetime.datetime(2023, 1, 2), # comp2 is newer + ] + io_mock.dir_size.side_effect = [3000, 1500] + + io_service.free_guest_compute_space() + + # oldest computation was deleted + io_mock.rmdir.assert_called_once_with(str(Path(path) / ""comp1"")) + + def test_delete_computation(self, io_service, io_mock, test_data): + """"""Test deleting a computation."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + + comp_path = ""/test/computation/path"" + with patch.object(io_service, ""get_computation_path"", return_value=comp_path): + io_service.delete_computation(computation_id, user_id) + + io_mock.rmdir.assert_called_once_with(comp_path) + + def test_delete_computation_exception(self, io_service, io_mock, logger_mock, test_data): + """"""Test handling exceptions when deleting a computation."""""" + computation_id = test_data[""computation_id""] + user_id = test_data[""user_id""] + + comp_path = ""/test/computation/path"" + with patch.object(io_service, ""get_computation_path"", return_value=comp_path): + io_mock.rmdir.side_effect = Exception(""Failed to remove directory"") + + with pytest.raises(Exception): + io_service.delete_computation(computation_id, user_id) + + assert logger_mock.method_calls + + def test_parse_filename_valid(self, io_service): + """"""Test parsing valid filename."""""" + file_hash = ""a"" * 64 + file_name = ""test_file.txt"" + filename = f""{file_hash}_{file_name}"" + + result_hash, result_name = io_service.parse_filename(filename) + + assert result_hash == file_hash + assert result_name == file_name + + def test_parse_filename_invalid_format(self, io_service, logger_mock): + """"""Test parsing invalid filename format."""""" + filename = ""invalid-format-no-hash.txt"" # no underscore + + with pytest.raises(ValueError, match=""Invalid filename format""): + io_service.parse_filename(filename) + + logger_mock.error.assert_called_once() + + def test_parse_filename_invalid_hash_length(self, io_service, logger_mock): + """"""Test parsing filename with invalid hash length."""""" + file_hash = ""a"" * 10 # Only 10 chars instead of 64 + filename = f""{file_hash}_test_file.txt"" + + with pytest.raises(ValueError, match=""Invalid filename format""): + io_service.parse_filename(filename) + + logger_mock.error.assert_called_once() + + def test_get_quota_user(self, io_service, io_mock): + """"""Test getting quota for a user."""""" + user_id = ""test_user"" + storage_path = ""/test/user/path"" + used_space = 1000 + quota = 5000 + + with patch.object(io_service, ""get_storage_path"", return_value=storage_path): + io_mock.dir_size.return_value = used_space + io_service.user_quota = quota + + result_used, result_available, result_quota = io_service.get_quota(user_id) + + assert result_used == used_space + assert result_available == quota - used_space + assert result_quota == quota + + def test_get_quota_guest(self, io_service, io_mock): + """"""Test getting quota for a guest."""""" + storage_path = ""/test/guest/path"" + used_space = 1000 + file_quota = 2000 + compute_quota = 3000 + + with patch.object(io_service, ""get_storage_path"", return_value=storage_path): + io_mock.dir_size.return_value = used_space + io_service.guest_file_quota = file_quota + io_service.guest_compute_quota = compute_quota + + result_used, result_available, result_quota = io_service.get_quota(None) + + assert result_used == used_space + assert result_available == (file_quota + compute_quota) - used_space + assert result_quota == file_quota + compute_quota + + def test_environment_variables(self, io_service): + """"""Test that environment variables are properly loaded."""""" + assert isinstance(io_service.workdir, Path) + + assert isinstance(io_service.examples_dir, Path) + + assert isinstance(io_service.user_quota, int) + assert isinstance(io_service.guest_file_quota, int) + assert isinstance(io_service.guest_compute_quota, int) + + assert isinstance(io_service.max_file_size, int) + assert isinstance(io_service.max_upload_size, int) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/services/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/services/test_chargefw2_service.py",".py","12967","369","from typing import Literal +from unittest.mock import AsyncMock, Mock +import pytest + +from app.models.method import Method +from app.models.parameters import Parameters +from app.models.calculation import ( + CalculationConfigDto, + CalculationDto, + CalculationResultDto, +) +from app.models.setup import AdvancedSettingsDto +from app.models.suitable_methods import SuitableMethods +from app.services.chargefw2 import ChargeFW2Service + + +@pytest.fixture +def chargefw2_mock(): + return Mock() + + +@pytest.fixture +def logger_mock(): + return Mock() + + +@pytest.fixture +def io_mock(): + mock = Mock() + mock.parse_filename = Mock(side_effect=lambda f: (f.split(""_"")[0], f.split(""_"")[1])) + mock.listdir = Mock(return_value=[""hash1_file1.pdb"", ""hash2_file2.pdb""]) + mock.get_file_storage_path = Mock(return_value=""/storage"") + mock.get_inputs_path = Mock(return_value=""/inputs"") + mock.get_charges_path = Mock(return_value=""/charges"") + mock.create_dir = Mock() + mock.store_configs = AsyncMock() + mock.path_exists = Mock(return_value=True) + return mock + + +@pytest.fixture +def mmcif_service_mock(): + return Mock() + + +@pytest.fixture +def calculation_storage_mock(): + mock = Mock() + mock.get_calculation_set = Mock(return_value=None) + return mock + + +@pytest.fixture +def service(chargefw2_mock, logger_mock, io_mock, mmcif_service_mock, calculation_storage_mock): + return ChargeFW2Service( + chargefw2=chargefw2_mock, + logger=logger_mock, + io=io_mock, + mmcif_service=mmcif_service_mock, + calculation_storage=calculation_storage_mock, + max_workers=2, + max_concurrent_calculations=2, + ) + + +def get_method( + internal_name: str, + name: str = """", + fullName: str = """", + publication: str = """", + type: Literal[""2D"", ""3D"", ""other""] = ""3D"", + has_parameters: bool = False, +) -> Method: + return Method( + internal_name=internal_name, + name=name, + full_name=fullName, + publication=publication, + type=type, + has_parameters=has_parameters, + ) + + +def get_parameters( + internal_name: str, full_name: str = """", method: str = """", publication: str = """" +) -> Parameters: + return Parameters( + internal_name=internal_name, full_name=full_name, method=method, publication=publication + ) + + +class TestChargeFW2Service: + def test_get_available_methods(self, service, chargefw2_mock): + """"""Test getting available methods."""""" + + expected_methods = [get_method(""method1""), get_method(""method2"")] + chargefw2_mock.get_available_methods.return_value = expected_methods + + result = service.get_available_methods() + + assert result == expected_methods + chargefw2_mock.get_available_methods.assert_called_once() + service.logger.info.assert_called_once_with(""Getting available methods."") + + def test_get_available_methods_error(self, service, chargefw2_mock): + """"""Test handling exceptions when creating a directory."""""" + + chargefw2_mock.get_available_methods.side_effect = Exception(""Test error"") + + with pytest.raises(Exception, match=""Test error""): + service.get_available_methods() + + service.logger.error.assert_called_once() + + @pytest.mark.asyncio + async def test_get_available_parameters(self, service, chargefw2_mock): + """"""Test getting available parameters."""""" + + method = ""method1"" + expected_params = [get_parameters(""param1""), get_parameters(""param2"")] + chargefw2_mock.get_available_parameters.return_value = expected_params + + result = await service.get_available_parameters(method) + + assert result == expected_params + chargefw2_mock.get_available_parameters.assert_called_once_with(method) + service.logger.info.assert_called_once_with( + f""Getting available parameters for method {method}."" + ) + + @pytest.mark.asyncio + async def test_get_best_parameters(self, service, chargefw2_mock): + """"""Test getting best parameters."""""" + + method = ""method1"" + file_path = ""/path/to/file.pdb"" + expected_params = get_parameters(""best_params"") + + molecules_mock = Mock() + service.read_molecules = AsyncMock(return_value=molecules_mock) + chargefw2_mock.get_best_parameters.return_value = expected_params + + result = await service.get_best_parameters(method, file_path) + + assert result == expected_params + service.read_molecules.assert_called_once_with(file_path) + chargefw2_mock.get_best_parameters.assert_called_once_with(molecules_mock, method, True) + + @pytest.mark.asyncio + async def test_read_molecules(self, service, chargefw2_mock): + """"""Test reading molecules."""""" + + file_path = ""/path/to/file.pdb"" + molecules_mock = Mock() + chargefw2_mock.molecules.return_value = molecules_mock + + result = await service.read_molecules(file_path, True, False, True) + + assert result == molecules_mock + chargefw2_mock.molecules.assert_called_once_with(file_path, True, False, True) + service.logger.info.assert_called_once_with(f""Loading molecules from file {file_path}."") + + @pytest.mark.asyncio + async def test_get_suitable_methods(self, service): + """"""Test getting suitable methods."""""" + + file_hashes = [""hash1"", ""hash2""] + + # _find_suitable_methods mocks + mock_suitable_methods = SuitableMethods( + methods=[get_method(""method1"")], parameters={""method1"": [get_parameters(""param1"")]} + ) + service._find_suitable_methods = AsyncMock(return_value=mock_suitable_methods) + + result = await service.get_suitable_methods(file_hashes, True, ""user123"") + + assert result == mock_suitable_methods + service._find_suitable_methods.assert_called_once_with(file_hashes, True, ""user123"") + service.logger.info.assert_called_once_with( + f""Getting suitable methods for file hashes '{file_hashes}'"" + ) + + @pytest.mark.asyncio + async def test_get_computation_suitable_methods(self, service, calculation_storage_mock): + """"""Test getting suitable methods for a computation."""""" + + computation_id = ""comp123"" + user_id = ""user123"" + + advanced_settings = AdvancedSettingsDto(permissive_types=True) + mock_calculation_set = Mock() + mock_calculation_set.advanced_settings = advanced_settings + calculation_storage_mock.get_calculation_set.return_value = mock_calculation_set + + # _find_suitable_methods mocks + mock_suitable_methods = SuitableMethods( + methods=[get_method(""method1"")], parameters={""method1"": [get_parameters(""param1"")]} + ) + service._find_suitable_methods = AsyncMock(return_value=mock_suitable_methods) + + result = await service.get_computation_suitable_methods(computation_id, user_id) + + assert result == mock_suitable_methods + calculation_storage_mock.get_calculation_set.assert_called_once_with(computation_id) + service._find_suitable_methods.assert_called_once() + service.logger.info.assert_called_once_with( + f""Getting suitable methods for computation '{computation_id}'"" + ) + + @pytest.mark.asyncio + async def test_find_suitable_methods(self, service): + """"""Test finding suitable methods."""""" + + file_hashes = [""hash1"", ""hash2""] + permissive_types = True + user_id = ""user123"" + + molecules_mock = Mock() + service.read_molecules = AsyncMock(return_value=molecules_mock) + + method1 = get_method(""method1"") + method2 = get_method(""method2"") + param1 = get_parameters(""param1"") + param2 = get_parameters(""param2"") + + service._run_in_executor = AsyncMock( + side_effect=[ + [(method1, [param1]), (method2, [param2])], # For first file + [(method1, [param1])], # For second file + ] + ) + + result = await service._find_suitable_methods(file_hashes, permissive_types, user_id) + + assert len(result.methods) == 1 + assert method1 in result.methods + assert len(result.parameters[""method1""]) == 1 + assert result.parameters[""method1""][0] == param1 + + @pytest.mark.asyncio + async def test_calculate_charges(self, service): + """"""Test calculating charges."""""" + + computation_id = ""comp123"" + user_id = ""user123"" + settings = AdvancedSettingsDto() + + config = CalculationConfigDto(method=""method1"", parameters=""param1"") + file_hashes = [""hash1"", ""hash2""] + data = {config: file_hashes} + + result_dto = CalculationResultDto( + config=config, + calculations=[ + CalculationDto(file=""file1.pdb"", file_hash=""hash1"", charges={}, config=config), + CalculationDto(file=""file2.pdb"", file_hash=""hash2"", charges={}, config=config), + ], + ) + + service._calculate_charges = AsyncMock(return_value=result_dto) + + result = await service.calculate_charges(computation_id, settings, data, user_id) + + assert result == [result_dto] + service._calculate_charges.assert_called_once_with( + user_id, computation_id, settings, config, file_hashes + ) + service.io.store_configs.assert_called_once_with( + computation_id, [result_dto.config], user_id + ) + + @pytest.mark.asyncio + async def test_save_charges(self, service): + """"""Test saving charges."""""" + + computation_id = ""comp123"" + user_id = ""user123"" + settings = AdvancedSettingsDto() + + config = CalculationConfigDto(method=""method1"", parameters=""param1"") + results = [ + CalculationResultDto( + config=config, + calculations=[ + CalculationDto(file=""file1.pdb"", file_hash=""hash1"", charges={}, config=config), + CalculationDto(file=""file2.pdb"", file_hash=""hash2"", charges={}, config=config), + ], + ) + ] + + molecules_mock = Mock() + service.read_molecules = AsyncMock(return_value=molecules_mock) + service._run_in_executor = AsyncMock() + + await service.save_charges(settings, computation_id, results, user_id) + + assert service.read_molecules.call_count == 2 + assert service._run_in_executor.call_count == 2 + service.io.create_dir.assert_called_once() + + @pytest.mark.asyncio + async def test_info(self, service): + """"""Test getting info."""""" + + file_path = ""/path/to/file.pdb"" + molecules_mock = Mock() + mock_info = Mock() + mock_info.to_dict.return_value = { + ""total_atoms"": 0, + ""atom_type_counts"": [], + ""total_molecules"": 0, + } + molecules_mock.info.return_value = mock_info + + service.read_molecules = AsyncMock(return_value=molecules_mock) + + result = await service.info(file_path) + + assert result.model_dump() == { + ""total_atoms"": 0, + ""atom_type_counts"": [], + ""total_molecules"": 0, + } + service.read_molecules.assert_called_once_with(file_path) + molecules_mock.info.assert_called_once() + service.logger.info.assert_called_once_with(f""Getting info for file {file_path}."") + + def test_get_calculation_molecules(self, service, io_mock): + """"""Test getting calculation molecules."""""" + + path = ""/path/to/results"" + io_mock.listdir.return_value = [""mol1.fw2.cif"", ""mol2.fw2.cif"", ""config.json""] + + result = service.get_calculation_molecules(path) + + assert result == [""mol1"", ""mol2""] + io_mock.path_exists.assert_called_once_with(path) + io_mock.listdir.assert_called_once_with(path) + + def test_get_calculation_molecules_not_found(self, service, io_mock): + """"""Test getting calculation molecules from a nonexistent path."""""" + + path = ""/path/to/nonexistent"" + io_mock.path_exists.return_value = False + with pytest.raises(FileNotFoundError): + service.get_calculation_molecules(path) + + def test_delete_calculation(self, service): + """"""Test deleting a calculation."""""" + + computation_id = ""comp123"" + user_id = ""user123"" + + service.delete_calculation(computation_id, user_id) + + service.calculation_storage.delete_calculation_set.assert_called_once_with(computation_id) + service.io.delete_computation.assert_called_once_with(computation_id, user_id) + + def test_delete_calculation_error(self, service, calculation_storage_mock): + """"""Test handling exceptions when deleting a calculation."""""" + + computation_id = ""comp123"" + user_id = ""user123"" + calculation_storage_mock.delete_calculation_set.side_effect = Exception(""Test error"") + with pytest.raises(Exception): + service.delete_calculation(computation_id, user_id) + + service.logger.error.assert_called_once() +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/integrations/test_io_local.py",".py","6341","200","import datetime +import os +from pathlib import Path +import shutil +import tempfile +from typing import Any, Generator +import pytest + +from app.integrations.io.io import IOLocal + + +@pytest.fixture +def io_service() -> Generator[tuple[IOLocal, Path], Any, None]: + """"""Fixture for IO service."""""" + + test_dir = Path(tempfile.mkdtemp()) + io = IOLocal() + + yield io, test_dir + + shutil.rmtree(test_dir) + + +class TestIOService: + def test_mkdir(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + new_dir = base_dir / ""new_dir"" + + result = io.mkdir(str(new_dir)) + + assert result == str(new_dir) + assert new_dir.is_dir() + assert new_dir.exists() + + def test_rmdir(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + new_dir = base_dir / ""dir_to_remove"" + os.makedirs(str(new_dir)) + + io.rmdir(str(new_dir)) + + assert not new_dir.exists() + + def test_rm(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_file = os.path.join(base_dir, ""file_to_remove.txt"") + with open(test_file, ""w"") as f: + f.write(""test content"") + + io.rm(test_file) + + assert not os.path.exists(test_file) + + def test_last_modified(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_file = os.path.join(base_dir, ""test_modified.txt"") + with open(test_file, ""w"") as f: + f.write(""test content"") + + now = datetime.datetime.now(datetime.timezone.utc) + result = io.last_modified(test_file) + + assert abs((result - now).total_seconds()) < 5 # Within 5 seconds + + def test_dir_size(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_dir = os.path.join(base_dir, ""test_size_dir"") + os.makedirs(test_dir) + + # Create some files with known sizes (100 bytes and 150 bytes) + with open(os.path.join(test_dir, ""file1.txt""), ""w"") as f: + f.write(""a"" * 100) + + with open(os.path.join(test_dir, ""file2.txt""), ""w"") as f: + f.write(""b"" * 150) + + result = io.dir_size(test_dir) + + assert result == 250 # 100 + 150 bytes + + def test_file_size(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_file = os.path.join(base_dir, ""test_file_size.txt"") + + # Create a file with known size (200 bytes) + with open(test_file, ""w"") as f: + f.write(""a"" * 200) + + result = io.file_size(test_file) + + assert result == 200 + + def test_cp(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + src_file = os.path.join(base_dir, ""source.txt"") + dst_file = os.path.join(base_dir, ""destination.txt"") + + with open(src_file, ""w"") as f: + f.write(""test copy content"") + + result = io.cp(src_file, dst_file) + + assert result == dst_file + assert os.path.exists(dst_file) + + # Also verify the content + with open(dst_file, ""r"") as f: + content = f.read() + assert content == ""test copy content"" + + def test_symlink(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + src_file = os.path.join(base_dir, ""symlink_source.txt"") + dst_link = os.path.join(base_dir, ""symlink_dest.txt"") + + with open(src_file, ""w"") as f: + f.write(""test symlink content"") + + try: + io.symlink(src_file, dst_link) + + assert os.path.islink(dst_link) + assert os.path.exists(dst_link) + + # Verify the content can be accessed through the symlink + with open(dst_link, ""r"") as f: + content = f.read() + assert content == ""test symlink content"" + except OSError: + # Skipping on Windows + pytest.skip(""Symlinks not supported on this platform/environment"") + + def test_zip(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + src_dir = os.path.join(base_dir, ""dir_to_zip"") + os.makedirs(src_dir) + + # Create some files to zip + with open(os.path.join(src_dir, ""file1.txt""), ""w"") as f: + f.write(""test zip content 1"") + with open(os.path.join(src_dir, ""file2.txt""), ""w"") as f: + f.write(""test zip content 2"") + + zip_dest = os.path.join(base_dir, ""zipped_dir"") + result = io.zip(src_dir, zip_dest) + + assert result == f""{zip_dest}.zip"" + assert os.path.exists(result) + + def test_listdir(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + + # Create some files and directories + os.makedirs(os.path.join(base_dir, ""subdir1"")) + os.makedirs(os.path.join(base_dir, ""subdir2"")) + with open(os.path.join(base_dir, ""file1.txt""), ""w"") as f: + f.write(""test content"") + + result = io.listdir(base_dir) + + assert set(result) == {""subdir1"", ""subdir2"", ""file1.txt""} + + @pytest.mark.asyncio + async def test_write_file(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_file = os.path.join(base_dir, ""test_write.txt"") + test_content = ""test write content"" + + await io.write_file(test_file, test_content) + + assert os.path.exists(test_file) + + # Also verify the content + with open(test_file, ""r"") as f: + written_content = f.read() + assert written_content == test_content + + def test_path_exists(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + test_file = os.path.join(base_dir, ""test_exists.txt"") + + # File doesn't exist yet + assert not io.path_exists(test_file) + + with open(test_file, ""w"") as f: + f.write(""test content"") + + # File now exists + assert io.path_exists(test_file) + + def test_error_handling_nonexistent_path(self, io_service: tuple[IOLocal, Path]) -> None: + io, base_dir = io_service + nonexistent_path = os.path.join(base_dir, ""does_not_exist"") + + with pytest.raises(FileNotFoundError): + io.rm(nonexistent_path) + + with pytest.raises(FileNotFoundError): + io.rmdir(nonexistent_path) +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/integrations/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/data/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/data/integrations/__init__.py",".py","0","0","","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","src/backend/tests/data/integrations/chargefw2_data.py",".py","11839","289","PHENOLS = """""" +2,4-dinitrophenol + -OEChem-03052011433D + + 17 17 0 0 0 0 0 0 0999 V2000 + -2.4316 -1.7531 0.0012 O 0 0 0 0 0 0 0 0 0 0 0 0 + -1.9409 2.2955 0.0008 O 0 5 0 0 0 0 0 0 0 0 0 0 + -3.2877 0.5621 0.0002 O 0 0 0 0 0 0 0 0 0 0 0 0 + 3.6796 -0.3388 0.0020 O 0 5 0 0 0 0 0 0 0 0 0 0 + 2.8270 1.6841 -0.0004 O 0 0 0 0 0 0 0 0 0 0 0 0 + -2.1358 1.0571 0.0003 N 0 3 0 0 0 0 0 0 0 0 0 0 + 2.6931 0.4366 0.0003 N 0 3 0 0 0 0 0 0 0 0 0 0 + -1.0128 0.1845 -0.0008 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.3845 -0.1150 -0.0011 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.2723 0.7269 -0.0012 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.1858 -1.1995 -0.0004 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2116 -1.4991 -0.0006 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0736 -2.0413 -0.0004 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.4102 1.8057 -0.0010 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.0546 -2.1854 -0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.1935 -3.1215 0.0003 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.3495 -2.7222 0.0014 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 11 1 0 0 0 0 + 1 17 1 0 0 0 0 + 2 6 1 0 0 0 0 + 3 6 2 0 0 0 0 + 4 7 1 0 0 0 0 + 5 7 2 0 0 0 0 + 6 8 1 0 0 0 0 + 7 9 1 0 0 0 0 + 8 10 1 0 0 0 0 + 8 11 2 0 0 0 0 + 9 10 2 0 0 0 0 + 9 12 1 0 0 0 0 + 10 14 1 0 0 0 0 + 11 13 1 0 0 0 0 + 12 13 2 0 0 0 0 + 12 15 1 0 0 0 0 + 13 16 1 0 0 0 0 +M CHG 4 2 -1 4 -1 6 1 7 1 +M END +$$$$ +4-nitrophenol + -OEChem-03052011443D + + 15 15 0 0 0 0 0 0 0999 V2000 + 3.4465 -0.0002 0.0003 O 0 0 0 0 0 0 0 0 0 0 0 0 + -2.7330 1.0973 0.0007 O 0 5 0 0 0 0 0 0 0 0 0 0 + -2.7318 -1.0979 -0.0003 O 0 0 0 0 0 0 0 0 0 0 0 0 + -2.1244 0.0000 0.0002 N 0 3 0 0 0 0 0 0 0 0 0 0 + -0.7044 0.0007 -0.0005 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0066 1.2084 -0.0005 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0074 -1.2076 -0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 2.0854 -0.0003 0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.3882 1.2079 -0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.3875 -1.2082 0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.5164 2.1685 -0.0006 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.5175 -2.1675 0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1.9204 2.1554 -0.0004 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1.9254 -2.1524 0.0005 H 0 0 0 0 0 0 0 0 0 0 0 0 + 3.7616 0.9200 0.0001 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 8 1 0 0 0 0 + 1 15 1 0 0 0 0 + 2 4 1 0 0 0 0 + 3 4 2 0 0 0 0 + 4 5 1 0 0 0 0 + 5 6 2 0 0 0 0 + 5 7 1 0 0 0 0 + 6 9 1 0 0 0 0 + 6 11 1 0 0 0 0 + 7 10 2 0 0 0 0 + 7 12 1 0 0 0 0 + 8 9 2 0 0 0 0 + 8 10 1 0 0 0 0 + 9 13 1 0 0 0 0 + 10 14 1 0 0 0 0 +M CHG 2 2 -1 4 1 +M END +$$$$ +2-chlorophenol + -OEChem-03052004003D + + 13 13 0 0 0 0 0 0 0999 V2000 + 2.2677 -1.2333 0.0002 Cl 0 0 0 0 0 0 0 0 0 0 0 0 + 1.5040 1.6750 -0.0001 O 0 0 0 0 0 0 0 0 0 0 0 0 + 0.4596 0.7990 -0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.6712 -0.5797 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.8403 1.3051 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.4169 -1.4523 -0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.9285 0.4325 0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.7168 -0.9462 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.0125 2.3780 0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.2687 -2.5292 -0.0003 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.9406 0.8265 0.0003 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.5642 -1.6256 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.3312 1.1630 -0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 4 1 0 0 0 0 + 2 3 1 0 0 0 0 + 2 13 1 0 0 0 0 + 3 4 1 0 0 0 0 + 3 5 2 0 0 0 0 + 4 6 2 0 0 0 0 + 5 7 1 0 0 0 0 + 5 9 1 0 0 0 0 + 6 8 1 0 0 0 0 + 6 10 1 0 0 0 0 + 7 8 2 0 0 0 0 + 7 11 1 0 0 0 0 + 8 12 1 0 0 0 0 +M END +$$$$ +3-chlorophenol + -OEChem-03052011453D + + 13 13 0 0 0 0 0 0 0999 V2000 + 2.7478 -0.9696 0.0004 Cl 0 0 0 0 0 0 0 0 0 0 0 0 + -2.3353 -1.2050 0.0004 O 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2160 -0.4309 -0.0003 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0448 -1.0278 -0.0004 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.3295 0.9593 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.1920 -0.2344 -0.0004 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.1822 1.7526 0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.0785 1.1558 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.1319 -2.1119 -0.0003 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.3088 1.4301 0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.2707 2.8351 0.0005 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1.9636 1.7867 0.0004 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.0717 -2.1413 0.0004 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 6 1 0 0 0 0 + 2 3 1 0 0 0 0 + 2 13 1 0 0 0 0 + 3 4 2 0 0 0 0 + 3 5 1 0 0 0 0 + 4 6 1 0 0 0 0 + 4 9 1 0 0 0 0 + 5 7 2 0 0 0 0 + 5 10 1 0 0 0 0 + 6 8 2 0 0 0 0 + 7 8 1 0 0 0 0 + 7 11 1 0 0 0 0 + 8 12 1 0 0 0 0 +M END +$$$$ +m-cresol + -OEChem-03052011463D + + 16 16 0 0 0 0 0 0 0999 V2000 + 2.3679 -1.0991 0.0003 O 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2040 -0.3077 -0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0181 -1.0422 -0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.1607 1.0865 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2108 -0.3826 -0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -2.5181 -1.0126 0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0682 1.7462 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2540 1.0116 -0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0453 -2.1292 0.0016 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.0776 1.6700 0.0020 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.4534 -1.9685 -0.5307 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.8419 -1.2032 1.0282 H 0 0 0 0 0 0 0 0 0 0 0 0 + -3.2866 -0.4176 -0.5049 H 0 0 0 0 0 0 0 0 0 0 0 0 + 0.1019 2.8317 0.0008 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.2050 1.5375 0.0001 H 0 0 0 0 0 0 0 0 0 0 0 0 + 3.1203 -0.4826 0.0004 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 5 1 0 0 0 0 + 1 16 1 0 0 0 0 + 2 3 2 0 0 0 0 + 2 4 1 0 0 0 0 + 2 6 1 0 0 0 0 + 3 5 1 0 0 0 0 + 3 9 1 0 0 0 0 + 4 7 2 0 0 0 0 + 4 10 1 0 0 0 0 + 5 8 2 0 0 0 0 + 6 11 1 0 0 0 0 + 6 12 1 0 0 0 0 + 6 13 1 0 0 0 0 + 7 8 1 0 0 0 0 + 7 14 1 0 0 0 0 + 8 15 1 0 0 0 0 +M END +$$$$ +o-cresol + -OEChem-03052011463D + + 16 16 0 0 0 0 0 0 0999 V2000 + 1.6857 -1.5029 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 + 0.6382 0.6532 -0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.5573 -0.7393 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.5273 1.4196 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.9637 1.3405 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.6891 -1.3654 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.7737 0.7934 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.8547 -0.5991 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.4819 2.5054 0.0001 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.5347 1.0651 0.8929 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.5356 1.0638 -0.8918 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1.8594 2.4308 -0.0008 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.7672 -2.4493 0.0001 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.6813 1.3899 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.8253 -1.0865 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1.4333 -2.4422 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 3 1 0 0 0 0 + 1 16 1 0 0 0 0 + 2 3 1 0 0 0 0 + 2 4 2 0 0 0 0 + 2 5 1 0 0 0 0 + 3 6 2 0 0 0 0 + 4 7 1 0 0 0 0 + 4 9 1 0 0 0 0 + 5 10 1 0 0 0 0 + 5 11 1 0 0 0 0 + 5 12 1 0 0 0 0 + 6 8 1 0 0 0 0 + 6 13 1 0 0 0 0 + 7 8 2 0 0 0 0 + 7 14 1 0 0 0 0 + 8 15 1 0 0 0 0 +M END +$$$$ +propofol + -OEChem-03052011473D + + 31 31 0 0 0 0 0 0 0999 V2000 + -0.0014 1.9782 -0.0002 O 0 0 0 0 0 0 0 0 0 0 0 0 + -2.5116 0.6448 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + 2.5118 0.6452 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2079 -0.0834 -0.0005 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2080 -0.0829 0.0005 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.0001 0.6142 0.0001 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2077 -1.4783 -0.0004 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2083 -1.4778 0.0003 C 0 0 0 0 0 0 0 0 0 0 0 0 + -3.3461 0.3535 1.2608 C 0 0 0 0 0 0 0 0 0 0 0 0 + -3.3471 0.3539 -1.2601 C 0 0 0 0 0 0 0 0 0 0 0 0 + 3.3463 0.3540 -1.2607 C 0 0 0 0 0 0 0 0 0 0 0 0 + 3.3472 0.3540 1.2602 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0004 -2.1755 -0.0002 C 0 0 0 0 0 0 0 0 0 0 0 0 + -2.3609 1.7288 0.0131 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.3371 1.7281 0.0001 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.1353 -2.0441 -0.0006 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.1359 -2.0433 0.0004 H 0 0 0 0 0 0 0 0 0 0 0 0 + -3.6580 -0.6951 1.3140 H 0 0 0 0 0 0 0 0 0 0 0 0 + -4.2521 0.9694 1.2731 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.7738 0.5801 2.1672 H 0 0 0 0 0 0 0 0 0 0 0 0 + -2.7762 0.5845 -2.1664 H 0 0 0 0 0 0 0 0 0 0 0 0 + -4.2543 0.9680 -1.2696 H 0 0 0 0 0 0 0 0 0 0 0 0 + -3.6566 -0.6952 -1.3154 H 0 0 0 0 0 0 0 0 0 0 0 0 + 3.6610 -0.6938 -1.3126 H 0 0 0 0 0 0 0 0 0 0 0 0 + 4.2501 0.9730 -1.2741 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.7727 0.5777 -2.1671 H 0 0 0 0 0 0 0 0 0 0 0 0 + 2.7742 0.5777 2.1670 H 0 0 0 0 0 0 0 0 0 0 0 0 + 4.2510 0.9731 1.2729 H 0 0 0 0 0 0 0 0 0 0 0 0 + 3.6620 -0.6937 1.3119 H 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0005 -3.2616 -0.0002 H 0 0 0 0 0 0 0 0 0 0 0 0 + -0.6389 2.2874 -0.6653 H 0 0 0 0 0 0 0 0 0 0 0 0 + 1 6 1 0 0 0 0 + 1 31 1 0 0 0 0 + 2 4 1 0 0 0 0 + 2 9 1 0 0 0 0 + 2 10 1 0 0 0 0 + 2 14 1 0 0 0 0 + 3 5 1 0 0 0 0 + 3 11 1 0 0 0 0 + 3 12 1 0 0 0 0 + 3 15 1 0 0 0 0 + 4 6 2 0 0 0 0 + 4 7 1 0 0 0 0 + 5 6 1 0 0 0 0 + 5 8 2 0 0 0 0 + 7 13 2 0 0 0 0 + 7 16 1 0 0 0 0 + 8 13 1 0 0 0 0 + 8 17 1 0 0 0 0 + 9 18 1 0 0 0 0 + 9 19 1 0 0 0 0 + 9 20 1 0 0 0 0 + 10 21 1 0 0 0 0 + 10 22 1 0 0 0 0 + 10 23 1 0 0 0 0 + 11 24 1 0 0 0 0 + 11 25 1 0 0 0 0 + 11 26 1 0 0 0 0 + 12 27 1 0 0 0 0 + 12 28 1 0 0 0 0 + 12 29 1 0 0 0 0 + 13 30 1 0 0 0 0 +M END +$$$$ +"""""" +","Python" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","docs/backend/life-science/test-login.md",".md","1297","39","# Logging to Life Science Test Environment +First-time Life Science Login (test environment) requires a few additional steps to go through. + +1. After clicking on *Log in* on ACC II page, choose your institution. +![login 1](./images/login1.png) + +2. Login via your institution. +![login 2](./images/login2.png) + +3. Proceed to Life Science register. +![login 3](./images/login3.png) + +4. Check your information, accept privacy notice and acceptable use policy, and submit. +![login 4](./images/login4.png) + +5. Accept (again) and submit (again). +![login 5](./images/login5.png) + +6. Verify your email and continue. +![login 6](./images/login6.png) + +7. Continue after successful verification. +![login 7](./images/login7.png) + +8. Continue to the test service. +![login 8](./images/login8.png) + +9. Click on the *Register into Life Science Community - Test Environment*. +![login 9](./images/login9.png) + +10. Submit. Test membership expires after 30 days. +![login 10](./images/login10.png) + +11. You have been successfuly registered to the test environment. **You can now navigate back to the ACC II page and click on *Log in* again**. +![login 11](./images/login11.png) + +12. Consent for releasing your openid for use in ACC II. After clicking on continue, you should be logged in. +![login 12](./images/login12.png) +","Markdown" +"Nucleic acids","sb-ncbr/AtomicChargeCalculator","docs/backend/life-science/move-to-prod.md",".md","521","14","# Move Life Science Login to Production +Since the test environment is not supposed to be used in production, the environment (or service) needs to be *moved to production*. + +1. Open the service and click on the *Move to production* button. +![move to prod](./images/prod1.png) + +2. Verify service information and click on *Submit*. +![submit](./images/prod2.png) + +3. Wait for approval by LS administrators. +![approval](./images/prod3.png) + +4. After approval, the service should look like this: +![success](./images/prod4.png)","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","cran-comments.md",".md","1246","36","# CRAN submission TopDom 0.10.1 + +on 2021-05-04 + +Updated one URL in TopDom 0.10.0 that otherwise redirects HTTP to HTTPS. + +Thanks + + +TopDom 0.10.0 submission on 2021-05-03 comment: + +TopDom is a new CRAN package. Its code originates from supplementary R script of Shin et al. (2016). The original authors have agreed on the GPL license and are listed as co-authors of this package. + +Thank you + + + + +## Notes not sent to CRAN + +### R CMD check validation + +The package has been verified using `R CMD check --as-cran` on: + +| R version | GitHub Actions | Travis | AppVeyor | R-hub | win-builder | +| --------- | -------------- | ------ | -------- | ------- | ----------- | +| 3.3.x | L | | | | | +| 3.4.x | L | | | | | +| 3.5.x | L | | | | | +| 3.6.x | L | | | | | +| 4.0.x | L M W | L | | L M S | W | +| 4.1.x | | | | W | W | +| devel | L M W | L | W | | | + +Legend: OS: L = Linux S = Solaris M = macOS W = Windows +","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","OVERVIEW.md",".md","3522","35","The TopDom method identifies topological domains in genomes from Hi-C sequence data (Shin et al., 2016). The authors published an implementation of their method as an R script (two different versions; also available in this package). This package originates from those original TopDom R scripts and provides help pages adopted from the original TopDom PDF documentation. It also provides a small number of bug fixes to the original code. + + +## Citing TopDom - the method and the package + +Whenever using the TopDom method, please cite: + +* Hanjun Shin, Yi Shi, Chao Dai, Harianto Tjong, Ke Gong, Frank Alber, Xianghong Jasmine Zhou; TopDom: an efficient and deterministic method for identifying topological domains in genomes, Nucleic Acids Research, Volume 44, Issue 7, 20 April 2016, Pages e70, [10.1093/nar/gkv1505](https://doi.org/10.1093/nar/gkv1505). PMCID: [PMC4838359](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4838359/), PMID: 26704975. + +Whenever using the **TopDom** package, please cite: + +* Henrik Bengtsson, Hanjun Shin, Harris Lazaris, Gangqing Hu and Xianghong Zhou (2020). R Package TopDom: An Efficient and Deterministic Method for Identifying Topological Domains in Genomes. R package version 0.10.1. + +The above information is also available as plain text as well as BibTeX entries via `citation(""TopDom"")`. + + +## Background + +Please note that I, Henrik Bengtsson, is _not_ the developer of the TopDom method (Shin et al. 2016), or the (original) TopDom code available from the TopDom authors. As I needed the TopDom method in a project, I ended up putting their `TopDom_v0.0.*.R` scripts into a proper R package (this **TopDom** package) so I could validate the[ir] code via `R CMD check` and so on. Then I started to add a bit of help documentation to make my own life easier. I also found a few bugs that I fixed and did some improvements but I really tried not to diverge from the original functionality. + +Now, since I find it a waste of resources if someone else has to go through the same efforts that I had to, I decided to make this package public. The goal is also to submit the **TopDom** package to CRAN so that the TopDom method is properly archived for reproducible purposes. In order to do this, the original authors agreed on releasing their original TopDom scripts under the GPL license, which is also the license of the **TopDom** package. + +Having said this, please note that I don't intend to do user support for the TopDom method, how to use it, add new features, and so on. This is simply because I don't have the resources to do that. More importantly, I am not the best person to answer questions on the TopDom method and its implementation. Instead, I recommend that you reach out to the original TopDom authors to get your questions answered. + + +## Archaeology + +The original R script (versions 0.0.1 and 0.0.2) and the TopDom manual were made available on a website of the TopDom author (http://zhoulab.usc.edu/TopDom/). As of 2019, that website is no longer available. Instead, TopDom is now listed as a paragraph on with a link to one of the author GitHub repository [jasminezhoulab/TopDom](https://github.com/jasminezhoulab/TopDom), which holds the TopDom manual and version 0.0.2 of the script but not version 0.0.1. + + + +[R]: https://www.r-project.org/ +[TopDom]: https://github.com/HenrikBengtsson/TopDom/ +[TopDomData]: https://github.com/HenrikBengtsson/TopDomData/ +","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","CONTRIBUTING.md",".md","1225","9"," +# Contributing to the 'TopDom' package + +This Git repository uses the [Git Flow](https://nvie.com/posts/a-successful-git-branching-model/) branching model (the [`git flow`](https://github.com/petervanderdoes/gitflow-avh) extension is useful for this). The [`develop`](https://github.com/HenrikBengtsson/TopDom/tree/develop) branch contains the latest contributions and other code that will appear in the next release, and the [`master`](https://github.com/HenrikBengtsson/TopDom) branch contains the code of the latest release, which is exactly what is currently on [CRAN](https://cran.r-project.org/package=TopDom). + +Contributing to this package is easy. Just send a [pull request](https://help.github.com/articles/using-pull-requests/). When you send your PR, make sure `develop` is the destination branch on the [TopDom repository](https://github.com/HenrikBengtsson/TopDom). Your PR should pass `R CMD check --as-cran`, which will also be checked by GitHub Actions and when the PR is submitted. + +We abide to the [Code of Conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct/) of Contributor Covenant. +","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","NEWS.md",".md","6346","268","# Version (development version) + +## Documentation + + * Fix equation format issue and update one URL. + + +# Version 0.10.1 [2020-05-04] + +## CRAN Policies + + * Update URL that otherwise redirects HTTP to HTTPS. + + +# Version 0.10.0 [2020-05-03] + +## New Features + + * Package now includes mouse Chr19 data from the TopDom study. They + can be found in the `system.file(""exdata"", package = ""TopDom"")` + folder. + + * The orignal TopDom scripts `TopDom_v0.0.1.R` and `TopDom_v0.0.2.R` + are now distributed part of the package as-is. They can be found + in the `system.file(""original-scripts"", package = ""TopDom"")` + folder. + + * `readHiC()` gained arguments `...` which is passed as-is to + `read.table()`. + + +# Version 0.9.1 [2020-04-02] + +## Bug Fixes + + * `ggCountHeatmap()` for `TopDomData` could produce a warning on a + partial argument name. + + +# Version 0.9.0 [2020-02-19] + +## Significant Changes + + * The list data.frame elements returned by `overlapScores()` now has + column `chromosome` as the first position. The data.frame:s are of + kind `tibble`. + +## New Features + + * Add `as_tibble()` for `TopDomOverlapScores`. + +## Documentation + + * Add further documentation on the `window.size` parameter. + + * Add reference to Hanjun Shin's PhD thesis. + + +# Version 0.8.2 [2019-12-17] + +## Documentation + + * Improved help on `overlapScores()` and `TopDom()`. + + * Provide a reference for the default value for `window.size` of + `TopDom()`. + + +# Version 0.8.1 [2019-06-19] + +## Software Quality + + * Fix two cases of partial argument name. + + +# Version 0.8.0 [2019-04-11] + +## New Features + + * The TopDom object returned by `TopDom()` now has an attribute + `parameters` which records the value of arguments `window.size` and + `statFilter`. + + * Made `TopDom()` faster and more memory efficient by lower the + number of replicated computations. + + +# Version 0.7.1 [2019-04-09] + +## Robustness + + * Add internal sanity checks to `TopDom()` asserting that the + intermediate and final results are of proper length and does not + contain missing values. + +## Bug Fixes + + * Internal `Convert.Bin.To.Domain.TMP()` used by `TopDom()` could + produce `Error in `[<-.data.frame`(`*tmp*`, , ""to.coord"", value = + c(NA, 2500, 247500 : replacement has 3 rows, data has 1`, because + it assumed at least one domain was identified. + + +# Version 0.7.0 [2019-03-15] + +## Significant Changes + + * Renamed fields returned by `overlapScores()` to be in singular + form, e.g. `best_score` instead of `best_scores`. + +## New Features + + * Now `overlapScores()` returns also the lengths of the reference + domains. + + +# Version 0.6.0 [2019-01-08] + +## Significant Changes + + * Renamed and swapped the order of the first two arguments of + `overlapScores()` and renamed the second argument to `reference`. + This was done in order to make it clear which set of topological + domains the overlap scores are calculated relative to. + + +# Version 0.5.0 [2018-11-12] + +## Significant Changes + + * Lead TopDom author Xianghong Jasmine Zhou confirms by email that + the original TopDom scripts, and thereby this package, may be + released under the GNU Public License (GPL). + + +# Version 0.4.0 [2018-10-23] + +## New Features + + * Add `countsPerRegion()` for calculating the total contact-frequency + counts per region specified, e.g. per domain. + + * Add `print()`, `dim()`, `[()`, and `subsetByRegion()` for TopDom + objects where the number of rows in the dimension reflect the + number of TopDom domains. + + +# Version 0.3.0 [2018-10-08] + +## New Features + + * The legacy `TopDom()` functions, available via `legacy()`, also + accept `TopDomData` objects as returned by `readHiC()`. This is + supported mostly to make it possible to efficiently compare the + different implementations. + + * Added `[()` for `TopDomData` objects, e.g. `tdd[1:100]`. + + * Added `subsetByRegion()` for `TopDomData` objects. + + * Added `ggCountHeatmap()`, `ggDomain()`, and `ggDomainLabel()` for + `TopDomData` objects. + + +# Version 0.2.0 [2018-07-26] + +## Significant Changes + + * See 'BUG FIXES' below. + +## New Features + + * Add function `legacy()` for access to the original TopDom v0.0.1 + and TopDom v0.0.2 implementations, + e.g. `TopDom::legacy(""0.0.1"")$TopDom()`. + +## Bug Fixes + + * All TopDom functions except `TopDom()` itself were the ones from + TopDom v0.0.2. + + +# Version 0.1.2 [2018-06-28] + +## Significant Changes + + * Released on GitHub. + +## Miscellaneous + + * The license of the underlying TopDom R code/scripts is still unknown, + i.e. to be decided by the original authors of TopDom. Any mentioning + of code licenses in this package / git repository history is invalid. + +## New Features + + * Add `overlapScores()`. + + * Add `image()` for `TopDomData`. + + * List returned by `TopDom()` gained class `TopDom`. + + * Added logical option `TopDom.debug`, which controls whether + functions produce debug output or not. The default is FALSE. + +## Documentation + + * Updated the 'Value' section of `help(""TopDom"")` with details from + the TopDom Manual (an online PDF) provided by Shin et al. + + +# Version 0.1.1 [2018-05-04] + +## New Features + + * Add `print()` method for `TopDomData` object. + + * Reference the TopDom paper (Shin et al., 2016) in the help and the + README. + + +# Version 0.1.0 [2018-04-23] + +## Significant Changes + + * Turned the original TopDom R script into a package. + + * All progress messages are outputted done to standard error. + + * Add `readHiC()`. + +## New Features + + * `TopDom()` can now read, via `readHiC()`, a pure count matrix file + without bin information. To read such files, specify what + chromosome is being read (argument `chr`) and the bin size of the + count matrix (argument `binSize`). + + * If the matrix file is not of a known format, then `TopDom()` + produces an informative error. Previously it gave a message on + stdout and returned 0. + +## Code Style + + * Tidied up code. + +## Software Quality + + * Added package tests. + + +# Version 0.0.2 [2016-07-08] + + * TopDom v0.0.2 script from http://zhoulab.usc.edu/TopDom/ with the below + entries from the official release note: + + * Gap Identification module is changed. + + * Minor bug related to Change Points identification in very small + regions is fixed. + + * bed format support. + + +# Version 0.0.1 [2015-11-09] + + * TopDom v0.0.1 script from http://zhoulab.usc.edu/TopDom/. +","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","CONDUCT.md",".md","3207","75","# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [https://contributor-covenant.org/version/1/4][version] + +[homepage]: https://contributor-covenant.org +[version]: https://contributor-covenant.org/version/1/4/ +","Markdown" +"Nucleic acids","HenrikBengtsson/TopDom","inst/original-scripts/TopDom_v0.0.2.R",".R","20450","627","# @author : Hanjun Shin(shanjun@usc.edu) +# @credit : Harris Lazaris(Ph.D Stduent, NYU), Dr. Gangqing Hu(Staff Scientist, NIH) +# @brief : TopDom.R is a software package to identify topological domains for given Hi-C contact matrix. +# @version 0.0.2 + +# @fn TopDom +# @param matrixFile : string, matrixFile Address, +# - Format = {chromosome, bin start, bin end, N numbers normalized value } +# - N * (N + 3), where N is the number of bins +# @param window.size :integer, number of bins to extend. +# @param out_binSignal : string, binSignal file address to write +# @param out_ext : string, ext file address to write +TopDom <- function( matrix.file, window.size, outFile=NULL, statFilter=T) +{ + print(""#########################################################################"") + print(""Step 0 : File Read "") + print(""#########################################################################"") + window.size = as.numeric(window.size) + matdf = read.table(matrix.file, header=F) + + if( ncol(matdf) - nrow(matdf) == 3) { + colnames(matdf) <- c(""chr"", ""from.coord"", ""to.coord"") + } else if( ncol(matdf) - nrow(matdf) ==4 ) { + colnames(matdf) <- c(""id"", ""chr"", ""from.coord"", ""to.coord"") + } else { + print(""Unknwon Type of matrix file"") + return(0) + } + n_bins = nrow(matdf) + mean.cf <- rep(0, n_bins) + pvalue <- rep(1, n_bins) + + local.ext = rep(-0.5, n_bins) + + bins <- data.frame(id=1:n_bins, + chr=matdf[, ""chr""], + from.coord=matdf[, ""from.coord""], + to.coord=matdf[, ""to.coord""] ) + matrix.data <- as.matrix( matdf[, (ncol(matdf) - nrow(matdf)+1 ):ncol(matdf)] ) + + print(""-- Done!"") + print(""Step 0 : Done !!"") + + + print(""#########################################################################"") + print(""Step 1 : Generating binSignals by computing bin-level contact frequencies"") + print(""#########################################################################"") + ptm <- proc.time() + for(i in 1:n_bins) + { + diamond = Get.Diamond.Matrix(mat.data=matrix.data, i=i, size=window.size) + mean.cf[i] = mean(diamond) + } + + eltm = proc.time() - ptm + print(paste(""Step 1 Running Time : "", eltm[3])) + print(""Step 1 : Done !!"") + + print(""#########################################################################"") + print(""Step 2 : Detect TD boundaries based on binSignals"") + print(""#########################################################################"") + + ptm = proc.time() + #gap.idx = Which.Gap.Region(matrix.data=matrix.data) + #gap.idx = Which.Gap.Region2(mean.cf) + gap.idx = Which.Gap.Region2(matrix.data=matrix.data, window.size) + + proc.regions = Which.process.region(rmv.idx=gap.idx, n_bins=n_bins, min.size=3) + + #print(proc.regions) + + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + local.ext[start:end] = Detect.Local.Extreme(x=mean.cf[start:end]) + } + + eltm = proc.time() - ptm + print(paste(""Step 2 Running Time : "", eltm[3])) + print(""Step 2 : Done !!"") + + if(statFilter) + { + print(""#########################################################################"") + print(""Step 3 : Statistical Filtering of false positive TD boundaries"") + print(""#########################################################################"") + + ptm = proc.time() + print(""-- Matrix Scaling...."") + scale.matrix.data = matrix.data + for( i in 1:(2*window.size) ) + { + #diag(scale.matrix.data[, i:n_bins] ) = scale( diag( matrix.data[, i:n_bins] ) ) + scale.matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] = scale( matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] ) + } + + print(""-- Compute p-values by Wilcox Ranksum Test"") + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + pvalue[start:end] <- Get.Pvalue(matrix.data=scale.matrix.data[start:end, start:end], size=window.size, scale=1) + } + print(""-- Done!"") + + print(""-- Filtering False Positives"") + local.ext[intersect( union(which( local.ext==-1), which(local.ext==-1)), which(pvalue<0.05))] = -2 + local.ext[which(local.ext==-1)] = 0 + local.ext[which(local.ext==-2)] = -1 + print(""-- Done!"") + + eltm = proc.time() - ptm + print(paste(""Step 3 Running Time : "", eltm[3])) + print(""Step 3 : Done!"") + } else pvalue = 0 + + domains = Convert.Bin.To.Domain.TMP(bins=bins, + signal.idx=which(local.ext==-1), + gap.idx=which(local.ext==-0.5), + pvalues=pvalue, + pvalue.cut=0.05) + + bins = cbind(bins, + local.ext = local.ext, + mean.cf = mean.cf, + pvalue = pvalue) + + bedform = domains[, c(""chr"", ""from.coord"", ""to.coord"", ""tag"")] + colnames(bedform) = c(""chrom"", ""chromStart"", ""chromEnd"", ""name"") + + if( !is.null(outFile) ) { + print(""#########################################################################"") + print(""Writing Files"") + print(""#########################################################################"") + + outBinSignal = paste(outFile, "".binSignal"", sep="""") + print(paste(""binSignal File :"", outBinSignal) ) + write.table(bins, file=outBinSignal, quote=F, row.names=F, col.names=T, sep=""\t"") + + + outDomain = paste(outFile, "".domain"", sep="""") + print(paste(""Domain File :"", outDomain) ) + write.table( domains, file=outDomain, quote=F, row.names=F, col.names=T, sep=""\t"") + + outBed = paste(outFile, "".bed"", sep="""") + print(paste(""Bed File : "", outBed)) + write.table( bedform, file=outBed, quote=F, row.names=F, col.names=F, sep=""\t"") + } + + print(""Done!!"") + + print(""Job Complete !"") + return(list(binSignal=bins, domain=domains, bed=bedform)) +} + +# @fn Get.Diamond.Matrix +# @param mat.data : N by N matrix, where each element indicate contact frequency +# @param i :integer, bin index +# @param size : integer, window size to expand from bin +# @retrun : matrix. +Get.Diamond.Matrix <- function(mat.data, i, size) +{ + n_bins = nrow( mat.data ) + if(i==n_bins) return(NA) + + lowerbound = max( 1, i-size+1 ) + upperbound = min( i+size, n_bins) + + return( mat.data[lowerbound:i, (i+1):upperbound] ) +} + +# @fn Which.process.region +# @param rmv.idx : vector of idx, remove index vector +# @param n_bins : total number of bins +# @param min.size : minimum size of bins +# @retrun : data.frame of proc.regions +Which.process.region <- function(rmv.idx, n_bins, min.size=3) +{ + gap.idx = rmv.idx + + proc.regions = data.frame(start=numeric(0), end=numeric(0)) + proc.set = setdiff(1:n_bins, gap.idx) + n_proc.set = length(proc.set) + + i=1 + while(i < n_proc.set ) + { + start = proc.set[i] + j = i+1 + + while(j <= n_proc.set) + { + if( proc.set[j] - proc.set[j-1] <= 1) j = j + 1 + else { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + i = j + break + } + } + + if(j >= n_proc.set ) { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + break + } + } + + colnames(proc.regions) = c(""start"", ""end"") + proc.regions <- proc.regions[ which( abs(proc.regions[,""end""] - proc.regions[, ""start""]) >= min.size ), ] + + return(proc.regions) +} + +# @fn Which.Gap.Region +# @breif version 0.0.1 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region <- function(matrix.data) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + i=1 + while(i < n_bins) + { + j = i + 1 + while( j <= n_bins) + { + if( sum( matrix.data[i:j, i:j]) == 0 ) { + gap[i:j] = -0.5 + j = j+1 + #if(j-i > 1) gap[i:j]=-0.5 + #j=j+1 + } else break + } + + i = j + } + + idx = which(gap == -0.5) + return(idx) +} + +# @fn Which.Gap.Region3 +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region3 <- function(mean.cf) +{ + n_bins = length(mean.cf) + gapidx = which(mean.cf==0) + + return(gapidx) +} + +# @fn Which.Gap.Region2 +# @breif version 0.0.2 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region2 <- function(matrix.data, w) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + for(i in 1:n_bins) + { + if( sum( matrix.data[i, max(1, i-w):min(i+w, n_bins)] ) == 0 ) gap[i]=-0.5 + } + + idx = which(gap == -0.5) + return(idx) +} + +# @fn Detect.Local.Extreme +# @param x : original signal to find local minima +# @return vector of local extrme, -1 if the index is local minimum, 1 if the index is local maxima, 0 otherwise. +Detect.Local.Extreme <- function(x) +{ + n_bins = length(x) + ret = rep(0, n_bins) + x[is.na(x)]=0 + + if(n_bins <= 3) + { + ret[which.min(x)]=-1 + ret[which.max(x)]=1 + + return(ret) + } + # Norm##################################################3 + new.point = Data.Norm(x=1:n_bins, y=x) + x=new.point$y + ################################################## + cp = Change.Point(x=1:n_bins, y=x) + + if( length(cp$cp) <= 2 ) return(ret) + if( length(cp$cp) == n_bins) return(ret) + for(i in 2:(length(cp$cp)-1)) + { + if( x[cp$cp[i]] >= x[cp$cp[i]-1] && x[cp$cp[i]] >= x[cp$cp[i]+1] ) ret[cp$cp[i]] = 1 + else if(x[cp$cp[i]] < x[cp$cp[i]-1] && x[cp$cp[i]] < x[cp$cp[i]+1]) ret[cp$cp[i]] = -1 + + min.val = min( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + max.val = max( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + + if( min( x[cp$cp[i-1]:cp$cp[i]] ) < min.val ) ret[ cp$cp[i-1] - 1 + which.min( x[cp$cp[i-1]:cp$cp[i]] ) ] = -1 + if( max( x[cp$cp[i-1]:cp$cp[i]] ) > max.val ) ret[ cp$cp[i-1] - 1 + which.max( x[cp$cp[i-1]:cp$cp[i]] ) ] = 1 + } + + return(ret) +} + +# @fn Data.Norm +# @param x : x axis vector +# @param x : y axis vector +# @return list of normalized x and y +Data.Norm <- function(x, y) +{ + ret.x = rep(0, length(x)) + ret.y = rep(0, length(y)) + + ret.x[1] = x[1] + ret.y[1] = y[1] + + diff.x = diff(x) + diff.y = diff(y) + + scale.x = 1 / mean( abs(diff(x) ) ) + scale.y = 1 / mean( abs( diff(y) ) ) + + #print(scale.x) + #print(scale.y) + + for(i in 2:length(x)) + { + ret.x[i] = ret.x[i-1] + (diff.x[i-1]*scale.x) + ret.y[i] = ret.y[i-1] + (diff.y[i-1]*scale.y) + } + + return(list(x=ret.x, y=ret.y)) +} + +# @fn Change.Point +# @param x : x axis vector +# @param x : y axis vector +# @return change point index in x vector, +# Note that the first and the last point will be always change point +Change.Point <- function( x, y ) +{ + if( length(x) != length(y)) + { + print(""ERROR : The length of x and y should be the same"") + return(0) + } + + n_bins <- length(x) + Fv <- rep(NA, n_bins) + Ev <- rep(NA, n_bins) + cp <- 1 + + i=1 + Fv[1]=0 + while( i < n_bins ) + { + j=i+1 + Fv[j] = sqrt( (x[j]-x[i])^2 + (y[j] - y[i] )^2 ) + + while(j= 1 && i < n_bins) + { + lower = min(i+1, n_bins) + upper = min(i+size, n_bins) + + new.mat[size-(k-1), 1:(upper-lower+1)] = mat.data[i-(k-1), lower:upper] + } + } + + return(new.mat) +} + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + new.bdr.set = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + + i=1 + while(i <= nrow(ret)) + { + if( ret[i, ""tag""] == ""boundary"" ) + { + stack.bdr = rbind(stack.bdr, ret[i, ]) + } else if(nrow(stack.bdr)>0) { + new.bdr = data.frame(chr=bins[1, ""chr""], + from.id = min( stack.bdr[, ""from.id""]), + from.coord=min(stack.bdr[, ""from.coord""]), + to.id = max( stack.bdr[, ""to.id""]), + to.coord=max(stack.bdr[, ""to.coord""]), + tag=""boundary"", + size=max(stack.bdr[, ""to.coord""]) - min(stack.bdr[, ""from.coord""])) + new.bdr.set = rbind(new.bdr.set, new.bdr) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + } + + i = i + 1 + } + + ret = rbind( ret[ ret[, ""tag""]!=""boundary"", ], new.bdr.set ) + ret = ret[order(ret[, ""to.coord""]), ] + + return(ret) +} + + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain.TMP <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + return(ret) +}","R" +"Nucleic acids","HenrikBengtsson/TopDom","inst/original-scripts/TopDom_v0.0.1.R",".R","19187","580","# @author : Hanjun Shin +# @brief : TopDom.R is a software package to identify topological domains for given Hi-C contact matrix. + +# @fn TopDom +# @param matrixFile : string, matrixFile Address, +# - Format = {chromosome, bin start, bin end, N numbers normalized value } +# - N * (N + 3), where N is the number of bins +# @param window.size :integer, number of bins to extend. +# @param out_binSignal : string, binSignal file address to write +# @param out_ext : string, ext file address to write +TopDom <- function( matrix.file, window.size, outFile=NULL, statFilter=T) +{ + print(""#########################################################################"") + print(""Step 0 : File Read "") + print(""#########################################################################"") + window.size = as.numeric(window.size) + matdf = read.table(matrix.file, header=F) + + if( ncol(matdf) - nrow(matdf) == 3) { + colnames(matdf) <- c(""chr"", ""from.coord"", ""to.coord"") + } else if( ncol(matdf) - nrow(matdf) ==4 ) { + colnames(matdf) <- c(""id"", ""chr"", ""from.coord"", ""to.coord"") + } else { + print(""Unknwon Type of matrix file"") + return(0) + } + + n_bins = nrow(matdf) + mean.cf <- rep(0, n_bins) + pvalue <- rep(1, n_bins) + + local.ext = rep(-0.5, n_bins) + + + bins <- data.frame(id=1:n_bins, + chr=matdf[, ""chr""], + from.coord=matdf[, ""from.coord""], + to.coord=matdf[, ""to.coord""] ) + matrix.data <- as.matrix( matdf[, (ncol(matdf) - nrow(matdf)+1 ):ncol(matdf)] ) + + print(""-- Done!"") + print(""Step 0 : Done !!"") + + + print(""#########################################################################"") + print(""Step 1 : Generating binSignals by computing bin-level contact frequencies"") + print(""#########################################################################"") + ptm <- proc.time() + for(i in 1:n_bins) + { + diamond = Get.Diamond.Matrix(mat.data=matrix.data, i=i, size=window.size) + mean.cf[i] = mean(diamond) + } + + eltm = proc.time() - ptm + print(paste(""Step 1 Running Time : "", eltm[3])) + print(""Step 1 : Done !!"") + + print(""#########################################################################"") + print(""Step 2 : Detect TD boundaries based on binSignals"") + print(""#########################################################################"") + + ptm = proc.time() + gap.idx = Which.Gap.Region(matrix.data=matrix.data) + proc.regions = Which.process.region(rmv.idx=gap.idx, n_bins=n_bins, min.size=3) + + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + local.ext[start:end] = Detect.Local.Extreme(x=mean.cf[start:end]) + } + + eltm = proc.time() - ptm + print(paste(""Step 2 Running Time : "", eltm[3])) + print(""Step 2 : Done !!"") + + if(statFilter) + { + print(""#########################################################################"") + print(""Step 3 : Statistical Filtering of false positive TD boundaries"") + print(""#########################################################################"") + + ptm = proc.time() + print(""-- Matrix Scaling...."") + scale.matrix.data = matrix.data + for( i in 1:(2*window.size) ) + { + #diag(scale.matrix.data[, i:n_bins] ) = scale( diag( matrix.data[, i:n_bins] ) ) + scale.matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] = scale( matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] ) + } + + print(""-- Compute p-values by Wilcox Ranksum Test"") + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + pvalue[start:end] <- Get.Pvalue(matrix.data=scale.matrix.data[start:end, start:end], size=window.size, scale=1) + } + print(""-- Done!"") + + print(""-- Filtering False Positives"") + local.ext[intersect( union(which( local.ext==-1), which(local.ext==-1)), which(pvalue<0.05))] = -2 + local.ext[which(local.ext==-1)] = 0 + local.ext[which(local.ext==-2)] = -1 + print(""-- Done!"") + + eltm = proc.time() - ptm + print(paste(""Step 3 Running Time : "", eltm[3])) + print(""Step 3 : Done!"") + } else pvalue = 0 + + domains = Convert.Bin.To.Domain.TMP(bins=bins, + signal.idx=which(local.ext==-1), + gap.idx=which(local.ext==-0.5), + pvalues=pvalue, + pvalue.cut=0.05) + bins = cbind(bins, + local.ext = local.ext, + mean.cf = mean.cf, + pvalue = pvalue) + + if( !is.null(outFile) ) { + print(""#########################################################################"") + print(""Writing Files"") + print(""#########################################################################"") + + outBinSignal = paste(outFile, "".binSignal"", sep="""") + print(paste(""binSignal File :"", outBinSignal) ) + write.table(bins, file=outBinSignal, quote=F, row.names=F, col.names=T, sep=""\t"") + + + outDomain = paste(outFile, "".domain"", sep="""") + print(paste(""Domain File :"", outDomain) ) + write.table( domains, file=outDomain, quote=F, row.names=F, col.names=T, sep=""\t"") + } + + print(""Done!!"") + + print(""Job Complete !"") + return(list(binSignal=bins, domain=domains)) +} + +# @fn Get.Diamond.Matrix +# @param mat.data : N by N matrix, where each element indicate contact frequency +# @param i :integer, bin index +# @param size : integer, window size to expand from bin +# @retrun : matrix. +Get.Diamond.Matrix <- function(mat.data, i, size) +{ + n_bins = nrow( mat.data ) + if(i==n_bins) return(NA) + + lowerbound = max( 1, i-size+1 ) + upperbound = min( i+size, n_bins) + + return( mat.data[lowerbound:i, (i+1):upperbound] ) +} + +# @fn Which.process.region +# @param rmv.idx : vector of idx, remove index vector +# @param n_bins : total number of bins +# @param min.size : minimum size of bins +# @retrun : data.frame of proc.regions +Which.process.region <- function(rmv.idx, n_bins, min.size=3) +{ + gap.idx = rmv.idx + + proc.regions = data.frame(start=numeric(0), end=numeric(0)) + proc.set = setdiff(1:n_bins, gap.idx) + n_proc.set = length(proc.set) + + i=1 + while(i < n_proc.set ) + { + start = proc.set[i] + j = i+1 + + while(j <= n_proc.set) + { + if( proc.set[j] - proc.set[j-1] <= 1) j = j + 1 + else { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + i = j + break + } + } + + if(j >= n_proc.set ) { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + break + } + } + + colnames(proc.regions) = c(""start"", ""end"") + proc.regions <- proc.regions[ which( abs(proc.regions[,""end""] - proc.regions[, ""start""]) >= min.size ), ] + + return(proc.regions) +} + +# @fn Which.Gap.Region +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region <- function(matrix.data) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + i=1 + while(i < n_bins) + { + j = i + 1 + while( j <= n_bins) + { + if( sum( matrix.data[i:j, i:j]) == 0 ) { + gap[i:j] = -0.5 + j = j+1 + } else break + } + + i = j + } + idx = which(gap == -0.5) + return(idx) +} + +# @fn Detect.Local.Extreme +# @param x : original signal to find local minima +# @return vector of local extrme, -1 if the index is local minimum, 1 if the index is local maxima, 0 otherwise. +Detect.Local.Extreme <- function(x) +{ + n_bins = length(x) + ret = rep(0, n_bins) + x[is.na(x)]=0 + + if(n_bins <= 3) + { + ret[which.min(x)]=-1 + ret[which.max(x)]=1 + + return(ret) + } + # Norm##################################################3 + new.point = Data.Norm(x=1:n_bins, y=x) + x=new.point$y + ################################################## + cp = Change.Point(x=1:n_bins, y=x) + + if( length(cp$cp) <= 2 ) return(ret) + for(i in 2:(length(cp$cp)-1)) + { + if( x[cp$cp[i]] >= x[cp$cp[i]-1] && x[cp$cp[i]] >= x[cp$cp[i]+1] ) ret[cp$cp[i]] = 1 + else if(x[cp$cp[i]] < x[cp$cp[i]-1] && x[cp$cp[i]] < x[cp$cp[i]+1]) ret[cp$cp[i]] = -1 + + min.val = min( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + max.val = max( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + + if( min( x[cp$cp[i-1]:cp$cp[i]] ) < min.val ) ret[ cp$cp[i-1] - 1 + which.min( x[cp$cp[i-1]:cp$cp[i]] ) ] = -1 + if( max( x[cp$cp[i-1]:cp$cp[i]] ) > max.val ) ret[ cp$cp[i-1] - 1 + which.max( x[cp$cp[i-1]:cp$cp[i]] ) ] = 1 + } + + return(ret) +} + +# @fn Data.Norm +# @param x : x axis vector +# @param x : y axis vector +# @return list of normalized x and y +Data.Norm <- function(x, y) +{ + ret.x = rep(0, length(x)) + ret.y = rep(0, length(y)) + + ret.x[1] = x[1] + ret.y[1] = y[1] + + diff.x = diff(x) + diff.y = diff(y) + + scale.x = 1 / mean( abs(diff(x) ) ) + scale.y = 1 / mean( abs( diff(y) ) ) + + #print(scale.x) + #print(scale.y) + + for(i in 2:length(x)) + { + ret.x[i] = ret.x[i-1] + (diff.x[i-1]*scale.x) + ret.y[i] = ret.y[i-1] + (diff.y[i-1]*scale.y) + } + + return(list(x=ret.x, y=ret.y)) +} + +# @fn Change.Point +# @param x : x axis vector +# @param x : y axis vector +# @return change point index in x vector, +# Note that the first and the last point will be always change point +Change.Point <- function( x, y ) +{ + if( length(x) != length(y)) + { + print(""ERROR : The length of x and y should be the same"") + return(0) + } + + n_bins <- length(x) + Fv <- rep(NA, n_bins) + Ev <- rep(NA, n_bins) + cp <- 1 + + i=1 + Fv[1]=0 + while( i < n_bins ) + { + j=i+1 + Fv[j] = sqrt( (x[j]-x[i])^2 + (y[j] - y[i] )^2 ) + + while(j= 1 && i < n_bins) + { + lower = min(i+1, n_bins) + upper = min(i+size, n_bins) + + new.mat[size-(k-1), 1:(upper-lower+1)] = mat.data[i-(k-1), lower:upper] + } + } + + return(new.mat) +} + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + new.bdr.set = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + + i=1 + while(i <= nrow(ret)) + { + if( ret[i, ""tag""] == ""boundary"" ) + { + stack.bdr = rbind(stack.bdr, ret[i, ]) + } else if(nrow(stack.bdr)>0) { + new.bdr = data.frame(chr=bins[1, ""chr""], + from.id = min( stack.bdr[, ""from.id""]), + from.coord=min(stack.bdr[, ""from.coord""]), + to.id = max( stack.bdr[, ""to.id""]), + to.coord=max(stack.bdr[, ""to.coord""]), + tag=""boundary"", + size=max(stack.bdr[, ""to.coord""]) - min(stack.bdr[, ""from.coord""])) + new.bdr.set = rbind(new.bdr.set, new.bdr) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + } + + i = i + 1 + } + + ret = rbind( ret[ ret[, ""tag""]!=""boundary"", ], new.bdr.set ) + ret = ret[order(ret[, ""to.coord""]), ] + + return(ret) +} + + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain.TMP <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + return(ret) +}","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/TopDom_0.0.1.R",".R","19525","593","# @author : Hanjun Shin +# @brief : TopDom.R is a software package to identify topological domains for given Hi-C contact matrix. + +# @fn TopDom +# @param matrixFile : string, matrixFile Address, +# - Format = {chromosome, bin start, bin end, N numbers normalized value } +# - N * (N + 3), where N is the number of bins +# @param window.size :integer, number of bins to extend. +# @param out_binSignal : string, binSignal file address to write +# @param out_ext : string, ext file address to write +TopDom_0.0.1 <- local({ +TopDom <- function( matrix.file, window.size, outFile=NULL, statFilter=T) +{ + if (inherits(matrix.file, ""TopDomData"")) { + bins <- matrix.file$bins + matrix.data <- matrix.file$counts + n_bins <- nrow(bins) + mean.cf <- rep(0, times = n_bins) + pvalue <- rep(1.0, times = n_bins) + local.ext <- rep(-0.5, times = n_bins) + } else { + print(""#########################################################################"") + print(""Step 0 : File Read "") + print(""#########################################################################"") + matdf <- read.table(matrix.file, header=F) + + if( ncol(matdf) - nrow(matdf) == 3) { + colnames(matdf) <- c(""chr"", ""from.coord"", ""to.coord"") + } else if( ncol(matdf) - nrow(matdf) ==4 ) { + colnames(matdf) <- c(""id"", ""chr"", ""from.coord"", ""to.coord"") + } else { + print(""Unknwon Type of matrix file"") + return(0) + } + + n_bins = nrow(matdf) + mean.cf <- rep(0, n_bins) + pvalue <- rep(1, n_bins) + + local.ext = rep(-0.5, n_bins) + + + bins <- data.frame(id=1:n_bins, + chr=matdf[, ""chr""], + from.coord=matdf[, ""from.coord""], + to.coord=matdf[, ""to.coord""] ) + matrix.data <- as.matrix( matdf[, (ncol(matdf) - nrow(matdf)+1 ):ncol(matdf)] ) + + print(""-- Done!"") + print(""Step 0 : Done !!"") + } + + + print(""#########################################################################"") + print(""Step 1 : Generating binSignals by computing bin-level contact frequencies"") + print(""#########################################################################"") + ptm <- proc.time() + for(i in 1:n_bins) + { + diamond = Get.Diamond.Matrix(mat.data=matrix.data, i=i, size=window.size) + mean.cf[i] = mean(diamond) + } + + eltm = proc.time() - ptm + print(paste(""Step 1 Running Time : "", eltm[3])) + print(""Step 1 : Done !!"") + + print(""#########################################################################"") + print(""Step 2 : Detect TD boundaries based on binSignals"") + print(""#########################################################################"") + + ptm = proc.time() + gap.idx = Which.Gap.Region(matrix.data=matrix.data) + proc.regions = Which.process.region(rmv.idx=gap.idx, n_bins=n_bins, min.size=3) + + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + local.ext[start:end] = Detect.Local.Extreme(x=mean.cf[start:end]) + } + + eltm = proc.time() - ptm + print(paste(""Step 2 Running Time : "", eltm[3])) + print(""Step 2 : Done !!"") + + if(statFilter) + { + print(""#########################################################################"") + print(""Step 3 : Statistical Filtering of false positive TD boundaries"") + print(""#########################################################################"") + + ptm = proc.time() + print(""-- Matrix Scaling...."") + scale.matrix.data = matrix.data + for( i in 1:(2*window.size) ) + { + #diag(scale.matrix.data[, i:n_bins] ) = scale( diag( matrix.data[, i:n_bins] ) ) + scale.matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] = scale( matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] ) + } + + print(""-- Compute p-values by Wilcox Ranksum Test"") + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + pvalue[start:end] <- Get.Pvalue(matrix.data=scale.matrix.data[start:end, start:end], size=window.size, scale=1) + } + print(""-- Done!"") + + print(""-- Filtering False Positives"") + local.ext[intersect( union(which( local.ext==-1), which(local.ext==-1)), which(pvalue<0.05))] = -2 + local.ext[which(local.ext==-1)] = 0 + local.ext[which(local.ext==-2)] = -1 + print(""-- Done!"") + + eltm = proc.time() - ptm + print(paste(""Step 3 Running Time : "", eltm[3])) + print(""Step 3 : Done!"") + } else pvalue = 0 + + domains = Convert.Bin.To.Domain.TMP(bins=bins, + signal.idx=which(local.ext==-1), + gap.idx=which(local.ext==-0.5), + pvalues=pvalue, + pvalue.cut=0.05) + bins = cbind(bins, + local.ext = local.ext, + mean.cf = mean.cf, + pvalue = pvalue) + + if( !is.null(outFile) ) { + print(""#########################################################################"") + print(""Writing Files"") + print(""#########################################################################"") + + outBinSignal = paste(outFile, "".binSignal"", sep="""") + print(paste(""binSignal File :"", outBinSignal) ) + write.table(bins, file=outBinSignal, quote=F, row.names=F, col.names=T, sep=""\t"") + + + outDomain = paste(outFile, "".domain"", sep="""") + print(paste(""Domain File :"", outDomain) ) + write.table( domains, file=outDomain, quote=F, row.names=F, col.names=T, sep=""\t"") + } + + print(""Done!!"") + + print(""Job Complete !"") + return(list(binSignal=bins, domain=domains)) +} + +# @fn Get.Diamond.Matrix +# @param mat.data : N by N matrix, where each element indicate contact frequency +# @param i :integer, bin index +# @param size : integer, window size to expand from bin +# @retrun : matrix. +Get.Diamond.Matrix <- function(mat.data, i, size) +{ + n_bins = nrow( mat.data ) + if(i==n_bins) return(NA) + + lowerbound = max( 1, i-size+1 ) + upperbound = min( i+size, n_bins) + + return( mat.data[lowerbound:i, (i+1):upperbound] ) +} + +# @fn Which.process.region +# @param rmv.idx : vector of idx, remove index vector +# @param n_bins : total number of bins +# @param min.size : minimum size of bins +# @retrun : data.frame of proc.regions +Which.process.region <- function(rmv.idx, n_bins, min.size=3) +{ + gap.idx = rmv.idx + + proc.regions = data.frame(start=numeric(0), end=numeric(0)) + proc.set = setdiff(1:n_bins, gap.idx) + n_proc.set = length(proc.set) + + i=1 + while(i < n_proc.set ) + { + start = proc.set[i] + j = i+1 + + while(j <= n_proc.set) + { + if( proc.set[j] - proc.set[j-1] <= 1) j = j + 1 + else { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + i = j + break + } + } + + if(j >= n_proc.set ) { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + break + } + } + + colnames(proc.regions) = c(""start"", ""end"") + proc.regions <- proc.regions[ which( abs(proc.regions[,""end""] - proc.regions[, ""start""]) >= min.size ), ] + + return(proc.regions) +} + +# @fn Which.Gap.Region +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region <- function(matrix.data) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + i=1 + while(i < n_bins) + { + j = i + 1 + while( j <= n_bins) + { + if( sum( matrix.data[i:j, i:j]) == 0 ) { + gap[i:j] = -0.5 + j = j+1 + } else break + } + + i = j + } + idx = which(gap == -0.5) + return(idx) +} + +# @fn Detect.Local.Extreme +# @param x : original signal to find local minima +# @return vector of local extrme, -1 if the index is local minimum, 1 if the index is local maxima, 0 otherwise. +Detect.Local.Extreme <- function(x) +{ + n_bins = length(x) + ret = rep(0, n_bins) + x[is.na(x)]=0 + + if(n_bins <= 3) + { + ret[which.min(x)]=-1 + ret[which.max(x)]=1 + + return(ret) + } + # Norm##################################################3 + new.point = Data.Norm(x=1:n_bins, y=x) + x=new.point$y + ################################################## + cp = Change.Point(x=1:n_bins, y=x) + + if( length(cp$cp) <= 2 ) return(ret) + for(i in 2:(length(cp$cp)-1)) + { + if( x[cp$cp[i]] >= x[cp$cp[i]-1] && x[cp$cp[i]] >= x[cp$cp[i]+1] ) ret[cp$cp[i]] = 1 + else if(x[cp$cp[i]] < x[cp$cp[i]-1] && x[cp$cp[i]] < x[cp$cp[i]+1]) ret[cp$cp[i]] = -1 + + min.val = min( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + max.val = max( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + + if( min( x[cp$cp[i-1]:cp$cp[i]] ) < min.val ) ret[ cp$cp[i-1] - 1 + which.min( x[cp$cp[i-1]:cp$cp[i]] ) ] = -1 + if( max( x[cp$cp[i-1]:cp$cp[i]] ) > max.val ) ret[ cp$cp[i-1] - 1 + which.max( x[cp$cp[i-1]:cp$cp[i]] ) ] = 1 + } + + return(ret) +} + +# @fn Data.Norm +# @param x : x axis vector +# @param x : y axis vector +# @return list of normalized x and y +Data.Norm <- function(x, y) +{ + ret.x = rep(0, length(x)) + ret.y = rep(0, length(y)) + + ret.x[1] = x[1] + ret.y[1] = y[1] + + diff.x = diff(x) + diff.y = diff(y) + + scale.x = 1 / mean( abs(diff(x) ) ) + scale.y = 1 / mean( abs( diff(y) ) ) + + #print(scale.x) + #print(scale.y) + + for(i in 2:length(x)) + { + ret.x[i] = ret.x[i-1] + (diff.x[i-1]*scale.x) + ret.y[i] = ret.y[i-1] + (diff.y[i-1]*scale.y) + } + + return(list(x=ret.x, y=ret.y)) +} + +# @fn Change.Point +# @param x : x axis vector +# @param x : y axis vector +# @return change point index in x vector, +# Note that the first and the last point will be always change point +Change.Point <- function( x, y ) +{ + if( length(x) != length(y)) + { + print(""ERROR : The length of x and y should be the same"") + return(0) + } + + n_bins <- length(x) + Fv <- rep(NA, n_bins) + Ev <- rep(NA, n_bins) + cp <- 1 + + i=1 + Fv[1]=0 + while( i < n_bins ) + { + j=i+1 + Fv[j] = sqrt( (x[j]-x[i])^2 + (y[j] - y[i] )^2 ) + + while(j= 1 && i < n_bins) + { + lower = min(i+1, n_bins) + upper = min(i+size, n_bins) + + new.mat[size-(k-1), 1:(upper-lower+1)] = mat.data[i-(k-1), lower:upper] + } + } + + return(new.mat) +} + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + new.bdr.set = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + + i=1 + while(i <= nrow(ret)) + { + if( ret[i, ""tag""] == ""boundary"" ) + { + stack.bdr = rbind(stack.bdr, ret[i, ]) + } else if(nrow(stack.bdr)>0) { + new.bdr = data.frame(chr=bins[1, ""chr""], + from.id = min( stack.bdr[, ""from.id""]), + from.coord=min(stack.bdr[, ""from.coord""]), + to.id = max( stack.bdr[, ""to.id""]), + to.coord=max(stack.bdr[, ""to.coord""]), + tag=""boundary"", + size=max(stack.bdr[, ""to.coord""]) - min(stack.bdr[, ""from.coord""])) + new.bdr.set = rbind(new.bdr.set, new.bdr) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + } + + i = i + 1 + } + + ret = rbind( ret[ ret[, ""tag""]!=""boundary"", ], new.bdr.set ) + ret = ret[order(ret[, ""to.coord""]), ] + + return(ret) +} + + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain.TMP <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + return(ret) +} + +TopDom +}) ## local() +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/overlapScores.R",".R","8326","227","#' Calculates Overlap Scores Between Two Sets of Topological Domains +#' +#' @param a,reference Topological domain (TD) set \eqn{A} and TD reference +#' set \eqn{R} both in a format as returned by [TopDom()]. +#' +#' @param debug If `TRUE`, debug output is produced. +#' +#' @return +#' Returns a named list of class `TopDomOverlapScores`, where the names +#' correspond to the chromosomes in domain reference set \eqn{R}. +#' Each of these chromosome elements contains a data.frame with fields: +#' +#' * `chromosome` - \eqn{D_{R,c}} character strings +#' * `best_score` - \eqn{D_{R,c}} numerics in \eqn{[0,1]} +#' * `best_length` - \eqn{D_{R,c}} positive integers +#' * `best_set` - list of \eqn{D_{R,c}} index vectors +#' +#' where \eqn{D_{R,c}} is the number of TDs in reference set \eqn{R} on +#' chromosome \eqn{c}. If a TD in reference \eqn{R} is not a `""domain""`, +#' then the corresponding `best_score` and `best_length` values are +#' `NA_real_` and `NA_integer_`, respectively, while `best_set` is an empty +#' list. +#' +#' @details +#' The _overlap score_, \eqn{overlap(A', r_i)}, represents how well a +#' _consecutive_ subset \eqn{A'} of topological domains (TDs) in \eqn{A} +#' overlap with topological domain \eqn{r_i} in reference set \eqn{R}. +#' For each reference TD \eqn{r_i}, the _best match_ \eqn{A'_{max}} is +#' identified, that is, the \eqn{A'} subset that maximize +#' \eqn{overlap(A', r_i)}. +#' For exact definitions, see Page 8 in Shin et al. (2016). +#' +#' Note that the overlap score is an asymmetric score, which means that +#' `overlapScores(a, b) != overlapScores(b, a)`. +#' +#' @section Warning - This might differ not be the correct implementation: +#' The original TopDom scripts do not provide an implementation for +#' calculating overlap scores. Instead, the implementation of +#' `TopDom::overlapScores()` is based on the textual description of +#' overlap scores provided in Shin et al. (2016). It is not known if this +#' is the exact same algorithm and implementation as the authors of the +#' TopDom article used. +#' +#' @example incl/overlapScores.R +#' +#' @references +#' * Shin et al., +#' TopDom: an efficient and deterministic method for identifying +#' topological domains in genomes, +#' _Nucleic Acids Research_, 44(7): e70, April 2016. +#' doi: 10.1093/nar/gkv1505, +#' PMCID: [PMC4838359](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4838359/), +#' PMID: [26704975](https://pubmed.ncbi.nlm.nih.gov/26704975/) +#' +#' @author Henrik Bengtsson - based on the description in Shin et al. (2016). +#' +#' @seealso [TopDom]. +#' +#' @importFrom tibble as_tibble tibble +#' @export +overlapScores <- function(a, reference, debug = getOption(""TopDom.debug"", FALSE)) { + stopifnot(inherits(reference, ""TopDom""), inherits(a, ""TopDom"")) + stopifnot(is.logical(debug), length(debug) == 1L, !is.na(debug)) + + ## Extract the 'domain' fields from the 'reference' and the 'a' TopDom objects + domains_R <- reference$domain + domains_A <- a$domain + + chromosomes <- unique(domains_R$chr) + scores <- vector(""list"", length = length(chromosomes)) + names(scores) <- chromosomes + for (chr in chromosomes) { + if (debug) message(sprintf(""Chromosome %s ..."", chr)) + doms_R <- domains_R[domains_R$chr == chr, ] + doms_A <- domains_A[domains_A$chr == chr, ] + scores_chr <- overlapScoresOneChromosome(doms_A, doms_R = doms_R, debug = debug) + scores_chr <- as_tibble(cbind(tibble(chromosome = chr), scores_chr)) + scores[[chr]] <- scores_chr + if (debug) message(sprintf(""Chromosome %s ... done"", chr)) + } + + class(scores) <- c(""TopDomOverlapScores"", class(scores)) + scores +} + + +#' @importFrom tibble as_tibble +overlapScoresOneChromosome <- function(doms_A, doms_R, debug = getOption(""TopDom.debug"", FALSE)) { + stopifnot(is.logical(debug), length(debug) == 1L, !is.na(debug)) + ## FIXME: Assert that A and reference R are sorted by (chr, pos) + + dtags <- diff(c(0L, as.integer(doms_A$tag == ""domain""), 0L)) + sets <- data.frame( + first = which(dtags == +1L), + last = which(dtags == -1L) - 1L, + stringsAsFactors = FALSE + ) + sets$from.coord <- doms_A$from.coord[sets$first] + sets$to.coord <- doms_A$to.coord[sets$last] + + doms_R$length <- as.integer(doms_R$to.coord - doms_R$from.coord) + doms_A$length <- as.integer(doms_A$to.coord - doms_A$from.coord) + + best_scores <- rep(NA_real_, times = nrow(doms_R)) + best_lengths <- rep(NA_integer_, times = nrow(doms_R)) + best_sets <- vector(""list"", length = nrow(doms_R)) + idxs_td <- which(doms_R$tag == ""domain"") + for (ii in seq_along(idxs_td)) { + idx_td <- idxs_td[ii] + if (debug) message(sprintf(""TD \""domain\"" #%d of %d ..."", ii, length(idxs_td))) + td_R <- doms_R[idx_td, ] + + ## Identify sets to consider + ## Q. How many sets can match this? [0,1], [0,2], [0,3], or even more? + sets_t <- sets[(sets$to.coord >= td_R$from.coord & + sets$from.coord <= td_R$to.coord), ] + + best_score <- 0.0 + best_set <- integer(0L) + + ## For each possible A' set ... + for (kk in seq_len(nrow(sets_t))) { + set <- sets_t[kk,] + doms <- doms_A[set$first:set$last,] + doms$cap <- doms$length + + ## TD in A' that is overlapping part of the beginning of reference R + before <- which(doms$from.coord <= td_R$from.coord) + if (length(before) > 0L) { + before <- before[length(before)] + doms$cap[before] <- doms$to.coord[before] - td_R$from.coord + } + + ## TD in A' that is overlapping part of the end of reference R + after <- which(doms$to.coord >= td_R$to.coord) + if (length(after) > 0L) { + after <- after[1L] + doms$cap[after] <- td_R$to.coord - doms$from.coord[after] + } + + ## TDs in A' that are strictly overlapping with reference R + is_inside <- (doms$from.coord >= td_R$from.coord & + doms$to.coord <= td_R$to.coord) + idxs_t <- c(before, which(is_inside), after) + n <- length(idxs_t) + stop_if_not(n > 0L) + caps <- doms$cap[idxs_t] + stop_if_not(length(caps) > 0L, any(is.finite(caps))) + stop_if_not(!anyNA(caps)) + cups <- doms$length[idxs_t] + stop_if_not(length(cups) > 0L, any(is.finite(cups))) + if (n == 1L) { + idxs_u <- list(1L) + max_score <- caps / cups + } else if (n == 2L) { + idxs_u <- list(1L, 1:2, 2L) + } else if (n >= 3L) { + idxs_u <- list(1L, 1L:(n-1L), 2L:(n-1L), 2L:n, n) + } + stop_if_not(!anyNA(idxs_u)) + scores <- sapply(idxs_u, FUN = function(idxs) { + sum(caps[idxs]) / sum(cups[idxs]) + }) + stop_if_not(any(is.finite(scores))) + max_idx <- which.max(scores) + + max_score <- scores[max_idx] + if (max_score > best_score) { + best_score <- max_score + best_set <- idxs_u[[max_idx]] + } + } ## for (kk ...) + + ## Sanity checks + stop_if_not(length(best_score) == 1L, length(td_R$length) == 1L) + + best_scores[ii] <- best_score + best_lengths[ii] <- td_R$length + best_sets[[ii]] <- best_set + + if (debug) message(sprintf(""TD \""domain\"" #%d of %d ... done"", ii, length(idxs_td))) + } ## for (ii ...) + + ## Sanity checks + stop_if_not(length(best_scores) == nrow(doms_R), + length(best_lengths) == nrow(doms_R), + length(best_sets) == nrow(doms_R)) + + res <- data.frame(best_score = best_scores, best_length = best_lengths, stringsAsFactors = FALSE) + res$best_set <- best_sets + + res +} ## overlapScoresOneChromosome() + + +#' @importFrom tibble as_tibble +#' @export +as_tibble.TopDomOverlapScores <- function(x, ...) { + do.call(rbind, args = x) +} + + +#' @export +print.TopDomOverlapScores <- function(x, ...) { + cat(sprintf(""%s:\n"", paste(class(x), collapse = "", ""))) + + cat(sprintf(""Chromosomes: [n = %d] %s\n"", + length(x), paste(sQuote(names(x)), collapse = "", ""))) + + lengths <- lapply(x, FUN = `[[`, ""best_length"") + lengths[[""whole genome""]] <- unlist(lengths, use.names = FALSE) + cat(""Summary of reference domain lengths:\n"") + t <- t(sapply(lengths, FUN = function(x) { + c(summary(x), count = length(x)) + })) + print(t) + + scores <- lapply(x, FUN = `[[`, ""best_score"") + scores[[""whole genome""]] <- unlist(scores, use.names = FALSE) + cat(""Summary of best scores:\n"") + t <- t(sapply(scores, FUN = function(x) { + c(summary(x), count = length(x)) + })) + + print(t) +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/countsPerRegion.R",".R","1017","40","#' Calculates Counts per Region in a TopDomData Object +#' +#' @param data A TopDomData object. +#' +#' @param regions TopDom regions (a data.frame), e.g. domains. +#' +#' @return A numeric vector of length `nrow(regions)`. +#' +#' @author Henrik Bengtsson. +#' +#' @export +countsPerRegion <- function(data, regions) { + UseMethod(""countsPerRegion"") +} + + +#' @importFrom matrixStats colSums2 +#' @export +countsPerRegion.TopDomData <- function(data, regions) { + chr <- NULL ## To please R CMD check + + stopifnot(is.data.frame(regions)) + uchr <- unique(regions$chr) + stopifnot(length(uchr) == 1L) + + bins <- subset(data$bins, chr == uchr) + counts <- data$counts + + nregions <- nrow(regions) + total <- vector(storage.mode(counts), length = nregions) + + for (kk in seq_len(nregions)) { + region <- regions[kk, ] + idxs_kk <- with(bins, which(from.coord >= region$from.coord & to.coord <= region$to.coord)) + total[kk] <- sum(colSums2(counts, rows = idxs_kk, cols = idxs_kk, na.rm = TRUE), na.rm = TRUE) + } + + total +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/TopDom_0.0.2.R",".R","20826","641","# @author : Hanjun Shin(shanjun@usc.edu) +# @credit : Harris Lazaris(Ph.D Stduent, NYU), Dr. Gangqing Hu(Staff Scientist, NIH) +# @brief : TopDom.R is a software package to identify topological domains for given Hi-C contact matrix. +# @version 0.0.2 + +# @fn TopDom +# @param matrixFile : string, matrixFile Address, +# - Format = {chromosome, bin start, bin end, N numbers normalized value } +# - N * (N + 3), where N is the number of bins +# @param window.size :integer, number of bins to extend. +# @param out_binSignal : string, binSignal file address to write +# @param out_ext : string, ext file address to write +TopDom_0.0.2 <- local({ +TopDom <- function( matrix.file, window.size, outFile=NULL, statFilter=T) +{ + if (inherits(matrix.file, ""TopDomData"")) { + bins <- matrix.file$bins + matrix.data <- matrix.file$counts + n_bins <- nrow(bins) + mean.cf <- rep(0, times = n_bins) + pvalue <- rep(1.0, times = n_bins) + local.ext <- rep(-0.5, times = n_bins) + } else { + print(""#########################################################################"") + print(""Step 0 : File Read "") + print(""#########################################################################"") + window.size = as.numeric(window.size) + matdf <- read.table(matrix.file, header=F) + + if( ncol(matdf) - nrow(matdf) == 3) { + colnames(matdf) <- c(""chr"", ""from.coord"", ""to.coord"") + } else if( ncol(matdf) - nrow(matdf) ==4 ) { + colnames(matdf) <- c(""id"", ""chr"", ""from.coord"", ""to.coord"") + } else { + print(""Unknwon Type of matrix file"") + return(0) + } + n_bins = nrow(matdf) + mean.cf <- rep(0, n_bins) + pvalue <- rep(1, n_bins) + + local.ext = rep(-0.5, n_bins) + + bins <- data.frame(id=1:n_bins, + chr=matdf[, ""chr""], + from.coord=matdf[, ""from.coord""], + to.coord=matdf[, ""to.coord""] ) + matrix.data <- as.matrix( matdf[, (ncol(matdf) - nrow(matdf)+1 ):ncol(matdf)] ) + + print(""-- Done!"") + print(""Step 0 : Done !!"") + } + + + print(""#########################################################################"") + print(""Step 1 : Generating binSignals by computing bin-level contact frequencies"") + print(""#########################################################################"") + ptm <- proc.time() + for(i in 1:n_bins) + { + diamond = Get.Diamond.Matrix(mat.data=matrix.data, i=i, size=window.size) + mean.cf[i] = mean(diamond) + } + + eltm = proc.time() - ptm + print(paste(""Step 1 Running Time : "", eltm[3])) + print(""Step 1 : Done !!"") + + print(""#########################################################################"") + print(""Step 2 : Detect TD boundaries based on binSignals"") + print(""#########################################################################"") + + ptm = proc.time() + #gap.idx = Which.Gap.Region(matrix.data=matrix.data) + #gap.idx = Which.Gap.Region2(mean.cf) + gap.idx = Which.Gap.Region2(matrix.data=matrix.data, window.size) + + proc.regions = Which.process.region(rmv.idx=gap.idx, n_bins=n_bins, min.size=3) + + #print(proc.regions) + + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + local.ext[start:end] = Detect.Local.Extreme(x=mean.cf[start:end]) + } + + eltm = proc.time() - ptm + print(paste(""Step 2 Running Time : "", eltm[3])) + print(""Step 2 : Done !!"") + + if(statFilter) + { + print(""#########################################################################"") + print(""Step 3 : Statistical Filtering of false positive TD boundaries"") + print(""#########################################################################"") + + ptm = proc.time() + print(""-- Matrix Scaling...."") + scale.matrix.data = matrix.data + for( i in 1:(2*window.size) ) + { + #diag(scale.matrix.data[, i:n_bins] ) = scale( diag( matrix.data[, i:n_bins] ) ) + scale.matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] = scale( matrix.data[ seq(1+(n_bins*i), n_bins*n_bins, 1+n_bins) ] ) + } + + print(""-- Compute p-values by Wilcox Ranksum Test"") + for( i in 1:nrow(proc.regions)) + { + start = proc.regions[i, ""start""] + end = proc.regions[i, ""end""] + + print(paste(""Process Regions from "", start, ""to"", end)) + + pvalue[start:end] <- Get.Pvalue(matrix.data=scale.matrix.data[start:end, start:end], size=window.size, scale=1) + } + print(""-- Done!"") + + print(""-- Filtering False Positives"") + local.ext[intersect( union(which( local.ext==-1), which(local.ext==-1)), which(pvalue<0.05))] = -2 + local.ext[which(local.ext==-1)] = 0 + local.ext[which(local.ext==-2)] = -1 + print(""-- Done!"") + + eltm = proc.time() - ptm + print(paste(""Step 3 Running Time : "", eltm[3])) + print(""Step 3 : Done!"") + } else pvalue = 0 + + domains = Convert.Bin.To.Domain.TMP(bins=bins, + signal.idx=which(local.ext==-1), + gap.idx=which(local.ext==-0.5), + pvalues=pvalue, + pvalue.cut=0.05) + + bins = cbind(bins, + local.ext = local.ext, + mean.cf = mean.cf, + pvalue = pvalue) + + bedform = domains[, c(""chr"", ""from.coord"", ""to.coord"", ""tag"")] + colnames(bedform) = c(""chrom"", ""chromStart"", ""chromEnd"", ""name"") + + if( !is.null(outFile) ) { + print(""#########################################################################"") + print(""Writing Files"") + print(""#########################################################################"") + + outBinSignal = paste(outFile, "".binSignal"", sep="""") + print(paste(""binSignal File :"", outBinSignal) ) + write.table(bins, file=outBinSignal, quote=F, row.names=F, col.names=T, sep=""\t"") + + + outDomain = paste(outFile, "".domain"", sep="""") + print(paste(""Domain File :"", outDomain) ) + write.table( domains, file=outDomain, quote=F, row.names=F, col.names=T, sep=""\t"") + + outBed = paste(outFile, "".bed"", sep="""") + print(paste(""Bed File : "", outBed)) + write.table( bedform, file=outBed, quote=F, row.names=F, col.names=F, sep=""\t"") + } + + print(""Done!!"") + + print(""Job Complete !"") + return(list(binSignal=bins, domain=domains, bed=bedform)) +} + +# @fn Get.Diamond.Matrix +# @param mat.data : N by N matrix, where each element indicate contact frequency +# @param i :integer, bin index +# @param size : integer, window size to expand from bin +# @retrun : matrix. +Get.Diamond.Matrix <- function(mat.data, i, size) +{ + n_bins = nrow( mat.data ) + if(i==n_bins) return(NA) + + lowerbound = max( 1, i-size+1 ) + upperbound = min( i+size, n_bins) + + return( mat.data[lowerbound:i, (i+1):upperbound] ) +} + +# @fn Which.process.region +# @param rmv.idx : vector of idx, remove index vector +# @param n_bins : total number of bins +# @param min.size : minimum size of bins +# @retrun : data.frame of proc.regions +Which.process.region <- function(rmv.idx, n_bins, min.size=3) +{ + gap.idx = rmv.idx + + proc.regions = data.frame(start=numeric(0), end=numeric(0)) + proc.set = setdiff(1:n_bins, gap.idx) + n_proc.set = length(proc.set) + + i=1 + while(i < n_proc.set ) + { + start = proc.set[i] + j = i+1 + + while(j <= n_proc.set) + { + if( proc.set[j] - proc.set[j-1] <= 1) j = j + 1 + else { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + i = j + break + } + } + + if(j >= n_proc.set ) { + proc.regions = rbind(proc.regions, c(start=start, end=proc.set[j-1]) ) + break + } + } + + colnames(proc.regions) = c(""start"", ""end"") + proc.regions <- proc.regions[ which( abs(proc.regions[,""end""] - proc.regions[, ""start""]) >= min.size ), ] + + return(proc.regions) +} + +# @fn Which.Gap.Region +# @breif version 0.0.1 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region <- function(matrix.data) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + i=1 + while(i < n_bins) + { + j = i + 1 + while( j <= n_bins) + { + if( sum( matrix.data[i:j, i:j]) == 0 ) { + gap[i:j] = -0.5 + j = j+1 + #if(j-i > 1) gap[i:j]=-0.5 + #j=j+1 + } else break + } + + i = j + } + + idx = which(gap == -0.5) + return(idx) +} + +# @fn Which.Gap.Region3 +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region3 <- function(mean.cf) +{ + n_bins = length(mean.cf) + gapidx = which(mean.cf==0) + + return(gapidx) +} + +# @fn Which.Gap.Region2 +# @breif version 0.0.2 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region2 <- function(matrix.data, w) +{ + n_bins = nrow(matrix.data) + gap = rep(0, n_bins) + + for(i in 1:n_bins) + { + if( sum( matrix.data[i, max(1, i-w):min(i+w, n_bins)] ) == 0 ) gap[i]=-0.5 + } + + idx = which(gap == -0.5) + return(idx) +} + +# @fn Detect.Local.Extreme +# @param x : original signal to find local minima +# @return vector of local extrme, -1 if the index is local minimum, 1 if the index is local maxima, 0 otherwise. +Detect.Local.Extreme <- function(x) +{ + n_bins = length(x) + ret = rep(0, n_bins) + x[is.na(x)]=0 + + if(n_bins <= 3) + { + ret[which.min(x)]=-1 + ret[which.max(x)]=1 + + return(ret) + } + # Norm##################################################3 + new.point = Data.Norm(x=1:n_bins, y=x) + x=new.point$y + ################################################## + cp = Change.Point(x=1:n_bins, y=x) + + if( length(cp$cp) <= 2 ) return(ret) + if( length(cp$cp) == n_bins) return(ret) + for(i in 2:(length(cp$cp)-1)) + { + if( x[cp$cp[i]] >= x[cp$cp[i]-1] && x[cp$cp[i]] >= x[cp$cp[i]+1] ) ret[cp$cp[i]] = 1 + else if(x[cp$cp[i]] < x[cp$cp[i]-1] && x[cp$cp[i]] < x[cp$cp[i]+1]) ret[cp$cp[i]] = -1 + + min.val = min( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + max.val = max( x[ cp$cp[i-1] ], x[ cp$cp[i] ] ) + + if( min( x[cp$cp[i-1]:cp$cp[i]] ) < min.val ) ret[ cp$cp[i-1] - 1 + which.min( x[cp$cp[i-1]:cp$cp[i]] ) ] = -1 + if( max( x[cp$cp[i-1]:cp$cp[i]] ) > max.val ) ret[ cp$cp[i-1] - 1 + which.max( x[cp$cp[i-1]:cp$cp[i]] ) ] = 1 + } + + return(ret) +} + +# @fn Data.Norm +# @param x : x axis vector +# @param x : y axis vector +# @return list of normalized x and y +Data.Norm <- function(x, y) +{ + ret.x = rep(0, length(x)) + ret.y = rep(0, length(y)) + + ret.x[1] = x[1] + ret.y[1] = y[1] + + diff.x = diff(x) + diff.y = diff(y) + + scale.x = 1 / mean( abs(diff(x) ) ) + scale.y = 1 / mean( abs( diff(y) ) ) + + #print(scale.x) + #print(scale.y) + + for(i in 2:length(x)) + { + ret.x[i] = ret.x[i-1] + (diff.x[i-1]*scale.x) + ret.y[i] = ret.y[i-1] + (diff.y[i-1]*scale.y) + } + + return(list(x=ret.x, y=ret.y)) +} + +# @fn Change.Point +# @param x : x axis vector +# @param x : y axis vector +# @return change point index in x vector, +# Note that the first and the last point will be always change point +Change.Point <- function( x, y ) +{ + if( length(x) != length(y)) + { + print(""ERROR : The length of x and y should be the same"") + return(0) + } + + n_bins <- length(x) + Fv <- rep(NA, n_bins) + Ev <- rep(NA, n_bins) + cp <- 1 + + i=1 + Fv[1]=0 + while( i < n_bins ) + { + j=i+1 + Fv[j] = sqrt( (x[j]-x[i])^2 + (y[j] - y[i] )^2 ) + + while(j= 1 && i < n_bins) + { + lower = min(i+1, n_bins) + upper = min(i+size, n_bins) + + new.mat[size-(k-1), 1:(upper-lower+1)] = mat.data[i-(k-1), lower:upper] + } + } + + return(new.mat) +} + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + new.bdr.set = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + + i=1 + while(i <= nrow(ret)) + { + if( ret[i, ""tag""] == ""boundary"" ) + { + stack.bdr = rbind(stack.bdr, ret[i, ]) + } else if(nrow(stack.bdr)>0) { + new.bdr = data.frame(chr=bins[1, ""chr""], + from.id = min( stack.bdr[, ""from.id""]), + from.coord=min(stack.bdr[, ""from.coord""]), + to.id = max( stack.bdr[, ""to.id""]), + to.coord=max(stack.bdr[, ""to.coord""]), + tag=""boundary"", + size=max(stack.bdr[, ""to.coord""]) - min(stack.bdr[, ""from.coord""])) + new.bdr.set = rbind(new.bdr.set, new.bdr) + stack.bdr = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + } + + i = i + 1 + } + + ret = rbind( ret[ ret[, ""tag""]!=""boundary"", ], new.bdr.set ) + ret = ret[order(ret[, ""to.coord""]), ] + + return(ret) +} + + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain.TMP <- function(bins, signal.idx, gap.idx, pvalues=NULL, pvalue.cut=NULL) +{ + n_bins = nrow(bins) + ret = data.frame(chr=character(0), from.id=numeric(0), from.coord=numeric(0), to.id=numeric(0), to.coord=numeric(0), tag=character(0), size=numeric(0)) + levels( x=ret[, ""tag""] ) = c(""domain"", ""gap"", ""boundary"") + + rmv.idx = setdiff(1:n_bins, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + n_procs = nrow(proc.region) + gap = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""gap"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = union(signal.idx, gap.idx) + proc.region = Which.process.region(rmv.idx, n_bins, min.size=0) + n_procs = nrow(proc.region) + from.coord = bins[proc.region[, ""start""], ""from.coord""] + domain = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""domain"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + + rmv.idx = setdiff(1:n_bins, signal.idx) + proc.region = as.data.frame( Which.process.region(rmv.idx, n_bins, min.size=1) ) + n_procs = nrow(proc.region) + if(n_procs>0) + { + from.coord = bins[proc.region[, ""start""]+1, ""from.coord""] + boundary = data.frame(chr=rep( bins[1, ""chr""], n_procs), from.id=rep(0, n_procs), from.coord=from.coord, to.id=rep(0, n_procs), to.coord=rep(0, n_procs), tag=rep(""boundary"", n_procs), size=rep(0, n_procs), stringsAsFactors=F) + ret = rbind(ret, boundary) + } + + ret = rbind(gap, domain) + ret = ret[order(ret[,3]), ] + + ret[, ""to.coord""] = c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] = match( ret[, ""from.coord""], bins[, ""from.coord""] ) + ret[, ""to.id""] = match(ret[, ""to.coord""], bins[, ""to.coord""]) + ret[, ""size""] = ret[,""to.coord""]-ret[,""from.coord""] + + if(!is.null(pvalues) && !is.null(pvalue.cut)) + { + for(i in 1:nrow(ret)) + { + if(ret[i, ""tag""]==""domain"") + { + domain.bins.idx = ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr = which( pvalues[ domain.bins.idx ] < pvalue.cut ) + + if( length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] = ""boundary"" + } + } + } + + return(ret) +} + +TopDom +}) ## local() +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/ggCountHeatmap.R",".R","3464","108","#' Produce a Count Heatmap +#' +#' @param data A TopDomData object. +#' +#' @param transform A function applied to the counts prior to generating +#' heatmap colors. +#' +#' @param colors A named list to control to color scale. +#' +#' @param \ldots Not used. +#' +#' @return A [ggplot2::ggplot] object. +#' +#' @author Henrik Bengtsson. +#' +#' @seealso See [TopDom] for an example. +#' +#' @export +ggCountHeatmap <- function(data, transform, colors, ...) UseMethod(""ggCountHeatmap"") + +#' @importFrom reshape2 melt +#' @importFrom ggplot2 ggplot aes geom_raster coord_fixed theme_void scale_fill_gradient2 +#' @export +ggCountHeatmap.TopDomData <- function(data, transform = function(x) log2(x + 1), colors = c(na = ""white"", mid = ""blue"", high = ""yellow""), ...) { + ## To please R CMD check + x <- y <- counts <- NULL + + keepUpperTriangle <- function(x) { + x[lower.tri(x)] <- NA + x + } + + cols <- eval(formals(ggCountHeatmap.TopDomData)$colors) + keys <- names(cols) + keys <- keys[is.na(colors[keys])] + colors[keys] <- cols[keys] + + dd <- keepUpperTriangle(data$counts) + dd <- melt(dd, varnames = c(""x"", ""y""), na.rm = TRUE, value.name = ""counts"") + + ## Genomic coordinate system + mid <- with(data$bins, (from.coord + to.coord) / 2) + dd$x <- mid[dd$x] + dd$y <- mid[dd$y] + + gg <- ggplot(dd) + gg <- gg + aes(x, y, fill = transform(counts)) + gg <- gg + geom_raster(show.legend = FALSE) + gg <- gg + coord_fixed() + gg <- gg + theme_void() + gg <- gg + scale_fill_gradient2(limits = c(0, NA), na.value = colors[""na""], + mid = colors[""mid""], high = colors[""high""]) + gg +} + + +#' Add a Topological Domain to a Count Heatmap +#' +#' @param td A single-row data.frame. +#' +#' @param dx,delta,vline Absolute distance to heatmap. +#' If `dx = NULL` (default), then `dx = delta * w + vline` where `w` is +#' the width of the domain. +#' +#' @param size,color The thickness and color of the domain line. +#' +#' @return A [ggplot2::geom_segment] object to be added to the count heatmap. +#' +#' @importFrom ggplot2 geom_segment +#' @export +ggDomain <- function(td, dx = NULL, delta = 0.04, vline = 0, size = 2.0, color = ""#666666"") { + x0 <- td$from.coord + x1 <- td$to.coord + if (is.null(dx)) dx <- delta * (x1 - x0) + vline + gg <- geom_segment(aes(x = x0+dx, y = x0-dx, xend = x1+dx, yend = x1-dx), + color = color, size = size) + attr(gg, ""gg_params"") <- list(x0 = x0, x1 = x1, width = x1 - x0, dx = dx, delta = delta, vline = vline) + gg +} + + +#' Add a Topological Domain Label to a Count Heatmap +#' +#' @param td A single-row data.frame. +#' +#' @param fmt The [base::sprintf]-format string taking (chromosome, start, stop) as +#' (string, numeric, numeric) input. +#' +#' @param rot The amount of rotation in \[0,360\] of label. +#' +#' @param dx,vjust The vertical adjustment of the label (relative to rotation) +#' +#' @param cex The scale factor of the label. +#' +#' @return A [ggplot2::ggproto] object to be added to the count heatmap. +#' +#' @importFrom ggplot2 annotation_custom +#' @importFrom grid gpar textGrob +#' @export +ggDomainLabel <- function(td, fmt = ""%s: %.2f - %.2f Mbp"", rot = 45, dx = 0, vjust = 2.5, cex = 1.5) { + chr <- td$chr + x0 <- td$from.coord + dx + x1 <- td$to.coord + dx + label <- sprintf(fmt, chr, x0/1e6, x1/1e6) + grob <- textGrob(label = label, rot = rot, hjust = 0.5, vjust = vjust, gp = gpar(cex = cex)) + annotation_custom(grob = grob, ymin = x0, ymax = x1, xmin = x0, xmax = x1) +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/legacy.R",".R","558","22","#' Easy Access to the Original TopDom 0.0.1 and 0.0.2 Implementations +#' +#' @param version A version string. +#' +#' @return An environment containing the legacy TopDom API. +#' +#' @examples +#' TopDom::legacy(""0.0.2"")$TopDom +#' TopDom::legacy(""0.0.1"")$Detect.Local.Extreme +#' +#' @export +legacy <- function(version = c(""0.0.1"", ""0.0.2"")) { + if (version == ""0.0.1"") { + api <- environment(TopDom_0.0.1) + } else if (version == ""0.0.2"") { + api <- environment(TopDom_0.0.2) + } else { + stop(""Unknown TopDom legacy version: "", sQuote(version)) + } + api +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/TopDomData.R",".R","553","29","#' @importFrom utils str +#' @export +print.TopDomData <- function(x, ...) { + cat(sprintf(""%s:\n"", class(x))) + cat(""bins:\n"") + str(x$bins) + cat(""counts:\n"") + str(x$counts) +} + +#' @export +dim.TopDomData <- function(x) { + dim(x$counts) +} + +#' @export +`[.TopDomData` <- function(x, i, ...) { + structure(list( + bins = x$bins[i, , drop = FALSE], + counts = x$counts[i, i, drop = FALSE] + ), class = ""TopDomData"") +} + +#' @importFrom graphics image +#' @export +image.TopDomData <- function(x, transform = log2, ...) { + image(transform(x$counts), ...) +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/TopDom.R",".R","29383","877","#' Identify Topological Domains from a Hi-C Contact Matrix +#' +#' @param data A TopDomData object, or the pathname to a normalized +#' Hi-C contact matrix file as read by [readHiC()], that specify N bins. +#' +#' @param window.size The number of bins to extend (as a non-negative integer). +#' Recommended range is in {5, ..., 20}. +#' +#' @param outFile (optional) The filename without extension of the three +#' result files optionally produced. See details below. +#' +#' @param statFilter (logical) Specifies whether non-significant +#' topological-domain boundaries should be dropped or not. +#' +#' @param ... Additional arguments passed to [readHiC()]. +#' +#' @param debug If `TRUE`, debug output is produced. +#' +#' @return A named list of class `TopDom` with data.frame elements +#' `binSignal`, `domain`, and `bed`. +#' * The `binSignal` data frame (N-by-7) holds mean contact frequency, +#' local extreme, and p-value for every bin. The first four columns +#' represent basic bin information given by matrix file, such as +#' bin id (`id`), chromosome(`chr`), start coordinate (`from.coord`), +#' and end coordinate (`to.coord`) for each bin. +#' The last three columns (`local.ext`, `mean.cf`, and `p-value`) represent +#' computed values by the TopDom algorithm. +#' The columns are: +#' - `id`: Bin ID +#' - `chr`: Chromosome +#' - `from.coord`: Start coordinate of bin +#' - `to.coord`: End coordinate of bin +#' - `local.ext`: +#' + `-1`: Local minima. +#' + `-0.5`: Gap region. +#' + `0`: General bin. +#' + `1`: Local maxima. +#' - `mean.cf`: Average of contact frequencies between lower and upper +#' regions for bin _i = 1,2,...,N_. +#' - `p-value`: Computed p-value by Wilcox rank sum test. +#' See Shin et al. (2016) for more details. +#' +#' * The `domain` data frame (D-by-7): +#' Every bin is categorized by basic building block, such as gap, domain, +#' or boundary. +#' Each row indicates a basic building block. +#' The first five columns include the basic information about the block, +#' 'tag' column indicates the class of the building block. +#' - `id`: Identifier of block +#' - `chr`: Chromosome +#' - `from.id`: Start bin index of the block +#' - `from.coord`: Start coordinate of the block +#' - `to.id`: End bin index of the block +#' - `to.coord`: End coordinate of the block +#' - `tag`: Categorized name of the block. Three possible blocks exists: +#' + `gap` +#' + `domain` +#' + `boundary` +#' - `size`: size of the block +#' +#' * The `bed` data frame (D-by-4) is a representation of the `domain` +#' data frame in the +#' [BED file format](https://genome.ucsc.edu/FAQ/FAQformat.html#format1). +#' It has four columns: +#' - `chrom`: The name of the chromosome. +#' - `chromStart`: The starting position of the feature in the chromosome. +#' The first base in a chromosome is numbered 0. +#' - `chromEnd`: The ending position of the feature in the chromosome. +#' The `chromEnd` base is _not_ included in the feature. For example, +#' the first 100 bases of a chromosome are defined as `chromStart=0`, +#' `chromEnd=100`, and span the bases numbered 0-99. +#' - `name`: Defines the name of the BED line. This label is displayed to +#' the left of the BED line in the +#' [UCSC Genome Browser](https://genome.ucsc.edu/cgi-bin/hgGateway) +#' window when the track is open to full display mode or directly to +#' the left of the item in pack mode. +#' +#' If argument `outFile` is non-`NULL`, then the three elements (`binSignal`, +#' `domain`, and `bed`) returned are also written to tab-delimited files +#' with file names \file{.binSignal}, \file{.domain}, and +#' \file{.bed}, respectively. None of the files have row names, +#' and all but the BED file have column names. +#' +#' @section Windows size: +#' The `window.size` parameter is by design the only tuning parameter in the +#' TopDom method and affects the amount of smoothing applied when calculating +#' the TopDom bin signals. The binning window extends symmetrically downstream +#' and upstream from the bin such that the bin signal is the average +#' `window.size^2` contact frequencies. +#' For details, see Equation (1) and Figure 1 in Shin et al. (2016). +#' Typically, the number of identified TDs decreases while their average +#' lengths increase as this window-size parameter increases (Figure 2). +#' The default is `window.size = 5` (bins), which is motivated as: +#' ""Considering the previously reported minimum TD size (approx. 200 kb) +#' (Dixon et al., 2012) and our bin size of 40 kb, _w_\[indow.size\] = 5 is a +#' reasonable setting"" (Shin et al., 2016). +#' +#' @example incl/TopDom.R +#' +#' @author Hanjun Shin, Harris Lazaris, and Gangqing Hu. +#' \R package, help, and code refactoring by Henrik Bengtsson. +#' +#' @references +#' +#' * Shin et al., +#' TopDom: an efficient and deterministic method for identifying +#' topological domains in genomes, +#' _Nucleic Acids Research_, 44(7): e70, April 2016. +#' DOI: 10.1093/nar/gkv1505, +#' PMCID: [PMC4838359](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4838359/), +#' PMID: [26704975](https://pubmed.ncbi.nlm.nih.gov/26704975/) +#' +#' * Shin et al., \R script \file{TopDom_v0.0.2.R}, 2017 (originally from +#' \code{http://zhoulab.usc.edu/TopDom/}; +#' later available on \url{https://github.com/jasminezhoulab/TopDom} via +#' \url{https://zhoulab.dgsom.ucla.edu/pages/software}) +#' +#' * Shin et al., TopDom Manual, 2016-07-08 (original from +#' \code{http://zhoulab.usc.edu/TopDom/TopDom\%20Manual_v0.0.2.pdf}; +#' later available on \url{https://github.com/jasminezhoulab/TopDom} via +#' \url{https://zhoulab.dgsom.ucla.edu/pages/software}) +#' +#' * Hanjun Shin, Understanding the 3D genome organization in topological +#' domain level, Doctor of Philosophy Dissertation, +#' University of Southern California, March 2017, +#' \url{https://digitallibrary.usc.edu/cdm/ref/collection/p15799coll40/id/347735} +#' +#' * Dixon JR, Selvaraj S, Yue F, Kim A, et al. Topological domains in +#' mammalian genomes identified by analysis of chromatin interactions. +#' _Nature_; 485(7398):376-80, April 2012. +#' DOI: 10.1038/nature11082, +#' PMCID: [PMC3356448](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3356448/), +#' PMID: 22495300. +#' +#' @importFrom utils read.table write.table +#' @export +TopDom <- function(data, window.size, outFile = NULL, statFilter = TRUE, ..., debug = getOption(""TopDom.debug"", FALSE)) { + window.size <- as.integer(window.size) + stopifnot(is.numeric(window.size), + length(window.size) == 1, + !is.na(window.size), + window.size >= 0) + stopifnot(is.logical(debug), length(debug) == 1L, !is.na(debug)) + + if (is.character(data)) data <- readHiC(data, ...) + stopifnot(inherits(data, ""TopDomData"")) + + bins <- data$bins + matrix.data <- data$counts + n_bins <- nrow(bins) + + mean.cf <- rep(0, times = n_bins) + pvalue <- rep(1.0, times = n_bins) + + ## Gap region (== -0.5) by default + local.ext <- rep(-0.5, times = n_bins) ## gap region + + if (debug) { + mcat(""#########################################################################"") + mcat(""Step 1 : Generating binSignals by computing bin-level contact frequencies"") + mcat(""#########################################################################"") + } + ptm <- proc.time() + for (i in seq_len(n_bins)) { + diamond <- Get.Diamond.Matrix(mat.data = matrix.data, i = i, size = window.size) + mean.cf[i] <- mean(diamond) + } + stop_if_not(length(mean.cf) == n_bins) + + eltm <- proc.time() - ptm + if (debug) { + mcat(""Step 1 Running Time : "", eltm[3]) + mcat(""Step 1 : Done!"") + + mcat(""#########################################################################"") + mcat(""Step 2 : Detect TD boundaries based on binSignals"") + mcat(""#########################################################################"") + } + + ptm <- proc.time() + # gap.idx <- Which.Gap.Region(matrix.data = matrix.data) + # gap.idx <- Which.Gap.Region2(mean.cf) + gap.idx <- Which.Gap.Region2(matrix.data = matrix.data, w = window.size) + + proc.regions <- Which.process.region(rmv.idx = gap.idx, n_bins = n_bins, min.size = 3L) + stop_if_not(!anyNA(proc.regions[[""start""]]), all(proc.regions[[""start""]] >= 1), all(proc.regions[[""start""]] <= n_bins)) + stop_if_not(!anyNA(proc.regions[[""end""]]), all(proc.regions[[""end""]] >= 1), all(proc.regions[[""end""]] <= n_bins)) + + # mcat(proc.regions) + + for (i in seq_len(nrow(proc.regions))) { + start <- proc.regions[i, ""start""] + end <- proc.regions[i, ""end""] + if (debug) mcat(""Process Region #"", i, "" from "", start, "" to "", end) + idxs <- start:end + local.ext[idxs] <- Detect.Local.Extreme(x = mean.cf[idxs]) ## assigns values (-1,0,+1) + } + stop_if_not(!anyNA(local.ext), length(local.ext) == n_bins, all(local.ext %in% c(-0.5, -1, 0, +1))) + rm(list = ""idxs"") + + eltm <- proc.time() - ptm + if (debug) { + mcat(""Step 2 Running Time : "", eltm[3]) + mcat(""Step 2 : Done!"") + } + + if (statFilter) { + if (debug) { + mcat(""#########################################################################"") + mcat(""Step 3 : Statistical Filtering of false positive TD boundaries"") + mcat(""#########################################################################"") + } + + ptm <- proc.time() + if (debug) mcat(""-- Matrix Scaling...."") + scale.matrix.data <- matrix.data + for (i in seq_len(2 * window.size)) { + # diag(scale.matrix.data[, i:n_bins]) <- scale(diag(matrix.data[, i:n_bins])) + idxs <- seq(from = 1 + (n_bins * i), to = n_bins * n_bins, by = 1 + n_bins) + scale.matrix.data[idxs] <- scale(matrix.data[idxs]) + } + rm(list = c(""idxs"", ""matrix.data"")) + + if (debug) mcat(""-- Compute p-values by Wilcox Ranksum Test"") + for (i in seq_len(nrow(proc.regions))) { + start <- proc.regions[i, ""start""] + end <- proc.regions[i, ""end""] + + if (debug) mcat(""Process Region #"", i, "" from "", start, "" to "", end) + + idxs <- start:end + pvalue[idxs] <- Get.Pvalue(matrix.data = scale.matrix.data[idxs, idxs], size = window.size, scale = 1.0) + } + rm(list = ""idxs"") + stop_if_not(length(pvalue) == n_bins, !anyNA(pvalue)) + if (debug) mcat(""-- Done!"") + + if (debug) mcat(""-- Filtering False Positives"") + ## NOTE: The below duplication is left on purpose until we fully + ## understand why it is there in the first place, cf. + ## https://github.com/HenrikBengtsson/TopDom/issues/3 +# local.ext[((local.ext == -1.0) | (local.ext == -1.0)) & (pvalue < 0.05)] <- -2.0 +# local.ext[local.ext == -1.0] <- 0.0 ## general bin +# local.ext[local.ext == -2.0] <- -1.0 ## local minima + ## ""Finally, we filter out local minima with P-values larger than 0.05. [...]"" + ## (Page 4 in Shin et al. 2016) + local.ext[local.ext == -1.0 & pvalue >= 0.05] <- 0.0 ## drop non-significant local minima + + stop_if_not(!anyNA(local.ext), length(local.ext) == n_bins, all(local.ext %in% c(-0.5, -1, 0, +1))) + + if (debug) mcat(""-- Done!"") + + eltm <- proc.time() - ptm + if (debug) mcat(""Step 3 Running Time : "", eltm[3]) + if (debug) mcat(""Step 3 : Done!"") + } else { + rm(list = ""matrix.data"") + pvalue <- 0 + } + + if (debug) { + mcat(""#########################################################################"") + mcat(""Step 4 : Convert bins to domains (internal step)"") + mcat(""#########################################################################"") + } + + domains <- Convert.Bin.To.Domain.TMP( + bins = bins, + signal.idx = which(local.ext == -1.0), ## local minima + gap.idx = which(local.ext == -0.5), ## gap region + pvalues = pvalue, + pvalue.cut = 0.05 + ) + + bins <- cbind( + bins, + local.ext = local.ext, + mean.cf = mean.cf, + pvalue = pvalue + ) + + bedform <- domains[, c(""chr"", ""from.coord"", ""to.coord"", ""tag"")] + colnames(bedform) <- c(""chrom"", ""chromStart"", ""chromEnd"", ""name"") + + if (!is.null(outFile)) { + if (debug) { + mcat(""#########################################################################"") + mcat(""Writing Files"") + mcat(""#########################################################################"") + } + + outBinSignal <- paste0(outFile, "".binSignal"") + if (debug) mcat(""binSignal File : "", outBinSignal) + write.table(bins, file = outBinSignal, quote = FALSE, row.names = FALSE, col.names = TRUE, sep = ""\t"") + + outDomain <- paste0(outFile, "".domain"") + if (debug) mcat(""Domain File : "", outDomain) + write.table(domains, file = outDomain, quote = FALSE, row.names = FALSE, col.names = TRUE, sep = ""\t"") + + outBed <- paste0(outFile, "".bed"") + if (debug) mcat(""Bed File : "", outBed) + write.table(bedform, file = outBed, quote = FALSE, row.names = FALSE, col.names = FALSE, sep = ""\t"") + } + + if (debug) mcat(""Done!"") + + if (debug) mcat(""Job Complete!"") + + res <- structure( + list(binSignal = bins, domain = domains, bed = bedform), + class = ""TopDom"" + ) + attr(res, ""parameters"") <- list( + window.size = window.size, + statFilter = statFilter + ) + + res +} + +# @fn Get.Diamond.Matrix +# +# @param mat.data N-by-N numeric matrix, where each element indicate contact frequency +# +# @param i (integer) a bin index +# +# @param size (integer) the window size to expand from bin `i` +# +# @return A subset of the `mat.data` matrix. If `i` == N, then a missing value is returned. +Get.Diamond.Matrix <- function(mat.data, i, size) { + n_bins <- nrow(mat.data) + if (i == n_bins) { + na <- NA_real_ + storage.mode(na) <- storage.mode(mat.data) + return(na) + } + + lowerbound <- max(1, i - size + 1) + upperbound <- min(i + size, n_bins) + + mat.data[lowerbound:i, (i + 1):upperbound] +} + +# @fn Which.process.region +# @param rmv.idx : vector of idx, remove index vector +# @param n_bins : total number of bins +# @param min.size : (integer) minimum size of bins +# @retrun : data.frame of proc.regions +Which.process.region <- function(rmv.idx, n_bins, min.size = 3L) { + gap.idx <- rmv.idx + + proc.regions <- data.frame(start = numeric(0), end = numeric(0), stringsAsFactors = FALSE) + proc.set <- setdiff(seq_len(n_bins), gap.idx) + n_proc.set <- length(proc.set) + + i <- 1 + while (i < n_proc.set) { + start <- proc.set[i] + j <- i + 1 + + while (j <= n_proc.set) { + if (proc.set[j] - proc.set[j - 1] <= 1) { + j <- j + 1 + } else { + proc.regions <- rbind(proc.regions, c(start = start, end = proc.set[j - 1])) + i <- j + break + } + } + + if (j >= n_proc.set) { + proc.regions <- rbind(proc.regions, c(start = start, end = proc.set[j - 1])) + break + } + } + + colnames(proc.regions) <- c(""start"", ""end"") + proc.regions <- proc.regions[abs(proc.regions[, ""end""] - proc.regions[, ""start""]) >= min.size, ] + + proc.regions +} + +# @fn Which.Gap.Region +# @breif version 0.0.1 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region <- function(matrix.data) { + n_bins <- nrow(matrix.data) + gap <- rep(0, times = n_bins) + + i <- 1 + while (i < n_bins) { + j <- i + 1 + while (j <= n_bins) { + idxs <- i:j + if (sum(matrix.data[idxs, idxs]) == 0) { + gap[idxs] <- -0.5 + j <- j + 1 + # if (j-i > 1) gap[idxs] <- -0.5 + # j <- j+1 + } else { + break + } + } + + i <- j + } + + idx <- which(gap == -0.5) + idx +} + +# @fn Which.Gap.Region3 +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region3 <- function(mean.cf) { + n_bins <- length(mean.cf) + gapidx <- which(mean.cf == 0) + + gapidx +} + +# @fn Which.Gap.Region2 +# @breif version 0.0.2 used +# @param matrix.data : n by n matrix +# @return gap index +Which.Gap.Region2 <- function(matrix.data, w) { + n_bins <- nrow(matrix.data) + gap <- rep(0, times = n_bins) + + for (i in seq_len(n_bins)) { + if (sum(matrix.data[i, max(1, i - w):min(i + w, n_bins)]) == 0) gap[i] <- -0.5 + } + + idx <- which(gap == -0.5) + idx +} + +# @fn Detect.Local.Extreme +# @param x : original signal to find local minima +# @return vector of local extremes, -1 if the index is local minimum, +1 if the index is local maxima, 0 otherwise. +Detect.Local.Extreme <- function(x) { + n_bins <- length(x) + ret <- rep(0, times = n_bins) ## general bin (default) + x[is.na(x)] <- 0 ## general bin + + if (n_bins <= 3) { + ret[which.min(x)] <- -1 ## local minima + ret[which.max(x)] <- +1 ## local maxima + return(ret) + } + + # Norm##################################################3 + new.point <- Data.Norm(x = seq_len(n_bins), y = x) + x <- new.point$y + ################################################## + cp <- Change.Point(x = seq_len(n_bins), y = x) + cp <- cp$cp + + ncp <- length(cp) + if (ncp <= 2) return(ret) + if (ncp == n_bins) return(ret) + + for (i in 2:(ncp-1)) { + cp_b <- cp[i] + cp_c <- cp[i-1] + + x_a <- x[cp_b-1] + x_b <- x[cp_b] + x_c <- x[cp_b+1] + + if (x_b >= x_a && x_b >= x_c) { + ret[cp_b] <- +1 ## local maxima + } else if (x_b < x_a && x_b < x_c) { + ret[cp_b] <- -1 ## local minima + } + + min.val <- min(x[cp_c], x_b) + max.val <- max(x[cp_c], x_b) + + x_r <- x[cp_c:cp_b] + if (min(x_r) < min.val) ret[cp_c-1 + which.min(x_r)] <- -1 ## local minima + if (max(x_r) > max.val) ret[cp_c-1 + which.max(x_r)] <- +1 ## local maxima + } + + ret +} + +# @fn Data.Norm +# @param x : x axis vector +# @param x : y axis vector +# @return list of normalized x and y +Data.Norm <- function(x, y) { + ret.x <- rep(0, times = length(x)) + ret.y <- rep(0, times = length(y)) + + ret.x[1] <- x[1] + ret.y[1] <- y[1] + + diff.x <- diff(x) + diff.y <- diff(y) + + scale.x <- 1 / mean(abs(diff(x))) + scale.y <- 1 / mean(abs(diff(y))) + + # mcat(scale.x) + # mcat(scale.y) + + diff.x <- diff.x * scale.x + diff.y <- diff.y * scale.y + + for (i in 2:length(x)) { + ret.x[i] <- ret.x[i - 1] + diff.x[i - 1] + ret.y[i] <- ret.y[i - 1] + diff.y[i - 1] + } + + list(x = ret.x, y = ret.y) +} + +# @fn Change.Point +# @param x : x axis vector +# @param x : y axis vector +# @return change point index in x vector, +# Note that the first and the last point will be always change point +Change.Point <- function(x, y) { + if (length(x) != length(y)) { + mcat(""ERROR : The length of x and y should be the same"") + return(0) + } + + n_bins <- length(x) + Fv <- rep(NA_real_, times = n_bins) + Ev <- rep(NA_real_, times = n_bins) + cp <- 1 + + i <- 1 + Fv[1] <- 0 + while (i < n_bins) { + j <- i + 1 + Fv[j] <- sqrt((x[j] - x[i]) ^ 2 + (y[j] - y[i]) ^ 2) + + while (j < n_bins) { + j <- j + 1 + k <- (i + 1):(j - 1) + dx_ji <- x[j] - x[i] + dy_ji <- y[j] - y[i] + A <- sqrt(dx_ji^2 + dy_ji^2) + Ev_j <- sum(abs(dy_ji*x[k] - dx_ji*y[k] - x[i]*y[j] + x[j]*y[i])) / A + Ev[j] <- Ev_j + Fv[j] <- A - Ev_j + + ################################################# + # Not Original Code + if (is.na(Fv[j]) || is.na(Fv[j - 1])) { + j <- j - 1 + cp <- c(cp, j) + break + } + #################################################### 3 + if (Fv[j] < Fv[j - 1]) { + j <- j - 1 + cp <- c(cp, j) + break + } + } + i <- j + } + + cp <- c(cp, n_bins) + + list(cp = cp, objF = Fv, errF = Ev) +} + +# @fn Get.Pvalue +# @param matrix.data : matrix +# @param size : size to extend +# @param scale : scale parameter if necessary. deprecated parameter +# @return computed p-value vector +#' @importFrom stats wilcox.test +Get.Pvalue <- function(matrix.data, size, scale = 1.0) { + n_bins <- nrow(matrix.data) + pvalue <- rep(1, times = n_bins) + + for (i in seq_len(n_bins - 1)) { + dia <- as.vector(Get.Diamond.Matrix2(matrix.data, i = i, size = size)) + ups <- as.vector(Get.Upstream.Triangle(matrix.data, i = i, size = size)) + downs <- as.vector(Get.Downstream.Triangle(matrix.data, i = i, size = size)) + + wil.test <- wilcox.test(x = dia * scale, y = c(ups, downs), alternative = ""less"", exact = FALSE) + pvalue[i] <- wil.test$p.value + + # mcat(i, "" = "", wil.test$p.value) + } + + pvalue[is.na(pvalue)] <- 1 + pvalue +} + +# @fn Get.Upstream.Triangle +# @param mat.data : matrix data +# @param i : bin index +# @param size : size of window to extend +# @return upstream triangle matrix +Get.Upstream.Triangle <- function(mat.data, i, size) { + n_bins <- nrow(mat.data) + + lower <- max(1, i - size) + idxs <- lower:i + tmp.mat <- mat.data[idxs, idxs] + tmp.mat[upper.tri(tmp.mat, diag = FALSE)] +} + +# @fn Get.Downstream.Triangle +# @param mat.data : matrix data +# @param i : bin index +# @param size : size of window to extend +# @return downstream triangle matrix +Get.Downstream.Triangle <- function(mat.data, i, size) { + n_bins <- nrow(mat.data) + if (i == n_bins) { + na <- NA_real_ + storage.mode(na) <- storage.mode(mat.data) + return(na) + } + + upperbound <- min(i + size, n_bins) + idxs <- (i + 1):upperbound + tmp.mat <- mat.data[idxs, idxs] + tmp.mat[upper.tri(tmp.mat, diag = FALSE)] +} + +# @fn Get.Diamond.Matrix2 +# @param mat.data : matrix data +# @param i : bin index +# @param size : size of window to extend +# @return diamond matrix +Get.Diamond.Matrix2 <- function(mat.data, i, size) { + n_bins <- nrow(mat.data) + na <- NA_real_ + storage.mode(na) <- storage.mode(mat.data) + new.mat <- matrix(rep(na, times = size * size), nrow = size, ncol = size) + + for (k in seq_len(size)) { + if (i - (k - 1) >= 1 && i < n_bins) { + lower <- min(i + 1, n_bins) + upper <- min(i + size, n_bins) + + new.mat[size - (k - 1), seq_len(upper - lower + 1)] <- mat.data[i - (k - 1), lower:upper] + } + } + + new.mat +} + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain <- function(bins, signal.idx, gap.idx, pvalues = NULL, pvalue.cut = NULL) { + n_bins <- nrow(bins) + ret <- data.frame(chr = character(0), from.id = numeric(0), from.coord = numeric(0), to.id = numeric(0), to.coord = numeric(0), tag = character(0), size = numeric(0), stringsAsFactors = FALSE) + levels(x = ret[, ""tag""]) <- c(""domain"", ""gap"", ""boundary"") + + rmv.idx <- setdiff(seq_len(n_bins), gap.idx) + proc.region <- Which.process.region(rmv.idx, n_bins = n_bins, min.size = 0L) + from.coord <- bins[proc.region[, ""start""], ""from.coord""] + n_procs <- nrow(proc.region) + zeros <- double(length = n_procs) + gap <- data.frame( + chr = rep(bins[1, ""chr""], times = n_procs), + from.id = zeros, + from.coord = from.coord, + to.id = zeros, + to.coord = zeros, + tag = rep(""gap"", times = n_procs), + size = zeros, + stringsAsFactors = FALSE + ) + + rmv.idx <- union(signal.idx, gap.idx) + proc.region <- Which.process.region(rmv.idx, n_bins = n_bins, min.size = 0L) + n_procs <- nrow(proc.region) + from.coord <- bins[proc.region[, ""start""], ""from.coord""] + zeros <- double(length = n_procs) + domain <- data.frame( + chr = rep(bins[1, ""chr""], times = n_procs), + from.id = zeros, + from.coord = from.coord, + to.id = zeros, + to.coord = zeros, + tag = rep(""domain"", times = n_procs), + size = zeros, + stringsAsFactors = FALSE + ) + + rmv.idx <- setdiff(seq_len(n_bins), signal.idx) + proc.region <- as.data.frame(Which.process.region(rmv.idx, n_bins = n_bins, min.size = 1L)) + n_procs <- nrow(proc.region) + if (n_procs > 0) { + from.coord <- bins[proc.region[, ""start""] + 1, ""from.coord""] + zeros <- double(length = n_procs) + boundary <- data.frame( + chr = rep(bins[1, ""chr""], times = n_procs), + from.id = zeros, + from.coord = from.coord, + to.id = zeros, + to.coord = zeros, + tag = rep(""boundary"", times = n_procs), + size = zeros, + stringsAsFactors = FALSE + ) + ret <- rbind(ret, boundary) + } + + ret <- rbind(gap, domain) + ret <- ret[order(ret[, 3]), ] + + ret[, ""to.coord""] <- c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] <- match(ret[, ""from.coord""], table = bins[, ""from.coord""]) + ret[, ""to.id""] <- match(ret[, ""to.coord""], table = bins[, ""to.coord""]) + ret[, ""size""] <- ret[, ""to.coord""] - ret[, ""from.coord""] + + if (!is.null(pvalues) && !is.null(pvalue.cut)) { + for (i in seq_len(nrow(ret))) { + if (ret[i, ""tag""] == ""domain"") { + domain.bins.idx <- ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr <- which(pvalues[domain.bins.idx] < pvalue.cut) + + if (length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] <- ""boundary"" + } + } + } + + new.bdr.set <- stack.bdr <- stack.bdr.empty <- data.frame( + chr = character(0), + from.id = numeric(0), + from.coord = numeric(0), + to.id = numeric(0), + to.coord = numeric(0), + tag = character(0), + size = numeric(0), + stringsAsFactors = FALSE + ) + + i <- 1L + while (i <= nrow(ret)) { + if (ret[i, ""tag""] == ""boundary"") { + stack.bdr <- rbind(stack.bdr, ret[i, ]) + } else if (nrow(stack.bdr) > 0) { + new.bdr <- data.frame( + chr = bins[1, ""chr""], + from.id = min(stack.bdr[, ""from.id""]), + from.coord = min(stack.bdr[, ""from.coord""]), + to.id = max(stack.bdr[, ""to.id""]), + to.coord = max(stack.bdr[, ""to.coord""]), + tag = ""boundary"", + size = max(stack.bdr[, ""to.coord""]) - min(stack.bdr[, ""from.coord""]), + stringsAsFactors = FALSE + ) + new.bdr.set <- rbind(new.bdr.set, new.bdr) + stack.bdr <- stack.bdr.empty + } + + i <- i + 1L + } + rm(list = c(""stack.bdr"", ""stack.bdr.empty"")) + + + ret <- rbind(ret[ret[, ""tag""] != ""boundary"", ], new.bdr.set) + ret <- ret[order(ret[, ""to.coord""]), ] + + ret +} + + +# @fn Convert.Bin.To.Domain +# @param bins : bin information +# @param signal.idx : signal index +# @param signal.idx : gap index +# @param pvalues : pvalue vector +# @param pvalue.cut : pvalue threshold +# @return dataframe storing domain information +Convert.Bin.To.Domain.TMP <- function(bins, signal.idx, gap.idx, pvalues = NULL, pvalue.cut = NULL) { + n_bins <- nrow(bins) + ret <- data.frame(chr = character(0), from.id = numeric(0), from.coord = numeric(0), to.id = numeric(0), to.coord = numeric(0), tag = character(0), size = numeric(0), stringsAsFactors = FALSE) + levels(x = ret[, ""tag""]) <- c(""domain"", ""gap"", ""boundary"") + + rmv.idx <- setdiff(seq_len(n_bins), gap.idx) + proc.region <- Which.process.region(rmv.idx, n_bins = n_bins, min.size = 0L) + from.coord <- bins[proc.region[, ""start""], ""from.coord""] + n_procs <- nrow(proc.region) + zeros <- double(length = n_procs) + gap <- data.frame(chr = rep(bins[1, ""chr""], times = n_procs), from.id = zeros, from.coord = from.coord, to.id = zeros, to.coord = zeros, tag = rep(""gap"", times = n_procs), size = zeros, stringsAsFactors = FALSE) + + rmv.idx <- union(signal.idx, gap.idx) + proc.region <- Which.process.region(rmv.idx, n_bins = n_bins, min.size = 0L) + n_procs <- nrow(proc.region) + from.coord <- bins[proc.region[, ""start""], ""from.coord""] + zeros <- double(length = n_procs) + domain <- data.frame(chr = rep(bins[1, ""chr""], times = n_procs), from.id = zeros, from.coord = from.coord, to.id = zeros, to.coord = zeros, tag = rep(""domain"", times = n_procs), size = zeros, stringsAsFactors = FALSE) + + rmv.idx <- setdiff(seq_len(n_bins), signal.idx) + proc.region <- as.data.frame(Which.process.region(rmv.idx, n_bins = n_bins, min.size = 1L)) + n_procs <- nrow(proc.region) + if (n_procs > 0) { + from.coord <- bins[proc.region[, ""start""] + 1, ""from.coord""] + zeros <- double(length = n_procs) + boundary <- data.frame(chr = rep(bins[1, ""chr""], times = n_procs), from.id = zeros, from.coord = from.coord, to.id = zeros, to.coord = zeros, tag = rep(""boundary"", times = n_procs), size = zeros, stringsAsFactors = FALSE) + ret <- rbind(ret, boundary) + } + + if (nrow(domain) == 0L) { + ret <- gap + } else { + ret <- rbind(gap, domain) + ret <- ret[order(ret[, 3]), ] + + ## FIXME: Below code assumes nrow(ret) >= 2 + ret[, ""to.coord""] <- c(ret[2:nrow(ret), ""from.coord""], bins[n_bins, ""to.coord""]) + ret[, ""from.id""] <- match(ret[, ""from.coord""], table = bins[, ""from.coord""]) + ret[, ""to.id""] <- match(ret[, ""to.coord""], table = bins[, ""to.coord""]) + ret[, ""size""] <- ret[, ""to.coord""] - ret[, ""from.coord""] + + if (!is.null(pvalues) && !is.null(pvalue.cut)) { + for (i in seq_len(nrow(ret))) { + if (ret[i, ""tag""] == ""domain"") { + domain.bins.idx <- ret[i, ""from.id""]:ret[i, ""to.id""] + p.value.constr <- which(pvalues[domain.bins.idx] < pvalue.cut) + + if (length(domain.bins.idx) == length(p.value.constr)) ret[i, ""tag""] <- ""boundary"" + } + } + } + } + + ret +} + + + +#' @importFrom utils str +#' @export +print.TopDom <- function(x, ...) { + cat(sprintf(""%s:\n"", class(x))) + cat(""Parameters:\n"") + params <- attr(x, ""parameters"") + if (length(params) > 0L) { + cat(sprintf(""- window.size: %d\n"", params$window.size)) + cat(sprintf(""- statFilter: %s\n"", params$statFilter)) + } else { + cat("" - N/A\n"") + } + cat(""binSignal:\n"") + str(x$binSignal) + cat(""domain:\n"") + str(x$domain) + cat(""bed:\n"") + str(x$bed) +} + +#' @export +dim.TopDom <- function(x) { + dim(x$domain) +} + +#' @export +`[.TopDom` <- function(x, i, ...) { + structure(list( + binSignal = x$binSignal, + domain = x$domain[i, , drop = FALSE], + bed = x$bed[i, , drop = FALSE] + ), class = ""TopDom"") +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/utils.R",".R","799","32","#' @importFrom utils capture.output +mcat <- function(...) { + msg <- paste0(...) + cat(msg, ""\n"", sep = """", file = stderr()) +} + + +#' Asserts the Truth of R Expressions +#' +#' @param \dots Zero or more \R expressions to be asserted to be TRUE. +#' +#' @return Nothing. +#' +#' @details +#' A bare bone, faster version of [base::stopifnot]. +#' +#' @keywords internal +stop_if_not <- function(...) { + res <- list(...) + for (ii in seq_along(res)) { + res_ii <- .subset2(res, ii) + if (length(res_ii) != 1L || is.na(res_ii) || !res_ii) { + mc <- match.call() + call <- deparse(mc[[ii + 1]], width.cutoff = 60L) + if (length(call) > 1L) call <- paste(call[1L], ""...."") + stop(sprintf(""%s is not TRUE"", sQuote(call)), + call. = FALSE, domain = NA) + } + } + invisible() +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/readHiC.R",".R","5634","157","#' Reads Hi-C Contact Data from File +#' +#' @param file The pathname of a normalize Hi-C contact matrix file +#' stored as a whitespace-delimited file. See below for details. +#' Also a gzip-compressed file can be used. +#' +#' @param chr,binSize If the file contains a count matrix without bin +#' annotation, the latter is created from these parameters. +#' +#' @param \ldots Arguments passed to [utils::read.table()] as-is. +#' +#' @param debug If `TRUE`, debug output is produced. +#' +#' @return A list with elements \code{bins} (an N-by-4 data.frame) and +#' \code{counts} (N-by-N matrix). +#' +#' @section Format of HiC contact-matrix file: +#' The contact-matrix file should be a whitespace-delimited text file with +#' neither row names nor column names. The content should be a N-by-(3+N) +#' table where the first three columns correspond to `chr` (string), +#' `from.coord` (integer position), and `to.coord` (integer position). +#' These column defines the genomic location of the N Hi-C bins (in order). +#' The last N columns should contain normalized contact counts (float) such +#' that element (r,3+c) in this table corresponds to count (r,c) in the +#' normalized contact matrix. +#' +#' If an N-by-(4+N) table, then the first column is assumed to contain an +#' `id` (integer), and everything else as above. +#' +#' Example: +#' \preformatted{ +#' chr10 0 40000 0 0 0 0 ... +#' chr10 40000 80000 0 0 0 0 ... +#' chr10 80000 120000 0 0 0 0 ... +#' chr10 120000 160000 0 0 0 0 ... +#' ... +#' } +#' +#' @example incl/readHiC.R +#' +#' @seealso [TopDom]. +#' +#' @importFrom utils file_test read.table +#' @export +readHiC <- function(file, chr = NULL, binSize = NULL, ..., debug = getOption(""TopDom.debug"", FALSE)) { + stopifnot(file_test(""-f"", file)) + stopifnot(is.logical(debug), length(debug) == 1L, !is.na(debug)) + + if (debug) { + mcat(""#########################################################################"") + mcat(""Step 0 : File Read"") + mcat(""#########################################################################"") + } + + if (!is.null(chr)) { + chr <- as.character(chr) + stopifnot(is.character(chr), length(chr) == 1, !is.na(chr)) + binSize <- as.integer(binSize) + stopifnot(is.integer(binSize), length(binSize) == 1, !is.na(binSize), binSize >= 1) + + args <- list(..., comment.char = """", na.strings = """", quote = """", + stringsAsFactors = FALSE) + bins <- args$bins + args$bins <- NULL + args <- args[unique(names(args))] + argsT <- c(list(file, header = FALSE, nrows = 1L), args) + first <- do.call(read.table, args = argsT) + if (debug) mcat("" -- reading "", length(first), ""-by-"", length(first), "" count matrix"") + ## Assert that it's a count matrix + is.numeric <- unlist(lapply(first, FUN = is.numeric), use.names = FALSE) + stopifnot(all(is.numeric)) + + if (!is.null(bins)) { + if (any(bins < 1)) { + stop(""Argument 'bins' specifies non-positive bin indices"") + } else if (any(bins > length(first))) { + stop(sprintf(""Argument 'bins' specifies bin indices out of range [1,%d]"", length(first))) + } + colClasses <- rep(""NULL"", times = length(first)) + colClasses[bins] <- ""numeric"" + } else { + colClasses <- rep(""numeric"", times = length(first)) + } + argsT <- c(list(file, colClasses = colClasses, header = FALSE), args) + matrix.data <- do.call(read.table, args = argsT) + colnames(matrix.data) <- NULL + + if (!is.null(bins)) { + matrix.data <- matrix.data[bins, , drop = FALSE] + } + + ## N-by-N count matrix (from file content) + matrix.data <- as.matrix(matrix.data) + dimnames(matrix.data) <- NULL + stopifnot(nrow(matrix.data) == ncol(matrix.data)) + n_bins <- length(first) + + from.coord <- seq(from = 0, by = binSize, length.out = n_bins) + to.coord <- seq(from = binSize, by = binSize, length.out = n_bins) + if (is.null(bins)) { + stopifnot(n_bins == nrow(matrix.data)) + id <- seq_len(n_bins) + } else { + n_bins <- length(bins) + id <- bins + from.coord <- from.coord[bins] + to.coord <- to.coord[bins] + } + + ## Bin annotation from (chr, binSize) + bins <- data.frame( + id = id, + chr = chr, + from.coord = from.coord, + to.coord = to.coord, + stringsAsFactors = FALSE + ) + } else { + args <- list(..., stringsAsFactors = FALSE) + args <- args[unique(names(args))] + argsT <- c(list(file, header = FALSE), args) + matdf <- do.call(read.table, args = argsT) + n_bins <- nrow(matdf) + if (ncol(matdf) - n_bins == 3) { + colnames(matdf) <- c(""chr"", ""from.coord"", ""to.coord"") + } else if (ncol(matdf) - n_bins == 4) { + colnames(matdf) <- c(""id"", ""chr"", ""from.coord"", ""to.coord"") + } else { + stop(""Unknown format of count-matrix file: "", sQuote(file)) + } + + ## Bin annotation (from file content) + bins <- data.frame( + id = seq_len(n_bins), + chr = matdf[[""chr""]], + from.coord = matdf[[""from.coord""]], + to.coord = matdf[[""to.coord""]], + stringsAsFactors = FALSE + ) + + ## N-by-N count matrix (from file content) + matdf <- matdf[, (ncol(matdf) - n_bins + 1):ncol(matdf)] + matrix.data <- as.matrix(matdf) + rm(list = ""matdf"") + } + + stopifnot(is.numeric(matrix.data), + is.matrix(matrix.data), + nrow(matrix.data) == ncol(matrix.data), + nrow(matrix.data) == n_bins) + + if (debug) mcat(""-- Done!"") + if (debug) mcat(""Step 0 : Done!"") + + structure(list(bins = bins, counts = matrix.data), class = ""TopDomData"") +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/subsetByRegion.R",".R","1308","50","#' Subset a TopDomData Object by Region +#' +#' @param data A TopDomData object. +#' +#' @param region A TopDom domain (a data.frame). +#' +#' @param margin An non-negative numeric specifying the additional margin +#' extracted around the domain. +#' If `margin < 1`, then the size of the margin is relative +#' to the size of the domain. +#' +#' @return A TopDomData object. +#' +#' @author Henrik Bengtsson. +#' +#' @export +subsetByRegion <- function(data, region, margin = 1/2) { + UseMethod(""subsetByRegion"") +} + + +#' @export +subsetByRegion.TopDomData <- function(data, region, margin = 1/2) { + stopifnot(is.data.frame(region)) + stopifnot(margin >= 0) + + if (margin < 1) { + margin <- margin * (region$to.coord - region$from.coord) + } + + idxs <- with(data$bins, which(chr == region$chr & from.coord >= region$from.coord - margin & to.coord <= region$to.coord + margin)) + + data[idxs] +} + + +#' @export +subsetByRegion.TopDom <- function(data, region, margin = 1/2) { + stopifnot(is.data.frame(region)) + stopifnot(margin >= 0) + + if (margin < 1) { + margin <- margin * (region$to.coord - region$from.coord) + } + + idxs <- with(data$domain, which(chr == region$chr & from.coord >= region$from.coord - margin & to.coord <= region$to.coord + margin)) + + data[idxs, ] +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","R/exdata.R",".R","2197","51","#' Data for the TopDom Package +#' +#' The \file{exdata/} folder of this package provides a example data set +#' used in examples. The data are also used to validate the \pkg{TopDom} +#' implementation toward the original TopDom scripts. +#' +#' @section Origin: +#' The data herein contain a tiny subset of the HiC and TopDom data used +#' in the TopDom study (Shin et al., 2016). +#' More precisely, it contains: +#' +#' 1. A TopDom file \file{mESC_5w_chr19.nij.HindIII.comb.40kb.domain}, which +#' is part of the \file{mESC_5w_domain.zip} file +#' (5,504 bytes; md5 ffb19996f681a4d35d5c9944f2c44343) from the +#' Supplementary Materials of Shin et al. (2016). +#' These data were downloaded from the +#' TopDom website (http://zhoulab.usc.edu/TopDom/ - now defunct). +#' +#' 2. A normalized HiC-count matrix file \file{nij.chr19.gz}, where the +#' non-compressed version is part of the \file{mESC.norm.tar.gz} file +#' (1,305,763,679 bytes; md5 2e79d0f57463b5b7c4bf86b187086d3c) made available +#' by [UCSD Ren Lab](http://renlab.sdsc.edu/renlab_website/) originally +#' downloaded from \file{http://chromosome.sdsc.edu/mouse/hi-c/download.html} +#' (no longer available). +#' It is a tab-delimited file containing a 3250-by-3250 numeric matrix +#' non-negative decimal values. The underlying HiC sequence data is +#' available from +#' [GSE35156](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE35156) +#' on GEO and was published part of Dixon, et al. (2012). +#' +#' @references +#' 1. Dixon JR, Selvaraj S, Yue F, Kim A, et al. Topological domains in +#' mammalian genomes identified by analysis of chromatin interactions. +#' Nature 2012 Apr 11; 485(7398):376-80, +#' doi: 10.1038/nature11082, +#' PMCID: [PMC3356448](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3356448/), +#' PMID: 22495300. +#' +#' 2. Shin, et al., TopDom: an efficient and deterministic method for +#' identifying topological domains in genomes, +#' Nucleic Acids Res. 2016 Apr 20; 44(7): e70., 2016. +#' doi: 10.1093/nar/gkv1505, +#' PMCID: [PMC4838359](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4838359/), +#' PMID: 26704975. +#' +#' @name TopDom-data +#' @aliases TopDom-data +#' @docType data +#' @keywords data +NULL +","R" +"Nucleic acids","HenrikBengtsson/TopDom","incl/overlapScores.R",".R","696","23","library(tibble) +path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) + +## Original count data (on a subset of the bins to speed up example) +chr <- ""chr19"" +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3, bins = 1:500) +print(data) + +## Find topological domains using TopDom method for two window sizes +tds_5 <- TopDom(data, window.size = 5L) +tds_6 <- TopDom(data, window.size = 6L) + +## Overlap scores (in both directions) +overlap_56 <- overlapScores(tds_6, reference = tds_5) +print(overlap_56) +print(as_tibble(overlap_56)) + +overlap_65 <- overlapScores(tds_5, reference = tds_6) +print(overlap_65) +print(as_tibble(overlap_65)) + +","R" +"Nucleic acids","HenrikBengtsson/TopDom","incl/TopDom.R",".R","1773","52","path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) + +## Original count data (on a subset of the bins to speed up example) +chr <- ""chr19"" +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3, bins = 1:500) +print(data) ## a TopDomData object + +## Find topological domains using the TopDom method +fit <- TopDom(data, window.size = 5L) +print(fit) ## a TopDom object + +## Display the largest domain +td <- subset(subset(fit$domain, tag == ""domain""), size == max(size)) +print(td) ## a data.frame + +## Subset TopDomData object +data_s <- subsetByRegion(data, region = td, margin = 0.9999) +print(data_s) ## a TopDomData object + +vp <- grid::viewport(angle = -45, width = 0.7, y = 0.3) +gg <- ggCountHeatmap(data_s) +gg <- gg + ggDomain(td, color = ""#cccc00"") + ggDomainLabel(td) +print(gg, newpage = TRUE, vp = vp) + +gg <- ggCountHeatmap(data_s, colors = list(mid = ""white"", high = ""black"")) +gg_td <- ggDomain(td, delta = 0.08) +dx <- attr(gg_td, ""gg_params"")$dx +gg <- gg + gg_td + ggDomainLabel(td, vjust = 2.5) +print(gg, newpage = TRUE, vp = vp) + +## Subset TopDom object +fit_s <- subsetByRegion(fit, region = td, margin = 0.9999) +print(fit_s) ## a TopDom object +for (kk in seq_len(nrow(fit_s$domain))) { + gg <- gg + ggDomain(fit_s$domain[kk, ], dx = dx * (4 + kk %% 2), color = ""red"", size = 1) +} + +print(gg, newpage = TRUE, vp = vp) + + +gg <- ggCountHeatmap(data_s) +gg_td <- ggDomain(td, delta = 0.08) +dx <- attr(gg_td, ""gg_params"")$dx +gg <- gg + gg_td + ggDomainLabel(td, vjust = 2.5) +fit_s <- subsetByRegion(fit, region = td, margin = 0.9999) +for (kk in seq_len(nrow(fit_s$domain))) { + gg <- gg + ggDomain(fit_s$domain[kk, ], dx = dx * (4 + kk %% 2), color = ""blue"", size = 1) +} + +print(gg, newpage = TRUE, vp = vp) +","R" +"Nucleic acids","HenrikBengtsson/TopDom","incl/readHiC.R",".R","236","9","path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) + +## Original count data +chr <- ""chr19"" +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3) +print(data) +str(data) +","R" +"Nucleic acids","HenrikBengtsson/TopDom","tests/overlapScores.R",".R","1322","42","library(""TopDom"") + +path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) +chr <- Sys.getenv(""R_TOPDOM_TESTS_CHROMOSOME"", ""chr19"") + +## Original count data +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3) +str(data) + +## Find topological domains using TopDom method for two window sizes +tds_5 <- TopDom(data, window.size = 5L) +tds_6 <- TopDom(data, window.size = 6L) + +## Overlap scores (in both directions) +overlap_56 <- overlapScores(tds_6, reference = tds_5) +print(overlap_56) +overlap_65 <- overlapScores(tds_5, reference = tds_6) +print(overlap_65) + +if (FALSE) { + ## Find topological domains as a function of windows size + window.size <- c(5L, 6L, 8L, 10L, 12L, 14L, 16L, 18L, 20L) + tds <- lapply(window.size, FUN = function(w) TopDom(data, window.size = w)) + names(tds) <- sprintf(""window.size=%d"", window.size) + + ## Overlap scores relative to the first window.size + overlaps <- lapply(tds, FUN = overlapScores, reference = tds[[1]]) + print(overlaps) + + scores <- lapply(overlaps, FUN = function(overlaps) { + unlist(lapply(overlaps, FUN = `[[`, ""best_score""), use.names = FALSE) + }) + + avg_scores <- sapply(scores, FUN = mean, na.rm = TRUE) + print(avg_scores) + + plot(window.size, avg_scores) + lines(window.size, avg_scores, lwd = 2) +} + +","R" +"Nucleic acids","HenrikBengtsson/TopDom","tests/legacy.R",".R","1915","55","library(""TopDom"") + +path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) +chr <- Sys.getenv(""R_TOPDOM_TESTS_CHROMOSOME"", ""chr19"") + +## From Supplementary Materials of TopDom article +## Source: http://zhoulab.usc.edu/TopDom/topdom_sup.htm +message(""Loading truth ..."") +pathname <- file.path(path, sprintf(""mESC_5w_%s.nij.HindIII.comb.40kb.domain"", chr)) +truth <- read.table(pathname, sep = ""\t"", header = TRUE, + colClasses = c(""factor"", ""integer"", ""numeric"", ""integer"", + ""numeric"", ""factor"", ""numeric"")) +str(truth) + +## Original count data +message(""Loading count data ..."") +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3) +str(data) + +## Find topological domains using TopDom method +message(""TopDom() ..."") +fit <- TopDom(data, window.size = 5L) +str(fit$domain) + +message(""TopDom() v0.0.1 ..."") +fit1 <- TopDom::legacy(""0.0.1"")$TopDom(data, window.size = 5L) +str(fit1$domain) + +message(""TopDom() v0.0.2 ..."") +fit2 <- TopDom::legacy(""0.0.2"")$TopDom(data, window.size = 5L) +str(fit2$domain) + +if (requireNamespace(""diffobj"", quietly = TRUE)) { + message(""TopDom v0.0.1 versus published results ..."") + diff <- diffobj::diffPrint(fit1$domain, truth, + extra = list(row.names = FALSE)) + print(diff) + + message(""TopDom v0.0.2 versus published results ..."") + diff <- diffobj::diffPrint(fit2$domain, truth, + extra = list(row.names = FALSE)) + print(diff) + + message(""TopDom v0.0.2 versus TopDom v0.0.1 results ..."") + diff <- diffobj::diffPrint(fit2$domain, fit1$domain, + extra = list(row.names = FALSE)) + print(diff) + + message(""TopDom (package version) versus TopDom v0.0.2 results ..."") + diff <- diffobj::diffPrint(fit$domain, fit2$domain, + extra = list(row.names = FALSE)) + print(diff) +} +","R" +"Nucleic acids","HenrikBengtsson/TopDom","tests/TopDomData.R",".R","939","35","library(""TopDom"") + +path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) +chr <- Sys.getenv(""R_TOPDOM_TESTS_CHROMOSOME"", ""chr19"") + +## From Supplementary Materials of TopDom article +## Source: http://zhoulab.usc.edu/TopDom/topdom_sup.htm +message(""Loading truth ..."") +pathname <- file.path(path, sprintf(""mESC_5w_%s.nij.HindIII.comb.40kb.domain"", chr)) +truth <- read.table(pathname, sep = ""\t"", header = TRUE, + colClasses = c(""factor"", ""integer"", ""numeric"", ""integer"", + ""numeric"", ""factor"", ""numeric"")) +str(truth) + +## Original count data +message(""Loading count data ..."") +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3) +str(data) + +## print() +print(data) + +## dim() +print(dim(data)) + +## Subsetting via [() +data_s <- data[101:200] +str(data_s) +stopifnot(identical(dim(data_s), c(100L, 100L))) + +## image() +image(data_s) + +","R" +"Nucleic acids","HenrikBengtsson/TopDom","tests/TopDom.R",".R","1330","42","library(""TopDom"") + +path <- system.file(""exdata"", package = ""TopDom"", mustWork = TRUE) +chr <- Sys.getenv(""R_TOPDOM_TESTS_CHROMOSOME"", ""chr19"") + +## From Supplementary Materials of TopDom article +## Source: http://zhoulab.usc.edu/TopDom/topdom_sup.htm +message(""Loading truth ..."") +pathname <- file.path(path, sprintf(""mESC_5w_%s.nij.HindIII.comb.40kb.domain"", chr)) +truth <- read.table(pathname, sep = ""\t"", header = TRUE, + colClasses = c(""factor"", ""integer"", ""numeric"", ""integer"", + ""numeric"", ""factor"", ""numeric"")) +str(truth) + +## Original count data +message(""Loading count data ..."") +pathname <- file.path(path, sprintf(""nij.%s.gz"", chr)) +data <- readHiC(pathname, chr = chr, binSize = 40e3) +str(data) + +## Find topological domains using TopDom method +message(""TopDom() ..."") +fit <- TopDom(data, window.size = 5L) +print(fit) +str(fit$domain) + +if (requireNamespace(""diffobj"", quietly = TRUE)) { + message(""TopDom versus published results ..."") + diff <- diffobj::diffPrint(fit$domain, truth, + extra = list(row.names = FALSE)) + print(diff) +} + +## The largest domain found +td <- subset(subset(fit$domain, tag == ""domain""), size == max(size)) +stopifnot(nrow(td) == 1L) + +data_s <- subsetByRegion(data, region = td, margin = 1/2) +print(data_s) +image(data_s) + +","R" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/App.java",".java","4238","146","package genepi.haplogrep3; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; + +import genepi.haplogrep3.commands.AlignCommand; +import genepi.haplogrep3.commands.AnnotationIndexCommand; +import genepi.haplogrep3.commands.BuildTreeCommand; +import genepi.haplogrep3.commands.ClassifyCommand; +import genepi.haplogrep3.commands.CleanWorkspaceCommand; +import genepi.haplogrep3.commands.ClusterHaplogroupsCommand; +import genepi.haplogrep3.commands.DistanceCommand; +import genepi.haplogrep3.commands.InstallTreeCommand; +import genepi.haplogrep3.commands.ListTreesCommand; +import genepi.haplogrep3.commands.ServerCommand; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.JobQueue; +import genepi.io.FileUtil; +import picocli.CommandLine; +import picocli.CommandLine.Command; + +@Command(name = ""haplogrep"") +public class App implements Runnable { + + public static final String NAME = ""Haplogrep 3""; + + public static final String VERSION = ""3.2.2""; + + public static final String COPYRIGHT = ""(c) 2022-2024 Sebastian Schönherr, Hansi Weissensteiner, Lukas Forer""; + + public static final int PORT = 7000; + + public static final String CONFIG_FILENAME = ""haplogrep3.yaml""; + + private static App instance; + + private Configuration configuration = new Configuration(); + + private String configFilename = null; + + private PhylotreeRepository treeRepository; + + private JobQueue jobQueue; + + private static CommandLine commandLine; + + public static synchronized App getDefault() { + if (instance == null) { + instance = new App(); + } + return instance; + } + + public void loadConfiguration(String configFilename) { + + if (this.configFilename != null && this.configFilename.equals(configFilename)) { + return; + } + + try { + + String parent = "".""; + + File configFile = new File(configFilename); + if (!configFile.exists()) { + + File jarFile = new File( + App.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); + configFile = new File(FileUtil.path(jarFile.getParent(), CONFIG_FILENAME)); + + parent = jarFile.getParent(); + + if (!configFile.exists()) { + + System.out.println(""Configuration file '"" + configFilename + ""' not found.""); + System.exit(1); + + } + } + + configuration = Configuration.loadFromFile(configFile, parent); + treeRepository = new PhylotreeRepository(); + treeRepository.loadFromConfiguration(configuration); + + jobQueue = new JobQueue(configuration.getThreads()); + + this.configFilename = configFilename; + + } catch (IOException | URISyntaxException e) { + System.out.println(""Loading configuration from file '"" + configFilename + ""' failed.""); + System.out.println(e.getMessage()); + System.exit(1); + } + + } + + public Configuration getConfiguration() { + return configuration; + } + + public PhylotreeRepository getTreeRepository() { + return treeRepository; + } + + public JobQueue getJobQueue() { + return jobQueue; + } + + public static void main(String[] args) throws URISyntaxException { + + System.out.println(); + System.out.println(NAME + "" "" + VERSION); + if (COPYRIGHT != null && !COPYRIGHT.isEmpty()) { + System.out.println(COPYRIGHT); + } + + commandLine = new CommandLine(new App()); + commandLine.addSubcommand(""server"", new ServerCommand()); + commandLine.addSubcommand(""classify"", new ClassifyCommand()); + commandLine.addSubcommand(""align"", new AlignCommand()); + commandLine.addSubcommand(""distance"", new DistanceCommand()); + commandLine.addSubcommand(""build-tree"", new BuildTreeCommand()); + commandLine.addSubcommand(""trees"", new ListTreesCommand()); + commandLine.addSubcommand(""install-tree"", new InstallTreeCommand()); + commandLine.addSubcommand(""cluster-haplogroups"", new ClusterHaplogroupsCommand()); + commandLine.addSubcommand(""annotation-index"", new AnnotationIndexCommand()); + commandLine.addSubcommand(""clean-workspace"", new CleanWorkspaceCommand()); + commandLine.setExecutionStrategy(new CommandLine.RunLast()); + int result = commandLine.execute(args); + System.exit(result); + + } + + public static boolean isDevelopmentSystem() { + return new File(""src/main/resources"").exists(); + } + + @Override + public void run() { + commandLine.usage(System.out); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/BuildTreeCommand.java",".java","1871","81","package genepi.haplogrep3.commands; + +import genepi.haplogrep3.haplogrep.io.PhylotreeDto; +import genepi.haplogrep3.haplogrep.io.PhylotreeReader; +import genepi.haplogrep3.haplogrep.io.PhylotreeWriter; +import genepi.haplogrep3.haplogrep.io.VariantsOfConcern; +import genepi.haplogrep3.haplogrep.io.WeightsWriter; +import picocli.CommandLine.Option; + +public class BuildTreeCommand extends AbstractCommand { + + @Option(names = { ""--input"" }, description = ""input nextstrain tree.json file"", required = true) + private String input; + + @Option(names = { ""--output"" }, description = ""output haplogrep xml file"", required = true) + private String output; + + @Option(names = { ""--output-weights"" }, description = ""output haplogrep xml file"", required = true) + private String outputWeights; + + @Option(names = { ""--voc"" }, description = ""variants of concerns "", required = true) + private String inputVOC; + + /** + * @return the input + */ + public String getInput() { + return input; + } + + /** + * @param input the input to set + */ + public void setInput(String input) { + this.input = input; + } + + /** + * @return the output + */ + public String getOutput() { + return output; + } + + /** + * @param output the output to set + */ + public void setOutput(String output) { + this.output = output; + } + + /** + * @return the outputWeights + */ + public String getOutputWeights() { + return outputWeights; + } + + /** + * @param outputWeights the outputWeights to set + */ + public void setOutputWeights(String outputWeights) { + this.outputWeights = outputWeights; + } + + @Override + public Integer call() throws Exception { + + PhylotreeDto phylotree = PhylotreeReader.readFromJson(input); + + PhylotreeWriter.writeToXml(output, phylotree); + + VariantsOfConcern variantsOfConcern = new VariantsOfConcern(inputVOC); + + WeightsWriter.writeToTxt(outputWeights, phylotree, variantsOfConcern); + + return 0; + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/ListTreesCommand.java",".java","698","29","package genepi.haplogrep3.commands; + +import java.io.IOException; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import picocli.CommandLine.Command; + +@Command +public class ListTreesCommand extends AbstractCommand { + + @Override + public Integer call() throws IOException { + + PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + System.out.println(); + System.out.println(""Available trees:""); + for (Phylotree phylotree : treeRepository.getAll()) { + System.out.println("" --tree "" + phylotree.getIdWithVersion() + ""\t\t\t"" + phylotree.getName()); + } + + System.out.println(); + + return 0; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/ServerCommand.java",".java","393","24","package genepi.haplogrep3.commands; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.web.WebApp; +import picocli.CommandLine.Command; + +@Command +public class ServerCommand extends AbstractCommand { + + @Override + public Integer call() { + + App app = App.getDefault(); + int port = app.getConfiguration().getPort(); + + WebApp server = new WebApp(port); + server.start(); + + return 0; + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/InstallTreeCommand.java",".java","710","29","package genepi.haplogrep3.commands; + +import java.io.IOException; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.PhylotreeRepository; +import picocli.CommandLine.Command; +import picocli.CommandLine.Parameters; + +@Command +public class InstallTreeCommand extends AbstractCommand { + + @Parameters(paramLabel = ""TREE"", description = ""one or more trees to install"") + + private String[] trees; + + @Override + public Integer call() throws IOException { + + for (String tree : trees) { + PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + treeRepository.install(tree, App.getDefault().getConfiguration()); + System.out.println(""Tree "" + tree + "" installed.""); + } + + return 0; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/AbstractCommand.java",".java","287","15","package genepi.haplogrep3.commands; + +import java.util.concurrent.Callable; + +import genepi.haplogrep3.App; + +public abstract class AbstractCommand implements Callable { + + public AbstractCommand() { + App app = App.getDefault(); + app.loadConfiguration(App.CONFIG_FILENAME); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/AnnotationIndexCommand.java",".java","1121","51","package genepi.haplogrep3.commands; + +import java.io.File; +import java.io.IOException; + +import genepi.haplogrep3.haplogrep.io.annotation.IndexFileWriter; +import picocli.CommandLine.Option; + +public class AnnotationIndexCommand extends AbstractCommand { + + @Option(names = { ""--file"" }, description = ""file"", required = true) + private String input; + + @Option(names = { ""-s"", ""--start"" }, description = ""start column"", required = true) + private int start; + + @Option(names = { ""-S"", ""--skip"" }, description = ""skip n lines"", required = true) + private int skip; + + @Override + public Integer call() throws IOException { + + File file = new File(input); + + if (!file.exists()) { + System.out.println(""Error: Inpur file '"" + file.getAbsolutePath() + ""' not found.""); + return 1; + } + + File indexFile = new File(input + "".index""); + + IndexFileWriter writer = new IndexFileWriter(file); + writer.buildIndex(indexFile, start, skip); + + return 0; + + } + + public void setFile(String input) { + this.input = input; + } + + public void setSkip(int skip) { + this.skip = skip; + } + + public void setStart(int start) { + this.start = start; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/AlignCommand.java",".java","1570","68","package genepi.haplogrep3.commands; + +import java.io.File; +import java.util.List; +import java.util.Vector; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.AlignTask; +import picocli.CommandLine.Option; + +public class AlignCommand extends AbstractCommand { + + @Option(names = { ""--fasta"" }, description = ""input haplogroups"", required = true) + private String fasta; + + @Option(names = { ""--tree"" }, description = ""Tree Id"", required = true) + private String phylotreeId; + + @Option(names = { ""--output"" }, description = ""output aligned fasta file"", required = true) + private String output; + + @Override + public Integer call() { + + PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + File fastaFile = new File(fasta); + if (!fastaFile.exists()) { + System.out.println(""Error: File '"" + fastaFile.getAbsolutePath() + ""' not found.""); + return 1; + } + + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + System.out.println(""Error: Tree "" + phylotreeId + "" not found.""); + return 1; + } + + List files = new Vector(); + files.add(fastaFile); + + AlignTask classificationTask = new AlignTask(phylotree, files, output); + + try { + + classificationTask.run(); + + } catch (Exception e) { + System.out.println(""Error: "" + e); + return 1; + } + + if (classificationTask.isSuccess()) { + + return 0; + + } else { + + System.out.println(""Error: "" + classificationTask.getError()); + return 1; + + } + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/CleanWorkspaceCommand.java",".java","1656","66","package genepi.haplogrep3.commands; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.nio.file.Files; +import java.util.Date; + +import com.google.gson.Gson; +import com.google.gson.JsonIOException; +import com.google.gson.JsonSyntaxException; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.tasks.Job; +import genepi.io.FileUtil; +import picocli.CommandLine.Command; +import picocli.CommandLine.Help.Visibility; +import picocli.CommandLine.Option; + +@Command +public class CleanWorkspaceCommand extends AbstractCommand { + + @Option(names = { ""--dry"" }, description = ""Dry run"", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean dry = false; + + @Override + public Integer call() throws JsonSyntaxException, JsonIOException, FileNotFoundException { + + String workspace = App.getDefault().getConfiguration().getWorkspace(); + + String[] jobFiles = FileUtil.getFiles(workspace, ""*.json""); + + int expired = 0; + int notExpired = 0; + int totalJobs = 0; + + Gson gson = new Gson(); + + for (String jobFile : jobFiles) { + Job job = gson.fromJson(new FileReader(jobFile), Job.class); + Date now = new Date(); + if (now.after(job.getExpiresOn())) { + File jobPath = new File(FileUtil.path(workspace, job.getId())); + if (jobPath.exists()) { + System.out.println(""Job "" + job.getId() + "" expired.""); + if (!dry) { + FileUtil.deleteDirectory(FileUtil.path(workspace, job.getId())); + expired++; + } + } + } else { + notExpired++; + } + + totalJobs++; + + } + + System.out.println(""Deleted "" + expired + "" expired jobs. Unexpired jobs: "" + notExpired); + + return 0; + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/ClusterHaplogroupsCommand.java",".java","1281","58","package genepi.haplogrep3.commands; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.haplogrep.io.HaplogroupClustering; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import picocli.CommandLine.Option; + +public class ClusterHaplogroupsCommand extends AbstractCommand { + + @Option(names = { ""--tree"" }, description = ""tree name"", required = true) + String tree; + + @Option(names = { ""--output"" }, description = ""output haplogrpups (txt)"", required = true) + String output; + + /** + * @return the output + */ + public String getOutput() { + return output; + } + + /** + * @param output the output to set + */ + public void setOutput(String output) { + this.output = output; + } + + public String getTree() { + return tree; + } + + public void setTree(String tree) { + this.tree = tree; + } + + @Override + public Integer call() throws Exception { + + Phylotree phylotree = loadPhylotree(tree); + + new HaplogroupClustering(phylotree, phylotree.getClusters(), output); + + return 0; + + } + + public Phylotree loadPhylotree(String id) throws FileNotFoundException, IOException { + PhylotreeRepository repository = App.getDefault().getTreeRepository(); + return repository.getById(id); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/ClassifyCommand.java",".java","5151","159","package genepi.haplogrep3.commands; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.ClassificationTask; +import genepi.haplogrep3.tasks.ExportQcReportTask; +import genepi.haplogrep3.tasks.ExportHaplogroupsTask; +import genepi.haplogrep3.tasks.ExportSequenceTask; +import genepi.haplogrep3.tasks.ExportHaplogroupsTask.ExportDataFormat; +import genepi.haplogrep3.tasks.ExportSequenceTask.ExportSequenceFormat; +import picocli.CommandLine.Command; +import picocli.CommandLine.Help.Visibility; +import picocli.CommandLine.Option; + +@Command +public class ClassifyCommand extends AbstractCommand { + + @Option(names = { ""--input"", ""--in"" }, description = ""Input file (vcf, fasta, hsd)"", required = true) + protected String input; + + @Option(names = { ""--tree"" }, description = ""Tree Id"", required = true) + protected String phylotreeId; + + @Option(names = { ""--output"", ""--out"" }, description = ""Output file location"", required = true) + protected String output; + + @Option(names = { ""--distance"", ""--metric"" }, description = ""Distance"", required = false) + protected Distance distance = Distance.KULCZYNSKI; + + @Option(names = { + ""--chip"" }, description = ""VCF data from a genotype chip"", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean chip = false; + + @Option(names = { + ""--hetLevel"" }, description = ""Add heteroplasmies with a level > X from the VCF file to the profile (default: 0.9)"", required = false) + protected double hetLevel = 0.9; + + @Option(names = { ""--hits"" }, description = ""Calculate best n hits"", required = false) + protected int hits = 1; + + @Option(names = { + ""--extend-report"" }, description = ""Add flag for a extended final output"", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean extendedReport = false; + + @Option(names = { + ""--write-fasta"" }, description = ""Write results in fasta format"", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean writeFasta = false; + + @Option(names = { + ""--write-fasta-msa"" }, description = ""Write multiple sequence alignment (_MSA.fasta) "", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean writeFastaMSA = false; + + @Option(names = { + ""--write-qc"" }, description = ""Write quality control results into csvfile"", required = false, showDefaultValue = Visibility.ALWAYS) + protected boolean writeQc = false; + + @Option(names = { + ""--skip-alignment-rules"" }, description = ""Skip nomenclature fixes based on rules for FASTA import"", required = false, showDefaultValue = Visibility.ALWAYS) + boolean skipAlignmentRules = false; + + @Override + public Integer call() { + + PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + File file = new File(input); + if (!file.exists()) { + System.out.println(""Error: File '"" + file.getAbsolutePath() + ""' not found.""); + return 1; + } + + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + System.out.println(""Error: Tree "" + phylotreeId + "" not found.""); + return 1; + } + + List files = new Vector(); + files.add(file); + + ClassificationTask classificationTask = new ClassificationTask(phylotree, files, distance); + classificationTask.setChip(chip); + classificationTask.setHetLevel(hetLevel); + classificationTask.setHits(hits); + classificationTask.setSkipAlignmentRules(skipAlignmentRules); + + try { + + classificationTask.run(); + + } catch (Exception e) { + System.out.println(""Error: "" + e); + return 1; + } + + if (classificationTask.isSuccess()) { + + ExportHaplogroupsTask exportTask = new ExportHaplogroupsTask(classificationTask.getSamples(), output, + extendedReport ? ExportDataFormat.EXTENDED : ExportDataFormat.SIMPLE, phylotree.getReference()); + exportTask.setHits(hits); + try { + exportTask.run(); + } catch (IOException e) { + System.out.println(""Error: "" + e); + return 1; + } + + if (writeFasta) { + ExportSequenceTask exportSequenceTask = new ExportSequenceTask(classificationTask.getSamples(), output, + ExportSequenceFormat.FASTA, phylotree.getReference()); + try { + exportSequenceTask.run(); + } catch (IOException e) { + System.out.println(""Error: "" + e); + return 1; + } + } + + if (writeFastaMSA) { + ExportSequenceTask exportSequenceTask = new ExportSequenceTask(classificationTask.getSamples(), output, + ExportSequenceFormat.FASTA_MSA, phylotree.getReference()); + try { + exportSequenceTask.run(); + } catch (IOException e) { + System.out.println(""Error: "" + e); + return 1; + } + } + + if (writeQc) { + ExportQcReportTask exportQcReportTask = new ExportQcReportTask(classificationTask.getSamples(), output); + try { + exportQcReportTask.run(); + } catch (IOException e) { + System.out.println(""Error: "" + e); + return 1; + } + } + + return 0; + + } else { + + System.out.println(""Error: "" + classificationTask.getError()); + return 1; + + } + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/commands/DistanceCommand.java",".java","3376","116","package genepi.haplogrep3.commands; + +import java.io.File; + +import core.Haplogroup; +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.io.table.reader.CsvTableReader; +import genepi.io.table.writer.CsvTableWriter; +import picocli.CommandLine.Option; + +public class DistanceCommand extends AbstractCommand { + + @Option(names = { ""--file1"" }, description = ""input haplogroups"", required = true) + private String file1; + + @Option(names = { ""--file2"" }, description = ""input haplogroups"", required = true) + private String file2; + + @Option(names = { ""--tree"" }, description = ""Tree Id"", required = true) + private String phylotreeId; + + @Option(names = { ""--output"" }, description = ""output haplogroups including distance"", required = true) + private String output; + + @Override + public Integer call() { + + PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + File file1File = new File(file1); + if (!file1File.exists()) { + System.out.println(""Error: File1 '"" + file1File.getAbsolutePath() + ""' not found.""); + return 1; + } + + File file2File = new File(file2); + if (!file2File.exists()) { + System.out.println(""Error: File2 '"" + file2File.getAbsolutePath() + ""' not found.""); + return 1; + } + + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + System.out.println(""Error: Tree "" + phylotreeId + "" not found.""); + return 1; + } + + CsvTableReader reader1 = new CsvTableReader(file1, ','); + CsvTableReader reader2 = new CsvTableReader(file2, ','); + + CsvTableWriter writer = new CsvTableWriter(output, ';'); + + int count = 0; + + String[] columns = new String[] { ""sample"", ""clade1"", ""quality1"", ""clade2"", ""quality2"", ""distance"" }; + writer.setColumns(columns); + + while (reader1.next()) { + count++; + + if (!reader2.next()) { + System.out.println(""Error: File 2 has not the same number of liens as File 1""); + return 1; + } + + String sample1 = reader1.getString(""sample""); + String sample2 = reader2.getString(""sample""); + + if (!sample1.equals(sample2)) { + System.out.println( + ""Error: different samples in line "" + count + "": '"" + sample1 + ""' vs. '"" + sample2 + ""'""); + return 1; + } + + writer.setString(""sample"", sample1); + + String clade1 = reader1.getString(""clade""); + writer.setString(""clade1"", clade1); + String clade2 = reader2.getString(""clade""); + writer.setString(""clade2"", clade2); + + double quality1 = reader1.getDouble(""quality""); + writer.setDouble(""quality1"", quality1); + double quality2 = reader2.getDouble(""quality""); + writer.setDouble(""quality2"", quality2); + + Haplogroup groupClade1 = new Haplogroup(clade1); + Haplogroup groupClade2 = new Haplogroup(clade2); + phylotree.Phylotree haplogrepPhylotree = phylotree.getPhylotreeInstance(); + + int distance = 0; + try { + distance = haplogrepPhylotree.getDistanceBetweenHaplogroups(groupClade1, groupClade2); + } catch (Exception e) { + System.err.println(""Error: Line "" + count + "" includes at least one unknown haplogroup: "" + clade1 + + "" or "" + clade2 + "".""); + System.exit(-1); + } + writer.setInteger(""distance"", distance); + writer.next(); + + } + + reader1.close(); + reader2.close(); + writer.close(); + + System.out.println(""Done.""); + System.out.println(""File written to "" + output + "".""); + + return 0; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/PhylotreeRepository.java",".java","2817","123","package genepi.haplogrep3.model; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Vector; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.plugins.InstalledPlugin; +import genepi.haplogrep3.plugins.PluginRelease; +import genepi.haplogrep3.plugins.PluginRepository; + +public class PhylotreeRepository { + + private List trees; + + private List categories = new Vector(); + + private boolean forceUpdate; + + public static boolean FORCE_UPDATE = false; + + public PhylotreeRepository() { + trees = new Vector(); + } + + public synchronized void loadFromConfiguration(Configuration configuration) + throws FileNotFoundException, IOException { + + trees = new Vector(); + + PluginRepository repository = new PluginRepository(configuration.getRepositories(), forceUpdate, configuration.getPluginsLocation()); + + for (String id : configuration.getPhylotrees()) { + + Phylotree phylotree = null; + + if (new File(id).exists()) { + + phylotree = Phylotree.load(new File(id)); + + } else { + + PluginRelease pluginRelease = repository.findById(id); + InstalledPlugin plugin = repository.resolveRelease(pluginRelease); + phylotree = Phylotree.load(plugin.getPath()); + + } + + trees.add(phylotree); + if (!categories.contains(phylotree.getCategory())) { + categories.add(phylotree.getCategory()); + } + + } + + } + + public void install(String id, Configuration configuration) throws IOException { + + PluginRepository repository = new PluginRepository(configuration.getRepositories(), forceUpdate, configuration.getPluginsLocation()); + + Phylotree phylotree = null; + + if (new File(id).exists()) { + + phylotree = Phylotree.load(new File(id)); + + } else { + + PluginRelease pluginRelease = repository.findById(id); + InstalledPlugin plugin = repository.resolveRelease(pluginRelease); + phylotree = Phylotree.load(plugin.getPath()); + + } + + if (phylotree != null) { + configuration.getPhylotrees().add(id); + configuration.save(); + } + } + + public List getAll() { + + return Collections.unmodifiableList(trees); + + } + + public synchronized Phylotree getById(String id) { + + // TODO: use data-structure with O(1), hashmap or so. + + for (Phylotree tree : trees) { + if (tree.getIdWithVersion().equals(id)) { + return tree; + } + } + return null; + + } + + public List getCategories() { + return categories; + } + + public List getByCategory(String category) { + + // TODO: use data-structure with O(1), hashmap or so. + + List result = new Vector(); + for (Phylotree tree : trees) { + if (tree.getCategory().equals(category)) { + result.add(tree); + } + } + return result; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/Distance.java",".java","288","18","package genepi.haplogrep3.model; + +public enum Distance { + + KULCZYNSKI(""Kulczynski (Default)""), HAMMING(""Hamming""), JACCARD(""Jaccard""), KIMURA(""Kimura""); + + private String label; + + private Distance(String label) { + this.label = label; + } + + public String getLabel() { + return label; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/AnnotatedSample.java",".java","5449","255","package genepi.haplogrep3.model; + +import java.util.List; +import java.util.Vector; + +import core.TestSample; +import genepi.haplogrep3.util.PolymorphismHelper; +import search.SearchResultDetailed; +import search.ranking.results.RankedResult; + +public class AnnotatedSample { + + private String sample; + + private String clade; + + private double quality; + + private int ns = 0; + + private int mixCount = 0; + + private int coverage = 0; + + private int expected = 0; + + private int found = 0; + + private String[] ranges = new String[0]; + + private String[] otherClades = new String[0]; + + private double[] otherQualities = new double[0]; + + private List remainingMutations = new Vector(); + + private List expectedMutations = new Vector(); + + private List annotatedPolymorphisms = new Vector(); + + private transient TestSample testSample; + + private List errors = new Vector(); + + private List warnings = new Vector(); + + private List infos = new Vector(); + + public AnnotatedSample(TestSample testSample) { + + this.testSample = testSample; + sample = testSample.getSampleID(); + RankedResult topResult = testSample.getTopResult(); + SearchResultDetailed detailedResult = topResult.getSearchResult().getDetailedResult(); + + clade = topResult.getHaplogroup().toString(); + clade = clade.split(""_"")[0]; + quality = topResult.getDistance(); + ns = PolymorphismHelper.getNCount(detailedResult.getRemainingPolysInSample()); + mixCount = PolymorphismHelper.getMixCount(detailedResult.getRemainingPolysInSample()); + coverage = PolymorphismHelper.getRangeLength(testSample.getSample().getSampleRanges().toString()); + + String[] rangesWithSpaces = testSample.getSample().getSampleRanges().toString().split("";""); + ranges = new String[rangesWithSpaces.length]; + for (int i = 0; i < ranges.length; i++) { + ranges[i] = rangesWithSpaces[i].trim(); + } + + int hits = testSample.getResults().size(); + if (hits > 1) { + otherClades = new String[hits - 1]; + otherQualities = new double[hits - 1]; + for (int i = 0; i < hits - 1; i++) { + RankedResult result = testSample.getResults().get(i + 1); + otherClades[i] = result.getHaplogroup().toString(); + otherQualities[i] = result.getDistance(); + } + } + + expected = detailedResult.getExpectedPolys().size(); + found = detailedResult.getFoundPolys().size(); + + } + + public String getSample() { + return sample; + } + + public void setSample(String sample) { + this.sample = sample; + } + + public String getClade() { + return clade; + } + + public void setClade(String clade) { + this.clade = clade; + } + + public double getQuality() { + return quality; + } + + public void setQuality(double quality) { + this.quality = quality; + } + + public int getNs() { + return ns; + } + + public void setNs(int ns) { + this.ns = ns; + } + + public int getMixCount() { + return mixCount; + } + + public void setMixCount(int mixCount) { + this.mixCount = mixCount; + } + + public int getCoverage() { + return coverage; + } + + public void setCoverage(int coverage) { + this.coverage = coverage; + } + + public void setOtherClades(String[] otherClades) { + this.otherClades = otherClades; + } + + public String[] getOtherClades() { + return otherClades; + } + + public void setOtherQualities(double[] otherQualities) { + this.otherQualities = otherQualities; + } + + public double[] getOtherQualities() { + return otherQualities; + } + + public String[] getRanges() { + return ranges; + } + + public void setRanges(String[] ranges) { + this.ranges = ranges; + } + + public void setAnnotatedPolymorphisms(List annotatedPolymorphisms) { + this.annotatedPolymorphisms = annotatedPolymorphisms; + } + + public List getAnnotatedPolymorphisms() { + return annotatedPolymorphisms; + } + + public void setExpected(int expected) { + this.expected = expected; + } + + public int getExpected() { + return expected; + } + + public void setFound(int found) { + this.found = found; + } + + public int getFound() { + return found; + } + + public void setExpectedMutations(List expectedMutations) { + this.expectedMutations = expectedMutations; + } + + public List getExpectedMutations() { + return expectedMutations; + } + + public TestSample getTestSample() { + return testSample; + } + + @Override + public String toString() { + return sample; + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } + + public boolean hasWarnings() { + return !warnings.isEmpty(); + } + + public boolean hasInfos() { + return !infos.isEmpty(); + } + + public void addError(String error) { + errors.add(error); + } + + public void addWarning(String warning) { + warnings.add(warning); + } + + public void addInfo(String info) { + infos.add(info); + } + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } + + public List getWarnings() { + return warnings; + } + + public void setWarnings(List warnings) { + this.warnings = warnings; + } + + public List getInfos() { + return infos; + } + + public void setInfos(List infos) { + this.infos = infos; + } + + public void setRemainingMutations(List remainingMutations) { + this.remainingMutations = remainingMutations; + } + + public List getRemainingMutations() { + return remainingMutations; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/HaplogroupStatistics.java",".java","3248","137","package genepi.haplogrep3.model; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +public class HaplogroupStatistics { + + private List> groups = new Vector<>(); + + public HaplogroupStatistics() { + + } + + public HaplogroupStatistics(List samples, Phylotree phylotree) { + + if (phylotree.hasClusters()) { + HashMap assignedClusters = assignClusters(samples, phylotree); + groups.add(assignedClusters); + } + + HashMap result = countHaplogroups(samples); + groups.add(result); + + } + + public void setGroups(List> clusters) { + this.groups = clusters; + } + + public List> getGroups() { + return groups; + } + + protected HashMap countHaplogroups(List samples) { + + List clades = new Vector(); + List values = new Vector(); + + for (AnnotatedSample sample : samples) { + String clade = sample.getClade(); + + int index = clades.indexOf(clade); + if (index == -1) { + clades.add(clade); + values.add(1); + } else { + int count = values.get(index); + values.set(index, count + 1); + } + } + + HashMap object = new HashMap(); + object.put(""name"", ""Haplogroup""); + object.put(""clades"", clades); + object.put(""values"", values); + + return object; + + } + + protected HashMap assignClusters(List samples, Phylotree phylotree) { + + List clusters = phylotree.getClusters(); + + Map frequencies = new HashMap<>(); + + for (AnnotatedSample sample : samples) { + + String clade = sample.getClade(); + String label = ""unknown""; + try { + String cluster = phylotree.getNearestCluster(clusters, clade); + if (cluster != null) { + label = cluster; + } + } catch (Exception e) { + e.printStackTrace(); + } + + ClusterCount clusterCount = frequencies.get(label); + + if (clusterCount == null) { + Cluster cluster = phylotree.getClusterByLabel(label); + clusterCount = new ClusterCount(); + clusterCount.label = label; + clusterCount.value = 1; + clusterCount.color = cluster.getColor(); + frequencies.put(label, clusterCount); + + } else { + clusterCount.value++; + } + } + + List sortedFrequencies = new Vector(frequencies.values()); + Collections.sort(sortedFrequencies, new Comparator() { + @Override + public int compare(ClusterCount o1, ClusterCount o2) { + return -Integer.compare(o1.value, o2.value); + } + }); + + List clades = new Vector(); + List values = new Vector(); + List colors = new Vector(); + for (ClusterCount clusterCount: sortedFrequencies) { + clades.add(clusterCount.label); + values.add(clusterCount.value); + colors.add(clusterCount.color); + } + + HashMap object = new HashMap(); + object.put(""name"", ""Clusters""); + object.put(""clades"", clades); + object.put(""values"", values); + object.put(""colors"", colors); + + return object; + + } + + class ClusterCount { + + String label; + + String color; + + int value; + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/Cluster.java",".java","1241","75","package genepi.haplogrep3.model; + +import java.util.HashMap; +import java.util.Map; + +public class Cluster implements Comparable { + + private String label; + + private String[] nodes = new String[0]; + + private String color; + + private Map frequencies = new HashMap(); + + public Cluster() { + + } + + public Cluster(String label, String[] nodes, String color) { + + this.label = label; + this.nodes = nodes; + this.color = color; + + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String[] getNodes() { + + if (nodes == null || nodes.length == 0) { + return new String[] { label }; + } + + return nodes; + } + + public void setNodes(String[] nodes) { + this.nodes = nodes; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public boolean hasFrequencies() { + return frequencies != null & frequencies.size() > 0; + } + + public void setFrequencies(Map frequencies) { + this.frequencies = frequencies; + } + + public Map getFrequencies() { + return frequencies; + } + + @Override + public int compareTo(Cluster o) { + return label.compareTo(o.label); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/AnnotatedPolymorphism.java",".java","1491","96","package genepi.haplogrep3.model; + +import java.util.Map; + +import core.Polymorphism; + +public class AnnotatedPolymorphism { + + private String aac = """"; + + private String nuc = """"; + + private boolean found = false; + + private String type = """"; + + private Map annotations = null; + + private int position; + + private String ref; + + private String alt; + + public AnnotatedPolymorphism(Polymorphism polymorphism) { + position = polymorphism.getPosition(); + ref = polymorphism.getReferenceBase().getMutation().toString(); + alt = polymorphism.getMutation().toString(); + } + + public String getAac() { + return aac; + } + + public void setAac(String aac) { + this.aac = aac; + } + + public String getNuc() { + return nuc; + } + + public void setNuc(String nuc) { + this.nuc = nuc; + } + + public boolean isFound() { + return found; + } + + public void setFound(boolean found) { + this.found = found; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Map getAnnotations() { + return annotations; + } + + public void setAnnotations(Map annotations) { + this.annotations = annotations; + } + + public void setAlt(String alt) { + this.alt = alt; + } + + public String getAlt() { + return alt; + } + + public void setPosition(int position) { + this.position = position; + } + + public int getPosition() { + return position; + } + + public void setRef(String ref) { + this.ref = ref; + } + + public String getRef() { + return ref; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/Phylotree.java",".java","13286","540","package genepi.haplogrep3.model; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import com.esotericsoftware.yamlbeans.YamlReader; + +import core.Haplogroup; +import core.Polymorphism; +import core.Reference; +import core.SampleFile; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationColumn; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationFileReader; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationSettings; +import genepi.haplogrep3.util.PolymorphismHelper; +import genepi.io.FileUtil; +import phylotree.PhyloTreeNode; +import phylotree.PhylotreeManager; +import search.ranking.HammingRanking; +import search.ranking.JaccardRanking; +import search.ranking.Kimura2PRanking; +import search.ranking.KulczynskiRanking; +import search.ranking.RankingMethod; + +public class Phylotree { + + private String id; + + private String version = """"; + + private String name; + + private String category = ""Other""; + + private String tree; + + private String weights; + + private String fasta; + + private Reference reference; + + private String aacTable; + + private String gff; + + private String alignmentRules; + + private String description = ""Please specify a description""; + + private String lastUpdate = ""unknown""; + + private String url = ""no_url_provided""; + + private String[] source = new String[] { ""Please specify the source of the data"" }; + + private boolean deprecated = false; + + private String[] genes = new String[0]; + + private HashSet hotspots = new HashSet<>(); + + private String template; + + private List clusters = new Vector(); + + private List annotations = new Vector(); + + private List populations = new Vector(); + + public Phylotree() { + + } + + public Phylotree(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getTree() { + return tree; + } + + public void setTree(String tree) { + this.tree = tree; + } + + public String getWeights() { + return weights; + } + + public void setWeights(String weights) { + this.weights = weights; + } + + public Reference getReference() { + return reference; + } + + public void setReference(Reference reference) { + this.reference = reference; + } + + public String getFasta() { + return fasta; + } + + public void setFasta(String fasta) { + this.fasta = fasta; + } + + public String getAacTable() { + return aacTable; + } + + public void setAacTable(String aacTable) { + this.aacTable = aacTable; + } + + public String getGff() { + return gff; + } + + public void setGff(String gff) { + this.gff = gff; + } + + public String getAlignmentRules() { + return alignmentRules; + } + + public void setAlignmentRules(String alignmentRules) { + this.alignmentRules = alignmentRules; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getLastUpdate() { + return lastUpdate; + } + + public void setLastUpdate(String lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isDeprecated() { + return deprecated; + } + + public void setDeprecated(boolean deprecated) { + this.deprecated = deprecated; + } + + public String[] getSource() { + return source; + } + + public void setSource(String[] source) { + this.source = source; + } + + public String[] getGenes() { + return genes; + } + + public void setGenes(String[] genes) { + this.genes = genes; + } + + public HashSet getHotspots() { + return hotspots; + } + + public void setHotspots(HashSet hotspots) { + this.hotspots = hotspots; + } + + public List getAnnotations() { + return annotations; + } + + public void setAnnotations(List annotations) { + this.annotations = annotations; + } + + public phylotree.Phylotree getPhylotreeInstance() { + return PhylotreeManager.getInstance().getPhylotree(getTree(), getWeights(), getReference(), getHotspots()); + } + + public String getTemplate() { + return template; + } + + public void setTemplate(String template) { + this.template = template; + } + + public void setClusters(List clusters) { + this.clusters = clusters; + } + + public List getClusters() { + return clusters; + } + + public boolean hasClusters() { + return clusters != null && !clusters.isEmpty(); + } + + public void classify(SampleFile sampleFile, Distance distance, int hits, boolean skipAlignmentRules) + throws FileNotFoundException { + + RankingMethod rankingMethod = null; + + switch (distance) { + case HAMMING: + rankingMethod = new HammingRanking(hits); + break; + case JACCARD: + rankingMethod = new JaccardRanking(hits); + break; + case KIMURA: + rankingMethod = new Kimura2PRanking(hits); + break; + case KULCZYNSKI: + rankingMethod = new KulczynskiRanking(hits); + break; + default: + break; + } + + phylotree.Phylotree haplogrepPhylotree = getPhylotreeInstance(); + + sampleFile.updateClassificationResults(haplogrepPhylotree, rankingMethod); + + sampleFile.runQualityChecks(haplogrepPhylotree); + + } + + public Haplogroup getHaplogroup(String name) { + phylotree.Phylotree haplogrepPhylotree = getPhylotreeInstance(); + List nodeList = haplogrepPhylotree.getPhyloTree().getSubHaplogroups(); + return findHaplogroup(name, nodeList); + } + + protected Haplogroup findHaplogroup(String name, List nodeList) { + for (int i = 0; i < nodeList.size(); i++) { + Haplogroup haplogroup = nodeList.get(i).getHaplogroup(); + if (haplogroup.toString().equalsIgnoreCase(name)) { + return haplogroup; + } + Haplogroup subHaplogroup = findHaplogroup(name, nodeList.get(i).getSubHaplogroups()); + if (subHaplogroup != null) { + return subHaplogroup; + } + } + return null; + } + + public PhyloTreeNode getHaplogroupTreeNode(String name) { + phylotree.Phylotree haplogrepPhylotree = getPhylotreeInstance(); + List nodeList = haplogrepPhylotree.getPhyloTree().getSubHaplogroups(); + return findHaplogroupTreeNode(name, nodeList); + } + + protected PhyloTreeNode findHaplogroupTreeNode(String name, List nodeList) { + for (int i = 0; i < nodeList.size(); i++) { + Haplogroup haplogroup = nodeList.get(i).getHaplogroup(); + if (haplogroup.toString().equalsIgnoreCase(name)) { + return nodeList.get(i); + } + PhyloTreeNode subHaplogroup = findHaplogroupTreeNode(name, nodeList.get(i).getSubHaplogroups()); + if (subHaplogroup != null) { + return subHaplogroup; + } + } + return null; + } + + protected void updateParent(String parent) { + // TODO: check required params + tree = FileUtil.path(parent, tree); + weights = FileUtil.path(parent, weights); + aacTable = FileUtil.path(parent, aacTable); + gff = FileUtil.path(parent, gff); + fasta = FileUtil.path(parent, fasta); + if (alignmentRules != null) { + alignmentRules = FileUtil.path(parent, alignmentRules); + } + if (template != null) { + template = FileUtil.path(parent, template); + } + for (AnnotationSettings annotation : annotations) { + annotation.setFilename(FileUtil.path(parent, annotation.getFilename())); + } + } + + public static Phylotree load(File file) throws IOException { + + YamlReader reader = new YamlReader(new FileReader(file)); + reader.getConfig().setPropertyElementType(Phylotree.class, ""annotations"", AnnotationSettings.class); + reader.getConfig().setPropertyElementType(Phylotree.class, ""clusters"", Cluster.class); + reader.getConfig().setPropertyElementType(Phylotree.class, ""populations"", Population.class); + reader.getConfig().setPropertyElementType(AnnotationSettings.class, ""properties"", AnnotationColumn.class); + + Phylotree phylotree = reader.read(Phylotree.class); + phylotree.updateParent(file.getAbsoluteFile().getParent()); + + Reference reference = new Reference(phylotree.getFasta()); + phylotree.setReference(reference); + + if (phylotree.hasClusters()) { + Collections.sort(phylotree.getClusters()); + } + + return phylotree; + + } + + public List getHaplogroups() { + Vector haplogroups = new Vector(); + + phylotree.Phylotree haplogrepPhylotree = getPhylotreeInstance(); + List nodeList = haplogrepPhylotree.getPhyloTree().getSubHaplogroups(); + addAllHaplogroups(haplogroups, nodeList); + return haplogroups; + + } + + protected void addAllHaplogroups(Vector haplogroups, List nodeList) { + for (int i = 0; i < nodeList.size(); i++) { + Haplogroup haplogroup = nodeList.get(i).getHaplogroup(); + haplogroups.add(haplogroup); + addAllHaplogroups(haplogroups, nodeList.get(i).getSubHaplogroups()); + } + } + + public List getPolymorphisms(Haplogroup haplogroup) { + Vector polymorphisms = new Vector(); + PhyloTreeNode node = getHaplogroupTreeNode(haplogroup.toString()); + addAllPolymorphisms(polymorphisms, node); + PolymorphismHelper.sortByPosition(polymorphisms); + return polymorphisms; + + } + + protected void addAllPolymorphisms(Vector polymorphisms, PhyloTreeNode node) { + for (Polymorphism polymorphism : node.getExpectedPolys()) { + polymorphisms.add(polymorphism); + } + if (node.getParent() != null) { + addAllPolymorphisms(polymorphisms, node.getParent()); + } + } + + public String getIdWithVersion() { + if (version == null || version.trim().isEmpty()) { + return id; + } else { + return id + ""@"" + version; + } + } + + public void annotate(List polymorphisms) throws IOException { + for (AnnotationSettings annotation : annotations) { + + AnnotationFileReader reader = new AnnotationFileReader(annotation.getFilename(), annotation.getProperties(), + true, annotation.getRefAllele(), annotation.getAltAllele()); + + for (AnnotatedPolymorphism polymorphism : polymorphisms) { + Map result = reader.query(annotation.getChr(), polymorphism.getPosition(), + polymorphism.getRef(), polymorphism.getAlt()); + if (result != null) { + if (polymorphism.getAnnotations() != null) { + polymorphism.getAnnotations().putAll(result); + } else { + polymorphism.setAnnotations(result); + } + } else { + if (polymorphism.getAnnotations() == null) { + polymorphism.setAnnotations(new HashMap<>()); + } + } + + } + + reader.close(); + } + + } + + public String getNearestCluster(List clusters, String haplogroup) throws Exception { + + phylotree.Phylotree haplogrepPhylotree = getPhylotreeInstance(); + Haplogroup haplogroupObject = new Haplogroup(haplogroup); + + int distanceTmp = -1; + String topLevelTmp = null; + + for (Cluster cluster : clusters) { + + // top level haplogroup + String label = cluster.getLabel(); + + for (String node : cluster.getNodes()) { + + boolean hit = new Haplogroup(node).isSuperHaplogroup(haplogrepPhylotree, haplogroupObject); + + if (hit) { + new Haplogroup(label); + int distance = haplogrepPhylotree.getDistanceBetweenHaplogroups(new Haplogroup(node), + haplogroupObject); + + if (distanceTmp == -1 || distance <= distanceTmp) { + + topLevelTmp = label.toString(); + distanceTmp = distance; + + } + } + } + } + + if (topLevelTmp != null) { + return topLevelTmp; + } else { + return null; + } + } + + public Cluster getClusterByLabel(String label) { + for (Cluster cluster : clusters) { + if (cluster.getLabel().equals(label)) { + return cluster; + } + } + return null; + } + + public Set getHaplogroupsByCluster(Cluster cluster) throws Exception { + Set haplogroups = new HashSet(); + for (String label : cluster.getNodes()) { + PhyloTreeNode node = getHaplogroupTreeNode(label); + if (node == null) { + return new HashSet(); + } + addChilds(cluster, node, haplogroups, 1); + } + return haplogroups; + } + + private void addChilds(Cluster cluster, PhyloTreeNode root, Set haplogroups, int level) throws Exception { + + List childs = root.getSubHaplogroups(); + + for (PhyloTreeNode child : childs) { + String haplogroup = child.getHaplogroup().toString(); + String nearestCluster = getNearestCluster(clusters, haplogroup); + if (nearestCluster != null && nearestCluster.equals(cluster.getLabel())) { + haplogroups.add(child.getHaplogroup().toString()); + addChilds(cluster, child, haplogroups, level++); + } + } + + } + + public List getPopulations() { + return populations; + } + + public void setPopulations(List populations) { + this.populations = populations; + } + + public Population getPopulationById(String id) { + for (Population population : populations) { + if (population.getId().equalsIgnoreCase(id)) { + return population; + } + } + return null; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/Population.java",".java","450","36","package genepi.haplogrep3.model; + +public class Population { + + private String id; + + private String label; + + private String color; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/JobStatus.java",".java","98","6","package genepi.haplogrep3.model; + +public enum JobStatus { + SUBMITTED, RUNNING, SUCCEDED, FAILED +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/model/Dataset.java",".java","1042","72","package genepi.haplogrep3.model; + +import genepi.io.FileUtil; + +public class Dataset { + + private String id; + + private String name; + + private String file; + + private String tree; + + private boolean chip = false; + + private boolean additionalOutput = false; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFile() { + return file; + } + + public void setFile(String file) { + this.file = file; + } + + public String getTree() { + return tree; + } + + public void setTree(String tree) { + this.tree = tree; + } + + public boolean isChip() { + return chip; + } + + public void setChip(boolean chip) { + this.chip = chip; + } + + public boolean isAdditionalOutput() { + return additionalOutput; + } + + public void setAdditionalOutput(boolean additionalOutput) { + this.additionalOutput = additionalOutput; + } + + public void updateParent(String parent) { + this.file = FileUtil.path(parent, file); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/JobQueue.java",".java","1134","59","package genepi.haplogrep3.tasks; + +import java.util.List; +import java.util.Vector; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class JobQueue implements Runnable { + + private List queue = new Vector(); + + private ThreadPoolExecutor scheduler; + + private static final Log log = LogFactory.getLog(JobQueue.class); + + public JobQueue(int threads) { + scheduler = new ThreadPoolExecutor(threads, threads, 10, TimeUnit.SECONDS, new LinkedBlockingQueue()); + } + + public void submit(Job job) { + + synchronized (queue) { + + Future l = scheduler.submit(job); + queue.add(job); + log.info(""Submit task "" + job.getId() + ""...""); + + } + + } + + @Override + public void run() { + + while (true) { + try { + + Thread.sleep(5000); + + } catch (Exception e) { + + log.warn(""Concurrency Exception!! ""); + e.printStackTrace(); + + } + + } + } + + public int getActiveCount() { + return scheduler.getActiveCount(); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/AnnotationTask.java",".java","5070","165","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import core.Polymorphism; +import core.SampleFile; +import core.TestSample; +import genepi.annotate.util.MapLocusGFF3; +import genepi.annotate.util.SequenceUtil; +import genepi.haplogrep3.model.AnnotatedPolymorphism; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.util.PolymorphismHelper; +import genepi.haplogrep3.util.TestSampleHelper; +import qualityAssurance.issues.QualityIssue; +import search.SearchResultDetailed; + +public class AnnotationTask { + + private SampleFile sampleFile; + + private Phylotree phylotree; + + private List samples = new Vector(); + + private Map codonTable; + + private MapLocusGFF3 maplocus; + + private String refSequence; + + public AnnotationTask(SampleFile sampleFile, Phylotree phylotree) { + this.sampleFile = sampleFile; + this.phylotree = phylotree; + } + + public void loadFiles() throws IOException { + codonTable = SequenceUtil.loadCodonTableLong(phylotree.getAacTable()); + maplocus = new MapLocusGFF3(phylotree.getGff()); + refSequence = phylotree.getReference().getSequence(); + } + + public void run() throws IOException { + + loadFiles(); + + // samples from haplogrep + ArrayList samplesH = sampleFile.getTestSamples(); + TestSampleHelper.sortBySampleId(samplesH); + + for (int i = 0; i < samplesH.size(); i++) { + + TestSample sample = samplesH.get(i); + SearchResultDetailed detailedResults = sample.getTopResult().getSearchResult().getDetailedResult(); + + AnnotatedSample annotatedSample = new AnnotatedSample(sample); + annotatedSample.setAnnotatedPolymorphisms( + getAminoAcidsFromPolys(sample.getSample().getPolymorphisms(), detailedResults)); + annotatedSample + .setExpectedMutations(getExpectedMutations(sample.getSample().getPolymorphisms(), detailedResults)); + + annotatedSample.setRemainingMutations(getRemainingPolymorphisms(detailedResults)); + + samples.add(annotatedSample); + + ArrayList issues = sampleFile.getQualityAssistent().getIssues(sample); + parseIssues(annotatedSample, issues); + } + } + + public List getAnnotatedSamples() { + return samples; + } + + public List getAminoAcidsFromPolys(List polymorphisms, + SearchResultDetailed detailedResults) { + + List annotatedPolymorphisms = new Vector(); + PolymorphismHelper.sortByPosition(polymorphisms); + + for (int i = 0; i < polymorphisms.size(); i++) { + + Polymorphism polymorphism = polymorphisms.get(i); + + AnnotatedPolymorphism annotatedPolymorphism = new AnnotatedPolymorphism(polymorphism); + annotatedPolymorphism.setNuc(PolymorphismHelper.getLabel(polymorphism)); + annotatedPolymorphisms.add(annotatedPolymorphism); + + } + + return annotatedPolymorphisms; + + } + + protected List getExpectedMutations(List polymorphisms, + SearchResultDetailed detailedResults) { + + List expectedMutations = new Vector(); + PolymorphismHelper.sortByPosition(polymorphisms); + + for (int i = 0; i < detailedResults.getExpectedPolys().size(); i++) { + + Polymorphism polymorphism = detailedResults.getExpectedPolys().get(i); + + AnnotatedPolymorphism annotatedPolymorphism = new AnnotatedPolymorphism(polymorphism); + annotatedPolymorphism.setNuc(PolymorphismHelper.getLabel(polymorphism)); + annotatedPolymorphism.setFound(detailedResults.getFoundPolys().contains(polymorphism)); + expectedMutations.add(annotatedPolymorphism); + } + + return expectedMutations; + + } + + protected List getRemainingPolymorphisms(SearchResultDetailed detailedResults) { + + List expectedMutations = new Vector(); + PolymorphismHelper.sortByPosition(detailedResults.getRemainingPolysInSample()); + + for (int i = 0; i < detailedResults.getRemainingPolysInSample().size(); i++) { + + Polymorphism polymorphism = detailedResults.getRemainingPolysInSample().get(i); + + AnnotatedPolymorphism annotatedPolymorphism = new AnnotatedPolymorphism(polymorphism); + annotatedPolymorphism.setNuc(PolymorphismHelper.getLabel(polymorphism)); + annotatedPolymorphism.setType(PolymorphismHelper.getType(polymorphism, phylotree)); + expectedMutations.add(annotatedPolymorphism); + + } + + return expectedMutations; + + } + + public void parseIssues(AnnotatedSample sample, ArrayList issues) { + if (issues == null) { + return; + } + + for (QualityIssue issue : issues) { + switch (issue.getPriority()) { + case 0: + sample.addWarning(getIssueMessage(issue)); + break; + case 1: + sample.addError(getIssueMessage(issue)); + break; + default: + sample.addInfo(getIssueMessage(issue)); + break; + } + } + + } + + public String getIssueMessage(QualityIssue issue) { + return issue.getDescription() + "" ("" + issue.getIssueType() + "")""; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ExportSequenceTask.java",".java","1116","52","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import core.Reference; +import core.TestSample; +import genepi.haplogrep3.model.AnnotatedSample; +import util.ExportUtils; + +public class ExportSequenceTask { + + private String filename; + + private List samples; + + private Reference reference; + + private ExportSequenceFormat format; + + public static enum ExportSequenceFormat { + FASTA, FASTA_MSA + } + + public ExportSequenceTask(List samples, String filename, ExportSequenceFormat format, Reference reference) { + this.samples = samples; + this.filename = filename; + this.reference = reference; + this.format = format; + } + + public void run() throws IOException { + + List testSamples = new Vector(); + for (AnnotatedSample sample : samples) { + testSamples.add(sample.getTestSample()); + } + + switch (format) { + case FASTA: + ExportUtils.generateFasta(testSamples, reference, filename); + break; + case FASTA_MSA: + ExportUtils.generateFastaMSA(testSamples, reference, filename); + break; + } + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/CreateZipFileTask.java",".java","1123","49","package genepi.haplogrep3.tasks; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class CreateZipFileTask { + + private String filename; + + private String[] files; + + public CreateZipFileTask(String[] files, String filename) { + this.filename = filename; + this.files = files; + } + + public void run() throws IOException { + createZipArchive(files, filename); + } + + protected void createZipArchive(String[] files, String filename) throws IOException { + + final FileOutputStream fos = new FileOutputStream(filename); + ZipOutputStream zipOut = new ZipOutputStream(fos); + + for (String srcFile : files) { + File fileToZip = new File(srcFile); + FileInputStream fis = new FileInputStream(fileToZip); + ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zipOut.putNextEntry(zipEntry); + + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + fis.close(); + } + + zipOut.close(); + fos.close(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ExportHaplogroupsTask.java",".java","1184","54","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import core.Reference; +import core.TestSample; +import genepi.haplogrep3.model.AnnotatedSample; +import util.ExportUtils; + +public class ExportHaplogroupsTask { + + private String filename; + + private List samples; + + private Reference reference; + + private int hits = 1; + + public static enum ExportDataFormat { + SIMPLE, EXTENDED + } + + private ExportDataFormat format = ExportDataFormat.SIMPLE; + + public ExportHaplogroupsTask(List samples, String filename, ExportDataFormat format, + Reference reference) { + this.samples = samples; + this.filename = filename; + this.format = format; + this.reference = reference; + } + + public void setHits(int hits) { + this.hits = hits; + } + + public void run() throws IOException { + + List testSamples = new Vector(); + for (AnnotatedSample sample : samples) { + testSamples.add(sample.getTestSample()); + } + + ExportUtils.createReport(testSamples, reference, filename, format == ExportDataFormat.EXTENDED, hits); + + System.out.println(""Written haplogroups to file "" + filename); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/AlignTask.java",".java","1546","71","package genepi.haplogrep3.tasks; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import core.SampleFile; +import core.TestSample; +import genepi.haplogrep3.model.Phylotree; +import importer.FastaImporter; +import util.ExportUtils; + +public class AlignTask { + + private boolean success = true; + + private String error = null; + + private Phylotree phylotree; + + private List files; + + private String filename; + + public AlignTask(Phylotree phylotree, List files, String filename) { + this.phylotree = phylotree; + this.files = files; + this.filename = filename; + } + + public void run() throws Exception { + + if (files == null || files.isEmpty()) { + setError(""No files uploaded.""); + return; + } + + ArrayList lines = new ArrayList(); + FastaImporter importer = new FastaImporter(); + for (File file : files) { + lines.addAll(importer.load(file, phylotree.getReference())); + } + + SampleFile sampleFile = new SampleFile(lines, phylotree.getReference()); + ArrayList samplesH = sampleFile.getTestSamples(); + ExportUtils.generateFasta(samplesH, phylotree.getReference(), filename); + + // ExportUtils creates a different filename --> rename it to filename user + // provided. + String newFilename = filename + ""_haplogrep2.fasta""; + new File(newFilename).renameTo(new File(filename)); + + success = true; + + } + + public boolean isSuccess() { + return success; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + success = false; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ExportHtmlReportTask.java",".java","1514","53","package genepi.haplogrep3.tasks; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.util.BasisTemplateFileRenderer; +import genepi.haplogrep3.web.util.Page; +import genepi.io.FileUtil; + +public class ExportHtmlReportTask { + + private Configuration configuration = App.getDefault().getConfiguration(); + + private String workspace = configuration.getWorkspace(); + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private String filename; + + private Job job; + + public ExportHtmlReportTask(Job job, String filename) { + this.job = job; + this.filename = filename; + } + + public void run() throws Exception { + + Phylotree phylotree = treeRepository.getById(job.getPhylotree()); + + String template = ""web/jobs/show."" + job.getStatus().name().toLowerCase() + "".view.html""; + + Page page = new Page(); + page.put(""job"", job); + page.put(""genes"", phylotree.getGenes()); + + String clades = FileUtil.path(workspace, job.getId(), ""clades.json""); + page.put(""clades"", FileUtil.readFileAsString(clades)); + page.put(""selfContained"", true); + page.put(""phylotree"", phylotree); + + BasisTemplateFileRenderer renderer = new BasisTemplateFileRenderer(); + String content = renderer.render(template, page); + + FileUtil.writeStringBufferToFile(filename, new StringBuffer(content)); + + System.out.println(""Written html report to file "" + filename); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ExportQcReportTask.java",".java","3225","104","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.List; + +import org.apache.commons.io.FilenameUtils; + +import genepi.haplogrep3.model.AnnotatedPolymorphism; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.io.table.writer.CsvTableWriter; + +public class ExportQcReportTask { + + private static final String INFO_TYPE = ""info""; + + private static final String WARNING_TYPE = ""warning""; + + private static final String ERROR_TYPE = ""error""; + + private static final String MESSAGE = ""Message""; + + private static final String HAPLOGROUP = ""Haplogroup""; + + private static final String MISSING_POLY = ""Missing Mutations""; + + private static final String ADDITIONAL_POLY = ""Global Private Mutations""; + + private static final String TYPE = ""Type""; + + private static final String SAMPLE_ID = ""SampleID""; + + private String filename; + + private List samples; + + public ExportQcReportTask(List samples, String filename) { + this.samples = samples; + this.filename = FilenameUtils.removeExtension(filename); + this.filename = this.filename + "".qc.txt""; + } + + public void run() throws IOException { + + CsvTableWriter writer = new CsvTableWriter(filename, '\t', true); + writer.setColumns(new String[] { SAMPLE_ID, HAPLOGROUP, TYPE, MESSAGE, MISSING_POLY, ADDITIONAL_POLY }); + for (AnnotatedSample sample : samples) { + for (String error : sample.getErrors()) { + writer.setString(SAMPLE_ID, sample.getSample()); + writer.setString(HAPLOGROUP, sample.getClade()); + writer.setString(TYPE, ERROR_TYPE); + writer.setString(MESSAGE, error); + writer.setString(MISSING_POLY, getMissingPolymorphisms(sample)); + writer.setString(ADDITIONAL_POLY, getAdditionalPolymorphisms(sample)); + writer.next(); + } + + for (String warning : sample.getWarnings()) { + writer.setString(SAMPLE_ID, sample.getSample()); + writer.setString(HAPLOGROUP, sample.getClade()); + writer.setString(TYPE, WARNING_TYPE); + writer.setString(MESSAGE, warning); + writer.setString(MISSING_POLY, getMissingPolymorphisms(sample)); + writer.setString(ADDITIONAL_POLY, getAdditionalPolymorphisms(sample)); + writer.next(); + } + + for (String info : sample.getInfos()) { + writer.setString(SAMPLE_ID, sample.getSample()); + writer.setString(HAPLOGROUP, sample.getClade()); + writer.setString(TYPE, INFO_TYPE); + writer.setString(MESSAGE, info); + writer.setString(MISSING_POLY, getMissingPolymorphisms(sample)); + writer.setString(ADDITIONAL_POLY, getAdditionalPolymorphisms(sample)); + writer.next(); + } + } + writer.close(); + + System.out.println(""Written qc report to file "" + filename); + + } + + private String getMissingPolymorphisms(AnnotatedSample sample) { + String missingPolys = """"; + for (AnnotatedPolymorphism poly : sample.getExpectedMutations()) { + if (!poly.isFound()) { + missingPolys += poly.getNuc() + "" ""; + } + } + return missingPolys.trim(); + } + + private String getAdditionalPolymorphisms(AnnotatedSample sample) { + String remainingPolys = """"; + for (AnnotatedPolymorphism poly : sample.getRemainingMutations()) { + if (poly.getType().contains(""private"")) { + remainingPolys += poly.getNuc() + "" ""; + } + } + return remainingPolys.trim(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ClassificationTask.java",".java","3547","170","package genepi.haplogrep3.tasks; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import genepi.haplogrep3.haplogrep.io.readers.InputFileReaderFactory; +import genepi.haplogrep3.haplogrep.io.readers.SampleFileWithStatistics; +import genepi.haplogrep3.haplogrep.io.readers.StatisticCounter; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.Phylotree; + +public class ClassificationTask { + + private boolean success = true; + + private String error = null; + + private Phylotree phylotree; + + private List files; + + private List samples; + + private long start = 0; + + private long end = 0; + + private Distance distance; + + private boolean chip = false; + + private double hetLevel = 0.9; + + private int hits = 1; + + private boolean skipAlignmentRules = false; + + private int samplesOk = 0; + + private int samplesWarning = 0; + + private int samplesError = 0; + + private List counters = new Vector(); + + public ClassificationTask(Phylotree phylotree, List files, Distance distance) { + this.phylotree = phylotree; + this.files = files; + this.distance = distance; + } + + public void setChip(boolean chip) { + this.chip = chip; + } + + public void setHetLevel(double hetLevel) { + this.hetLevel = hetLevel; + } + + public void setHits(int hits) { + this.hits = hits; + } + + public void setSkipAlignmentRules(boolean skipAlignmentRules) { + this.skipAlignmentRules = skipAlignmentRules; + } + + public void run() throws Exception { + + start = System.currentTimeMillis(); + + samples = new ArrayList<>(); + if (files == null || files.isEmpty()) { + setError(""No files uploaded.""); + return; + } + + try { + + InputFileReaderFactory reader = new InputFileReaderFactory(); + reader.setChip(chip); + reader.setHetLevel(hetLevel); + reader.setSkipAlignmentRules(skipAlignmentRules); + + SampleFileWithStatistics sampleFile = reader.read(files, phylotree); + if (sampleFile.getStatistics() != null) { + counters = sampleFile.getStatistics().getCounters(); + } + + phylotree.classify(sampleFile.getSampleFile(), distance, hits, skipAlignmentRules); + + AnnotationTask annotationTask = new AnnotationTask(sampleFile.getSampleFile(), phylotree); + annotationTask.run(); + samples = annotationTask.getAnnotatedSamples(); + for (AnnotatedSample sample : samples) { + if (sample.hasErrors()) { + samplesError++; + } else if (sample.hasWarnings()) { + samplesWarning++; + } else { + samplesOk++; + } + } + + end = System.currentTimeMillis(); + + } catch (Exception e) { + e.printStackTrace(); + setError(e.getMessage()); + return; + } + + } + + public boolean isSuccess() { + return success; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + success = false; + } + + public List getSamples() { + return samples; + } + + public long getExecutionTime() { + return end - start; + } + + public int getSamplesOk() { + return samplesOk; + } + + public int getSamplesError() { + return samplesError; + } + + public int getSamplesWarning() { + return samplesWarning; + } + + public List getCounters() { + return counters; + } + + public StatisticCounter getCounterByLabel(String label) { + if (counters == null) { + return null; + } + for (StatisticCounter counter : counters) { + if (counter.getLabel().equals(label)) { + return counter; + } + } + return null; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/ExportAnnotationsTask.java",".java","2667","89","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import org.apache.commons.io.FilenameUtils; + +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationColumn; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationSettings; +import genepi.haplogrep3.model.AnnotatedPolymorphism; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.haplogrep3.model.Phylotree; +import genepi.io.table.writer.CsvTableWriter; + +public class ExportAnnotationsTask { + + private static final String SAMPLE_ID = ""SampleID""; + + private static final String SNP_POSITION = ""Position""; + + private static final String SNP_REF = ""Ref""; + + private static final String SNP_ALT = ""Alt""; + + private String filename; + + private List samples; + + private Phylotree phylotree; + + public ExportAnnotationsTask(List samples, String filename, Phylotree phylotree) { + this.samples = samples; + this.filename = FilenameUtils.removeExtension(filename); + this.filename = this.filename + "".annotations.txt""; + this.phylotree = phylotree; + } + + public void run() throws IOException { + + CsvTableWriter writer = new CsvTableWriter(filename, '\t', true); + List columns = new Vector(); + columns.add(SAMPLE_ID); + columns.add(SNP_POSITION); + columns.add(SNP_REF); + columns.add(SNP_ALT); + for (AnnotationSettings settings : phylotree.getAnnotations()) { + for (AnnotationColumn property : settings.getProperties()) { + if (property.getExport() != null) { + columns.add(property.getExport()); + } + } + } + + String[] columnsArray = new String[columns.size()]; + columns.toArray(columnsArray); + writer.setColumns(columnsArray); + for (AnnotatedSample sample : samples) { + phylotree.annotate(sample.getAnnotatedPolymorphisms()); + + for (AnnotatedPolymorphism mutation : sample.getAnnotatedPolymorphisms()) { + writer.setString(SAMPLE_ID, sample.getSample()); + writer.setInteger(SNP_POSITION, mutation.getPosition()); + writer.setString(SNP_REF, mutation.getRef()); + writer.setString(SNP_ALT, mutation.getAlt()); + for (AnnotationSettings settings : phylotree.getAnnotations()) { + for (AnnotationColumn property : settings.getProperties()) { + if (property.getExport() != null) { + String value = mutation.getAnnotations().get(property.getName()); + if (value == null) { + value = """"; + } + String cleanValue = value.replaceAll(""\"""", ""'""); + writer.setString(property.getExport(), cleanValue); + } + } + } + writer.next(); + } + + } + writer.close(); + + System.out.println(""Written annotations to file "" + filename); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/Job.java",".java","8655","367","package genepi.haplogrep3.tasks; + +import java.io.File; +import java.util.Date; +import java.util.List; + +import com.google.gson.Gson; + +import genepi.haplogrep3.haplogrep.io.readers.StatisticCounter; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.HaplogroupStatistics; +import genepi.haplogrep3.model.JobStatus; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.tasks.ExportHaplogroupsTask.ExportDataFormat; +import genepi.haplogrep3.tasks.ExportSequenceTask.ExportSequenceFormat; +import genepi.io.FileUtil; + +public class Job implements Runnable { + + private String id; + + private int samples = 0; + + private int samplesOk = 0; + + private int samplesWarning = 0; + + private int samplesError = 0; + + private String hash; + + private String phylotree; + + private Date submittedOn; + + private Date finisehdOn; + + private Date expiresOn; + + private long executionTime; + + private String error; + + private JobStatus status; + + private transient String _workspace; + + private transient Phylotree _phylotree; + + private transient List _files; + + private Distance distance; + + private boolean chip = false; + + private double hetLevel = 0.9; + + private int hits = 20; + + private HaplogroupStatistics statistics; + + private List counters; + + private boolean additionalOutput = false; + + public static long EXPIRES_HOURS = 24 * 7; + + private Job() { + + } + + public String getId() { + return id; + } + + public String getShortId() { + return id.substring(0, 6); + } + + public void setId(String id) { + this.id = id; + } + + public int getSamples() { + return samples; + } + + public void setSamples(int samples) { + this.samples = samples; + } + + public int getSamplesError() { + return samplesError; + } + + public void setSamplesError(int samplesError) { + this.samplesError = samplesError; + } + + public int getSamplesWarning() { + return samplesWarning; + } + + public void setSamplesWarning(int samplesWarning) { + this.samplesWarning = samplesWarning; + } + + public int getSamplesOk() { + return samplesOk; + } + + public void setSamplesOk(int samplesOk) { + this.samplesOk = samplesOk; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public String getPhylotree() { + return phylotree; + } + + public void setPhylotree(String phylotree) { + this.phylotree = phylotree; + } + + public void setChip(boolean chip) { + this.chip = chip; + } + + public boolean isChip() { + return chip; + } + + public void setHetLevel(double hetLevel) { + this.hetLevel = hetLevel; + } + + public double getHetLevel() { + return hetLevel; + } + + public void setHits(int hits) { + this.hits = hits; + } + + public int getHits() { + return hits; + } + + public Date getSubmittedOn() { + return submittedOn; + } + + public void setSubmittedOn(Date submittedOn) { + this.submittedOn = submittedOn; + } + + public Date getFinisehdOn() { + return finisehdOn; + } + + public void setFinisehdOn(Date finisehdOn) { + this.finisehdOn = finisehdOn; + } + + public Date getExpiresOn() { + return expiresOn; + } + + public void setExpiresOn(Date expiresOn) { + this.expiresOn = expiresOn; + } + + public long getExecutionTime() { + return executionTime; + } + + public void setExecutionTime(long executionTime) { + this.executionTime = executionTime; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public void setStatus(JobStatus status) { + this.status = status; + } + + public JobStatus getStatus() { + return status; + } + + public boolean isAdditionalOutput() { + return additionalOutput; + } + + public void setAdditionalOutput(boolean additionalOutput) { + this.additionalOutput = additionalOutput; + } + + public static Job create(String id, String workspace, Phylotree phylotree, List files, Distance distance, + boolean chip, double hetLevel, boolean additionalOutput) { + Job job = new Job(); + job.setId(id); + job.setStatus(JobStatus.SUBMITTED); + job.setSubmittedOn(new Date()); + Date date = new Date(new Date().getTime() + (EXPIRES_HOURS * 60L * 60L * 1000L)); + job.setExpiresOn(date); + job.setPhylotree(phylotree.getIdWithVersion()); + job._workspace = workspace; + job._phylotree = phylotree; + job._files = files; + job.distance = distance; + job.chip = chip; + job.hetLevel = hetLevel; + job.additionalOutput = additionalOutput; + job.save(); + return job; + } + + public void run() { + + setStatus(JobStatus.RUNNING); + save(); + + String dataDirectory = FileUtil.path(_workspace, getId(), ""data""); + + try { + + ClassificationTask task = new ClassificationTask(_phylotree, _files, distance); + task.setChip(chip); + task.setHetLevel(hetLevel); + task.setHits(hits); + task.setSkipAlignmentRules(false); + task.run(); + + FileUtil.deleteDirectory(dataDirectory); + + if (task.isSuccess()) { + + String extendedReportFilename = FileUtil.path(_workspace, getId(), ""haplogroups.extended.csv""); + ExportHaplogroupsTask exportExtendedReportTask = new ExportHaplogroupsTask(task.getSamples(), + extendedReportFilename, ExportDataFormat.EXTENDED, _phylotree.getReference()); + exportExtendedReportTask.run(); + + String reportFilename = FileUtil.path(_workspace, getId(), ""haplogroups.csv""); + ExportHaplogroupsTask exportReportTask = new ExportHaplogroupsTask(task.getSamples(), reportFilename, + ExportDataFormat.SIMPLE, _phylotree.getReference()); + exportReportTask.run(); + + if (additionalOutput) { + + String seqqueneFilename = FileUtil.path(_workspace, getId(), ""sequence""); + ExportSequenceTask exportSequenceTask = new ExportSequenceTask(task.getSamples(), seqqueneFilename, + ExportSequenceFormat.FASTA, _phylotree.getReference()); + exportSequenceTask.run(); + + ExportSequenceTask exportSequenceMsaTask = new ExportSequenceTask(task.getSamples(), + seqqueneFilename, ExportSequenceFormat.FASTA_MSA, _phylotree.getReference()); + exportSequenceMsaTask.run(); + + } + + String qcReportFilename = FileUtil.path(_workspace, getId(), ""samples""); + ExportQcReportTask exportQcReportTask = new ExportQcReportTask(task.getSamples(), qcReportFilename); + exportQcReportTask.run(); + + + String annotationFilename = FileUtil.path(_workspace, getId(), ""snps""); + ExportAnnotationsTask exportAnnotationsTask = new ExportAnnotationsTask(task.getSamples(), annotationFilename, _phylotree); + exportAnnotationsTask.run(); + + + save(task.getSamples()); + + setSamples(task.getSamples().size()); + setSamplesOk(task.getSamplesOk()); + setSamplesWarning(task.getSamplesWarning()); + setSamplesError(task.getSamplesError()); + setCounters(task.getCounters()); + + statistics = new HaplogroupStatistics(task.getSamples(), _phylotree); + + setExecutionTime(task.getExecutionTime()); + setFinisehdOn(new Date()); + setStatus(JobStatus.SUCCEDED); + + // create html report and zip file with all needed files + + String htmlReportFilename = FileUtil.path(_workspace, getId(), ""haplogroups.html""); + ExportHtmlReportTask htmlReportTask = new ExportHtmlReportTask(this, htmlReportFilename); + htmlReportTask.run(); + + String[] files = new String[] { extendedReportFilename, qcReportFilename + "".qc.txt"", + htmlReportFilename, annotationFilename + "".annotations.txt"" }; + + String zipFilename = FileUtil.path(_workspace, getId(), ""haplogroups.zip""); + CreateZipFileTask createZipFileTask = new CreateZipFileTask(files, zipFilename); + createZipFileTask.run(); + + save(); + + } else { + + setExecutionTime(task.getExecutionTime()); + setFinisehdOn(new Date()); + setStatus(JobStatus.FAILED); + setError(task.getError()); + save(); + + } + + } catch (Exception e) { + + setExecutionTime(0); + setFinisehdOn(new Date()); + setStatus(JobStatus.FAILED); + e.printStackTrace(); + save(); + + FileUtil.deleteDirectory(dataDirectory); + + } + } + + public HaplogroupStatistics getStatistics() { + return statistics; + } + + public void setStatistics(HaplogroupStatistics statistics) { + this.statistics = statistics; + } + + public void setCounters(List counters) { + this.counters = counters; + } + + public List getCounters() { + return counters; + } + + protected synchronized void save() { + String jobFilename = FileUtil.path(_workspace, getId() + "".json""); + Gson gson = new Gson(); + FileUtil.writeStringBufferToFile(jobFilename, new StringBuffer(gson.toJson(this))); + } + + protected void save(List samples) { + String cladesFilename = FileUtil.path(_workspace, getId(), ""clades.json""); + Gson gson = new Gson(); + FileUtil.writeStringBufferToFile(cladesFilename, new StringBuffer(gson.toJson(samples))); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/tasks/PhylotreeGraphBuilder.java",".java","1693","66","package genepi.haplogrep3.tasks; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import core.Polymorphism; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.util.PolymorphismHelper; +import genepi.haplogrep3.web.util.graph.Graph; +import phylotree.PhyloTreeNode; + +public class PhylotreeGraphBuilder { + + public static Graph buildGraph(Phylotree phylotree, String haplogroup) throws IOException { + Set haplogroups = new HashSet<>(); + haplogroups.add(haplogroup); + return build(phylotree, haplogroups); + } + + public static Graph build(Phylotree phylotree, Set haplogroups) throws IOException { + + Graph graph = new Graph(); + for (String haplogroup : haplogroups) { + graph.addNode(cleanUpNode(haplogroup)).setColor(""lightblue""); + } + + for (String haplogroup : haplogroups) { + PhyloTreeNode node = phylotree.getHaplogroupTreeNode(haplogroup); + writeTree(node, graph); + } + return graph; + } + + private static void writeTree(PhyloTreeNode child, Graph graph) { + + if (child == null) { + return; + } + + PhyloTreeNode root = child.getParent(); + if (root == null) { + return; + } + + ArrayList variants = child.getExpectedPolys(); + PolymorphismHelper.sortByPosition(variants); + String snps = """"; + for (int j = 0; j < variants.size(); j++) { + snps += PolymorphismHelper.getLabel(variants.get(j)); + snps += ""\\n""; + } + + graph.addEdge(cleanUpNode(root.getHaplogroup().toString()), cleanUpNode(child.getHaplogroup().toString()), + snps); + + writeTree(root, graph); + + } + + protected static String cleanUpNode(String node) { + return node.replace("" "", ""\\n"").replace(""'"", ""\\'""); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/plugins/Plugin.java",".java","1044","69","package genepi.haplogrep3.plugins; + +import java.util.List; +import java.util.Vector; + +public class Plugin { + + private String id; + + private String description; + + private String url; + + private String license; + + private String latest; + + private List releases = new Vector(); + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getLicense() { + return license; + } + + public void setLicense(String license) { + this.license = license; + } + + public String getLatest() { + return latest; + } + + public void setLatest(String latest) { + this.latest = latest; + } + + public void setReleases(List releases) { + this.releases = releases; + } + + public List getReleases() { + return releases; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/plugins/PluginRelease.java",".java","816","59","package genepi.haplogrep3.plugins; + +import java.util.Date; +import java.util.Map; + +public class PluginRelease { + + private String url; + + private String version; + + private Date date; + + private String sha512sum; + + private Plugin plugin; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getSha512sum() { + return sha512sum; + } + + public void setSha512sum(String sha512sum) { + this.sha512sum = sha512sum; + } + + public Plugin getPlugin() { + return plugin; + } + + public void setPlugin(Plugin plugin) { + this.plugin = plugin; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/plugins/PluginRepository.java",".java","4913","191","package genepi.haplogrep3.plugins; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Formatter; +import java.util.List; +import java.util.Vector; + +import com.esotericsoftware.yamlbeans.YamlReader; + +import genepi.io.FileUtil; +import net.lingala.zip4j.ZipFile; + +public class PluginRepository { + + public static String LATEST_VERSION = null; + + public File pluginsLocation = new File(""trees""); + + private List> repositories = new Vector>(); + + public PluginRepository(List urls, boolean forceUpdate, File pluginsLocation) throws IOException { + this.pluginsLocation = pluginsLocation; + pluginsLocation.mkdirs(); + + for (String url : urls) { + repositories.add(loadFromUrl(url, forceUpdate)); + } + + } + + public PluginRelease findById(String id) { + String[] tiles = id.split(""@"", 2); + String name = tiles[0]; + String version = LATEST_VERSION; + if (tiles.length > 1) { + version = tiles[1]; + } else { + throw new RuntimeException(""Please specify a version. Latest is not yet supported.""); + } + return findByNameAndVersion(name, version); + } + + public PluginRelease findByNameAndVersion(String name, String version) { + List releases = findReleasesByName(name); + if (releases == null) { + throw new RuntimeException(""Plugin '"" + name + ""' not found.""); + } + PluginRelease release = findRelease(releases, version); + if (release == null) { + throw new RuntimeException(""Plugin '"" + name + ""' found, but version "" + version + "" not found.""); + } + return release; + } + + private List findReleasesByName(String name) { + for (List plugins : repositories) { + for (Plugin plugin : plugins) { + if (plugin.getId().equals(name)) { + return plugin.getReleases(); + } + } + } + return null; + } + + protected PluginRelease findRelease(List releases, String version) { + for (PluginRelease release : releases) { + if (release.getVersion().equals(version)) { + return release; + } + } + return null; + } + + public InstalledPlugin resolveRelease(PluginRelease release) throws IOException { + + String id = release.getPlugin().getId(); + + String filename = ""tree.yaml""; + + File pluginPath = new File(pluginsLocation, FileUtil.path(id, release.getVersion())); + InstalledPlugin plugin = new InstalledPlugin(); + plugin.setRelease(release); + plugin.setPath(new File(pluginPath.getAbsolutePath(), filename)); + if (pluginPath.exists()) { + return plugin; + } + + if (isHttpProtocol(release.getUrl())) { + pluginPath.mkdirs(); + File zipPackage = new File(pluginPath, ""package.zip""); + download(release.getUrl(), zipPackage); + extract(zipPackage, pluginPath); + } else { + plugin.setPath(new File(release.getUrl())); + } + + return plugin; + + } + + protected void download(String url, File target) throws IOException { + + InputStream in = new URL(url).openStream(); + Files.copy(in, target.toPath(), StandardCopyOption.REPLACE_EXISTING); + + } + + protected void extract(File archive, File target) throws IOException { + new ZipFile(archive).extractAll(target.getAbsolutePath()); + + } + + protected boolean isHttpProtocol(String url) { + return url.toLowerCase().startsWith(""http://"") || url.toLowerCase().startsWith(""https://""); + } + + private List loadFromUrl(String url, boolean forceUpdate) throws IOException { + + File indexFile = null; + + if (isHttpProtocol(url)) { + indexFile = new File(pluginsLocation, getNameForUrl(url) + "".yaml""); + if (!indexFile.exists() || forceUpdate) { + download(url, indexFile); + } + } else { + indexFile = new File(url); + } + + return loadFromFile(indexFile); + } + + private List loadFromFile(File file) throws IOException { + + if (!file.exists()) { + throw new IOException(""File '"" + file.getAbsolutePath() + ""' not found.""); + } + + try { + + YamlReader reader = new YamlReader(new FileReader(file)); + reader.getConfig().setPropertyElementType(Plugin.class, ""releases"", PluginRelease.class); + List plugins = reader.read(List.class, Plugin.class); + for (Plugin plugin : plugins) { + for (PluginRelease release : plugin.getReleases()) { + release.setPlugin(plugin); + } + } + return plugins; + + } catch (Exception e) { + + System.out.println(""Loading repo failed""); + throw e; + + } + + } + + private String getNameForUrl(String url) { + MessageDigest md; + try { + md = MessageDigest.getInstance(""MD5""); + + md.update(url.getBytes()); + byte[] md5sum = md.digest(); + + Formatter fm = new Formatter(); + for (byte b : md5sum) { + fm.format(""%02x"", b); + } + String result = fm.out().toString(); + fm.close(); + return result; + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/plugins/InstalledPlugin.java",".java","386","28","package genepi.haplogrep3.plugins; + +import java.io.File; + +public class InstalledPlugin { + + private File path; + + private PluginRelease release; + + public File getPath() { + return path; + } + + public void setPath(File path) { + this.path = path; + } + + public PluginRelease getRelease() { + return release; + } + + public void setRelease(PluginRelease release) { + this.release = release; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/util/PolymorphismHelper.java",".java","3038","131","package genepi.haplogrep3.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.StringTokenizer; + +import core.Mutations; +import core.Polymorphism; +import core.TestSample; +import genepi.haplogrep3.model.Phylotree; + +public class PolymorphismHelper { + + public static boolean isNotN(Polymorphism polymorphism) { + + return (polymorphism.getMutation() != Mutations.N); + + } + + public static boolean isInSGene(Polymorphism polymorphism) { + + return (polymorphism.getPosition() > 21563 && polymorphism.getPosition() < 25384); + + } + + public static boolean isInSGeneAAC(String aac) { + + return (aac.contains(""S:"")); + + } + + public static int getNCount(ArrayList poly) { + int countNs = 0; + for (int i = 0; i < poly.size(); i++) { + if (poly.get(i).getMutation() == Mutations.N) + countNs++; + } + return countNs; + } + + public static int getMixCount(ArrayList poly) { + int countMix = 0; + for (int i = 0; i < poly.size(); i++) { + if (poly.get(i).getPosition() > 0) { + switch (poly.get(i).getMutation()) { + case R: + countMix++; + break; + case Y: + countMix++; + break; + case K: + countMix++; + break; + case M: + countMix++; + break; + case S: + countMix++; + break; + case W: + countMix++; + break; + case H: + countMix++; + break; + default: + break; + } + } + } + return countMix; + + } + + public static Integer getRangeLength(String range) { + int countBasesCovered = 0; + StringTokenizer st = new StringTokenizer(range, "";""); + while (st.hasMoreElements()) { + String rangeEntry = st.nextToken(); + int start = 0; + int stop = 0; + if (rangeEntry.contains(""-"")) { + start = Integer.valueOf(rangeEntry.split(""-"")[0].trim()); + stop = Integer.valueOf(rangeEntry.split(""-"")[1].trim()); + countBasesCovered += stop - start + 1; + } else if (!rangeEntry.trim().equals(""0"")) { + countBasesCovered++; + } + } + return countBasesCovered; + } + + public static double getWarnings(TestSample sample) { + double quality = sample.getResults().get(0).getDistance(); + BigDecimal bd = new BigDecimal(quality).setScale(2, RoundingMode.HALF_UP); + double result = bd.doubleValue(); + return result; + } + + public static String getLabel(Polymorphism polymorphism) { + return polymorphism.toString(); + } + + public static String getType(Polymorphism polymorphism, Phylotree phylotree) { + if (phylotree.getPhylotreeInstance().getMutationRate(polymorphism) == 0) { + if (phylotree.getPhylotreeInstance().isHotspot(polymorphism)) { + return ""hotspot""; + } else { + return ""global private mutation""; + } + } else { + return ""local private mutation""; + } + } + + public static void sortByPosition(List polymorphisms) { + polymorphisms.sort(new Comparator() { + + @Override + public int compare(Polymorphism arg0, Polymorphism arg1) { + return Integer.compare(arg0.getPosition(), arg1.getPosition()); + } + }); + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/util/TestSampleHelper.java",".java","404","20","package genepi.haplogrep3.util; + +import java.util.Comparator; +import java.util.List; + +import core.TestSample; + +public class TestSampleHelper { + + public static void sortBySampleId(List samplesH) { + samplesH.sort(new Comparator() { + @Override + public int compare(TestSample arg0, TestSample arg1) { + return arg0.getSampleID().compareTo(arg1.getSampleID()); + } + }); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/HaplogroupClustering.java",".java","1377","49","package genepi.haplogrep3.haplogrep.io; + +import java.util.List; + +import core.Haplogroup; +import genepi.haplogrep3.model.Cluster; +import genepi.haplogrep3.model.Phylotree; +import genepi.io.table.writer.CsvTableWriter; + +public class HaplogroupClustering { + + // static String[] TOPLEVEL_HAPLOGROUPS_TOP_DOWN = new String[] { ""L0"", ""L1"", + // ""L5"", ""L2"", ""L6"", ""L4"", ""L3"", ""M"", ""C"", + // ""Z"", ""E"", ""G"", ""Q"", ""D"", ""N"", ""Y"", ""A"", ""O"", ""S"", ""F"", ""B6"", ""P"", ""I"", ""W"", + // ""X"", ""R"", ""HV"", ""V"", ""H"", ""J"", + // ""T"", ""U"", ""K""}; + + public HaplogroupClustering(Phylotree phylotree, List clusters, String filename) { + + CsvTableWriter writer = new CsvTableWriter(filename, '\t'); + + String[] columnsWrite = { ""Haplogroup"", ""Super Haplogroup"" }; + writer.setColumns(columnsWrite); + + for (Haplogroup haplogroup : phylotree.getHaplogroups()) { + + try { + String topLevelHaplogroup = phylotree.getNearestCluster(clusters, haplogroup.toString()); + + // TODO Haplogroups like H2a2a1 dont have a super haplogroup. Problem with + // parsing? + if (topLevelHaplogroup != null) { + writer.setString(""Haplogroup"", haplogroup.toString()); + writer.setString(""Super Haplogroup"", topLevelHaplogroup); + writer.next(); + } + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + System.out.println(""Done""); + writer.close(); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/PhylotreeDto.java",".java","1282","50","package genepi.haplogrep3.haplogrep.io; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; + +@JacksonXmlRootElement(localName = ""phylotree"") +public class PhylotreeDto { + + @JsonIgnore + private Set allMutations = new HashSet(); + + @JacksonXmlElementWrapper(useWrapping = false) + @JsonProperty(""haplogroup"") + public List haplogroups = new Vector(); + + public List getHaplogroups() { + return haplogroups; + } + + public void setHaplogroups(List haplogroups) { + this.haplogroups = haplogroups; + } + + public HaplogroupDto addHaplogroup(String name) { + HaplogroupDto haplogroup = new HaplogroupDto(name); + haplogroups.add(haplogroup); + return haplogroup; + } + + public Set getAllMutations() { + return allMutations; + } + + public void setAllMutations(Set allMutations) { + this.allMutations = allMutations; + } + + public void addMutation(String mutation) { + allMutations.add(mutation); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/PhylotreeReader.java",".java","2606","88","package genepi.haplogrep3.haplogrep.io; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.UUID; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.google.gson.Gson; +import com.google.gson.internal.LinkedTreeMap; + +public class PhylotreeReader { + + public static PhylotreeDto readFromJson(String filename) throws Exception { + + Gson gson = new Gson(); + LinkedTreeMap o = (LinkedTreeMap) gson.fromJson(new FileReader(filename), Object.class); + + PhylotreeDto phylotree = new PhylotreeDto(); + buildTree(""root"", o.get(""tree""), phylotree, null); + + return phylotree; + + } + + public static PhylotreeDto readFromXml(String filename) throws JsonParseException, JsonMappingException, IOException { + + XmlMapper xmlMapper = new XmlMapper(); + PhylotreeDto phylotree = xmlMapper.readValue(new File(filename), PhylotreeDto.class); + + return phylotree; + + } + + protected static void buildTree(String parent, Object tree, PhylotreeDto phylotree, + HaplogroupDto parentHaplogroup) { + + String name = parent; + + if (((LinkedTreeMap) ((LinkedTreeMap) tree).get(""branch_attrs"")).get(""labels"") != null) { + + Object clade = ((LinkedTreeMap) ((LinkedTreeMap) ((LinkedTreeMap) tree).get(""branch_attrs"")).get(""labels"")) + .get(""clade""); + + if (clade != null) { + name = clade.toString(); + parent = name; + } else { + name = parent + ""_"" + UUID.randomUUID(); + } + + } else { + name = parent + ""_"" + UUID.randomUUID(); + } + + HaplogroupDto haplogroup = null; + if (parentHaplogroup != null) { + haplogroup = parentHaplogroup.addHaplogroup(name); + } else { + haplogroup = phylotree.addHaplogroup(name); + } + + if (((LinkedTreeMap) ((LinkedTreeMap) tree).get(""branch_attrs"")).get(""mutations"") != null) { + Object mutations = (Object) ((LinkedTreeMap) ((LinkedTreeMap) tree).get(""branch_attrs"")).get(""mutations""); + if (mutations != null && ((LinkedTreeMap) mutations).get(""nuc"") != null) { + for (Object mutation : (ArrayList) ((LinkedTreeMap) mutations).get(""nuc"")) { + // remove reference allele and rename deletions + String mutationName = mutation.toString().substring(1).replace(""-"", ""d""); + haplogroup.addPoly(mutationName); + phylotree.addMutation(mutationName); + } + } + } + + ArrayList children = (ArrayList) (((LinkedTreeMap) tree).get(""children"")); + if (children != null) { + for (Object child : children) { + buildTree(parent, child, phylotree, haplogroup); + } + } + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/PhylotreePoly.java",".java","770","48","package genepi.haplogrep3.haplogrep.io; + +public class PhylotreePoly implements Comparable { + + private String name; + + private double amount; + + public PhylotreePoly() { + + } + + public PhylotreePoly(String name, double amount) { + super(); + this.name = name; + this.amount = amount; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } + + @Override + public int compareTo(PhylotreePoly o) { + if (this.getAmount() > o.getAmount()) { + return -1; + } + if (this.getAmount() < o.getAmount()) { + return 1; + } else { + return 0; + } + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/PhylotreeWriter.java",".java","492","20","package genepi.haplogrep3.haplogrep.io; + +import java.io.File; +import java.io.IOException; + +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +public class PhylotreeWriter { + + public static void writeToXml(String filename, PhylotreeDto phylotree) throws IOException { + + XmlMapper xmlMapper = new XmlMapper(); + xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); + xmlMapper.writeValue(new File(filename), phylotree); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/HaplogroupDto.java",".java","1412","66","package genepi.haplogrep3.haplogrep.io; + +import java.util.List; +import java.util.Vector; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; + +public class HaplogroupDto { + + @JacksonXmlProperty(isAttribute = true) + private String name = """"; + + @JacksonXmlElementWrapper(useWrapping = false) + @JsonProperty(""haplogroup"") + public List haplogroups = new Vector(); + + @JacksonXmlElementWrapper(localName = ""details"") + @JsonProperty(""poly"") + private List details = new Vector(); + + public HaplogroupDto() { + + } + + public HaplogroupDto(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getDetails() { + return details; + } + + public void setDetails(List details) { + this.details = details; + } + + public void addPoly(String poly) { + details.add(poly); + } + + public void setHaplogroups(List haplogroups) { + this.haplogroups = haplogroups; + } + + public List getHaplogroups() { + return haplogroups; + } + + public HaplogroupDto addHaplogroup(String name) { + HaplogroupDto haplogroup = new HaplogroupDto(name); + haplogroups.add(haplogroup); + return haplogroup; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/VariantsOfConcern.java",".java","1650","61","package genepi.haplogrep3.haplogrep.io; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import genepi.annotate.util.MapLocusGFF3; +import genepi.annotate.util.MapLocusItem; +import genepi.annotate.util.SequenceUtil; +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Phylotree; +import genepi.io.text.LineReader; +import htsjdk.samtools.util.IntervalTree.Node; + +public class VariantsOfConcern { + + private Set variants = new HashSet(); + + private Map codonTable; + + private MapLocusGFF3 maplocus; + + private String refSequence; + + public VariantsOfConcern(String filename) throws IOException { + LineReader reader = new LineReader(filename); + while (reader.next()) { + String variant = reader.get(); + variants.add(variant); + } + reader.close(); + + Phylotree phylotree = App.getDefault().getTreeRepository().getById(""sarscov2-v6""); + + codonTable = SequenceUtil.loadCodonTableLong(phylotree.getAacTable()); + maplocus = new MapLocusGFF3(phylotree.getGff()); + refSequence = phylotree.getReference().getSequence(); + + } + + public boolean includes(int position, String mutation) throws Exception { + + Iterator> result = maplocus.findByPosition(position); + if (result.hasNext()) { + MapLocusItem item = result.next().getValue(); + String aac = SequenceUtil.getAAC(refSequence, codonTable, item, position, + mutation); + aac = aac.replaceAll(""\\?"", ""-""); + String variant = item.getShorthand() + "":"" + aac; + System.out.println(variant); + return variants.contains(variant); + } + + return false; + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/WeightsWriter.java",".java","2276","80","package genepi.haplogrep3.haplogrep.io; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.text.DecimalFormatSymbols; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +/** + * @author hansi + * + */ +public class WeightsWriter { + + public static double WEIGHT_VOC = 2.0; + + public static void writeToTxt(String filename, PhylotreeDto phylotree, VariantsOfConcern variantsOfConcern) + throws Exception { + + List haplolists = phylotree.getHaplogroups(); + + Map> poliesToHaplogroups = new HashMap<>(); + writeTreeRecursive(haplolists, poliesToHaplogroups); + + List polymorphisms = new Vector(); + for (String poly : poliesToHaplogroups.keySet()) { + polymorphisms.add(new PhylotreePoly(poly, 1.0 / poliesToHaplogroups.get(poly).size())); + } + + // sort and write + Collections.sort(polymorphisms); + + BufferedWriter weightsWriter = new BufferedWriter(new FileWriter(filename)); + + for (PhylotreePoly ph : polymorphisms) { + + int pos = Integer.valueOf(ph.getName().substring(0, ph.getName().length() - 1)); + + String mutation = ph.getName().substring(ph.getName().length() - 1, ph.getName().length()); + + boolean variantOfConcern = variantsOfConcern.includes(pos, mutation); + + weightsWriter.write( + ph.getName() + ""\t"" + ph.getAmount() + ""\t"" + (ph.getAmount()) + ""\t"" + variantOfConcern + ""\n""); + + } + + weightsWriter.close(); + } + + private static void writeTreeRecursive(List haplogroup, Map> poliesToHaplogroups) + + throws IOException { + + for (int i = 0; i < haplogroup.size(); i++) { + List poly = haplogroup.get(i).getDetails(); + for (int j = 0; j < poly.size(); j++) { + Set haplogroups = poliesToHaplogroups.get(poly.get(j)); + if (haplogroups == null) { + haplogroups = new HashSet(); + poliesToHaplogroups.put(poly.get(j), haplogroups); + } + String clade = haplogroup.get(i).getName().split(""_"")[0]; + haplogroups.add(clade); + } + + writeTreeRecursive(haplogroup.get(i).getHaplogroups(), poliesToHaplogroups); + } + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/InputFileReaderFactory.java",".java","1451","53","package genepi.haplogrep3.haplogrep.io.readers; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import genepi.haplogrep3.haplogrep.io.readers.impl.FastaInputFileReader; +import genepi.haplogrep3.haplogrep.io.readers.impl.HsdInputFileReader; +import genepi.haplogrep3.haplogrep.io.readers.impl.VcfInputFileReader; +import genepi.haplogrep3.model.Phylotree; + +public class InputFileReaderFactory { + + private boolean chip = false; + + private double hetLevel = 0.9; + + private boolean skipAlignmentRules = false; + + protected List getSupportedReaders() { + List readers = new Vector(); + readers.add(new HsdInputFileReader()); + readers.add(new VcfInputFileReader(chip, hetLevel)); + readers.add(new FastaInputFileReader(skipAlignmentRules)); + return readers; + } + + public SampleFileWithStatistics read(List files, Phylotree phylotree) throws Exception { + + for (AbstractInputFileReader reader : getSupportedReaders()) { + if (reader.accepts(files, phylotree)) { + return reader.read(files, phylotree); + } + } + + throw new IOException(""Unsupported file format""); + } + + public void setChip(boolean chip) { + this.chip = chip; + } + + public void setHetLevel(double hetLevel) { + this.hetLevel = hetLevel; + } + + public void setSkipAlignmentRules(boolean skipAlignmentRules) { + this.skipAlignmentRules = skipAlignmentRules; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/SampleFileStatistics.java",".java","253","16","package genepi.haplogrep3.haplogrep.io.readers; + +import java.util.List; + +public abstract class SampleFileStatistics { + + public SampleFileStatistics() { + + } + + public abstract boolean isFailed(); + + public abstract List getCounters(); + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/StatisticCounter.java",".java","1778","84","package genepi.haplogrep3.haplogrep.io.readers; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +import genepi.haplogrep3.haplogrep.io.readers.impl.StatisticCounterType; + +public class StatisticCounter { + + private String label = """"; + + private String value = """"; + + private StatisticCounterType type = StatisticCounterType.INFO; + + public static DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); + static { + symbols.setGroupingSeparator(','); + } + + public static final DecimalFormat DECIMAL_FORMAT_INTEGER = new DecimalFormat(""###,###"", symbols); + + public static final DecimalFormat DECIMAL_FORMAT_DOUBLE = new DecimalFormat(""#.##"", symbols); + + public StatisticCounter() { + + } + + public StatisticCounter(String label, Object value) { + this(label, value, -1); + } + + public StatisticCounter(String label, Object value, double threshold) { + this.label = label; + + if (value instanceof Integer) { + + this.value = DECIMAL_FORMAT_INTEGER.format((Integer) value); + if (threshold != -1 && (Integer) value > threshold) { + type = StatisticCounterType.WARNING; + } + + } else if (value instanceof Double || value instanceof Float) { + + this.value = DECIMAL_FORMAT_DOUBLE.format((Double) value); + if (threshold != -1 && (Integer) value > threshold) { + type = StatisticCounterType.WARNING; + } + + } else { + + this.value = value.toString(); + + } + + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public StatisticCounterType getType() { + return type; + } + + public void setType(StatisticCounterType type) { + this.type = type; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/AbstractInputFileReader.java",".java","692","31","package genepi.haplogrep3.haplogrep.io.readers; + +import java.io.File; +import java.util.List; + +import core.SampleFile; +import genepi.haplogrep3.model.Phylotree; + +public abstract class AbstractInputFileReader { + + public abstract boolean accepts(List files, Phylotree phylotree); + + public abstract SampleFileWithStatistics read(List files, Phylotree phylotree) throws Exception; + + public boolean hasFileExtensions(List files, String... extensions) { + for (File file : files) { + boolean ok = false; + for (String extension : extensions) { + if (file.getName().endsWith(extension)) { + ok = true; + } + } + if (!ok) { + return false; + } + } + return true; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/SampleFileWithStatistics.java",".java","498","28","package genepi.haplogrep3.haplogrep.io.readers; + +import core.SampleFile; + +public class SampleFileWithStatistics { + + private SampleFile sampleFile; + + private SampleFileStatistics statistics; + + public SampleFileWithStatistics(SampleFile sampleFile, SampleFileStatistics statistics) { + + this.sampleFile = sampleFile; + this.statistics = statistics; + } + + + public SampleFile getSampleFile() { + return sampleFile; + } + + + public SampleFileStatistics getStatistics() { + return statistics; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/impl/HsdInputFileReader.java",".java","957","33","package genepi.haplogrep3.haplogrep.io.readers.impl; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import core.SampleFile; +import genepi.haplogrep3.haplogrep.io.readers.AbstractInputFileReader; +import genepi.haplogrep3.haplogrep.io.readers.SampleFileWithStatistics; +import genepi.haplogrep3.model.Phylotree; +import importer.HsdImporter; + +public class HsdInputFileReader extends AbstractInputFileReader { + + public boolean accepts(List files, Phylotree phylotree) { + return hasFileExtensions(files, "".hsd"", "".txt""); + } + + public SampleFileWithStatistics read(List files, Phylotree phylotree) throws Exception { + + ArrayList lines = new ArrayList(); + HsdImporter importer = new HsdImporter(); + for (File file : files) { + lines.addAll(importer.load(file)); + } + + SampleFile sampleFile = new SampleFile(lines, phylotree.getReference()); + return new SampleFileWithStatistics(sampleFile, null); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/impl/FastaInputFileReader.java",".java","1593","55","package genepi.haplogrep3.haplogrep.io.readers.impl; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.SystemUtils; + +import core.SampleFile; +import genepi.haplogrep3.haplogrep.io.readers.AbstractInputFileReader; +import genepi.haplogrep3.haplogrep.io.readers.SampleFileWithStatistics; +import genepi.haplogrep3.model.Phylotree; +import importer.FastaImporter; + +public class FastaInputFileReader extends AbstractInputFileReader { + + private boolean skipAlignmentRules = false; + + public FastaInputFileReader(boolean skipAlignmentRules) { + this.skipAlignmentRules = skipAlignmentRules; + } + + public boolean accepts(List files, Phylotree phylotree) { + return hasFileExtensions(files, "".fasta"", "".fasta.gz"", "".fa"", "".fa.gz""); + } + + public SampleFileWithStatistics read(List files, Phylotree phylotree) throws Exception { + + if (SystemUtils.IS_OS_WINDOWS) { + throw new IOException(""Fasta is no supported on Windows""); + } + + ArrayList lines = new ArrayList(); + FastaImporter importer = new FastaImporter(); + for (File file : files) { + lines.addAll(importer.load(file, phylotree.getReference())); + } + + SampleFile sampleFile = new SampleFile(lines, phylotree.getReference()); + + if (!skipAlignmentRules && phylotree.getAlignmentRules() != null) { + + phylotree.Phylotree haplogrepPhylotree = phylotree.getPhylotreeInstance(); + + sampleFile.applyNomenclatureRules(haplogrepPhylotree, phylotree.getAlignmentRules()); + + } + + return new SampleFileWithStatistics(sampleFile, null); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/impl/StatisticCounterType.java",".java","108","8","package genepi.haplogrep3.haplogrep.io.readers.impl; + +public enum StatisticCounterType { + + WARNING, INFO + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/impl/VcfInputFileReader.java",".java","1628","59","package genepi.haplogrep3.haplogrep.io.readers.impl; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import core.SampleFile; +import genepi.haplogrep3.haplogrep.io.readers.AbstractInputFileReader; +import genepi.haplogrep3.haplogrep.io.readers.SampleFileWithStatistics; +import genepi.haplogrep3.haplogrep.io.readers.impl.vcf.VcfSampleFileStatistics; +import genepi.haplogrep3.model.Phylotree; +import importer.VcfImporter; +import util.ExportUtils; +import vcf.Sample; + +public class VcfInputFileReader extends AbstractInputFileReader { + + private boolean chip = false; + + private double hetLevel = 0.9; + + public VcfInputFileReader(boolean chip, double hetLevel) { + this.chip = chip; + this.hetLevel = hetLevel; + } + + public boolean accepts(List files, Phylotree phylotree) { + return hasFileExtensions(files, "".vcf"", "".vcf.gz""); + } + + public SampleFileWithStatistics read(List files, Phylotree phylotree) throws Exception { + + VcfSampleFileStatistics statistics = new VcfSampleFileStatistics(files, phylotree); + + ArrayList lines = new ArrayList(); + VcfImporter importerVcf = new VcfImporter(); + for (File file : files) { + HashMap samples = importerVcf.load(file, chip); + lines = ExportUtils.vcfTohsd(samples, Double.valueOf(hetLevel)); + + } + + SampleFile sampleFile = new SampleFile(lines, phylotree.getReference()); + + return new SampleFileWithStatistics(sampleFile, statistics); + + } + + public void setChip(boolean chip) { + this.chip = chip; + } + + public void setHetLevel(double hetLevel) { + this.hetLevel = hetLevel; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/readers/impl/vcf/VcfSampleFileStatistics.java",".java","5865","233","package genepi.haplogrep3.haplogrep.io.readers.impl.vcf; + +import java.io.File; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import core.Polymorphism; +import core.Reference; +import genepi.haplogrep3.haplogrep.io.readers.SampleFileStatistics; +import genepi.haplogrep3.haplogrep.io.readers.StatisticCounter; +import genepi.haplogrep3.model.Phylotree; +import htsjdk.variant.variantcontext.Allele; +import htsjdk.variant.variantcontext.Genotype; +import htsjdk.variant.variantcontext.VariantContext; +import htsjdk.variant.vcf.VCFFileReader; +import htsjdk.variant.vcf.VCFHeader; + +public class VcfSampleFileStatistics extends SampleFileStatistics { + + private static final double VARIANT_CALL_RATE = 0.90; + + private static final double SAMPLE_CALL_RATE = 0.5; + + private int lines = 0; + + private int variants = 0; + + private int samples = 0; + + private int misMatches = 0; + + private int invalidAlleles = 0; + + private int outOfRange = 0; + + private int indels = 0; + + private int passed = 0; + + private int duplicates = 0; + + private int filterFlags = 0; + + private int strandFlips = 0; + + private int multiallelics = 0; + + private int lowSampleCallRate = 0; + + private int lowVariantCallRate = 0; + + private int treeHits = 0; + + private int monomorphics = 0; + + private Reference reference; + + private int[] snpsPerSampleCount; + + private List files; + + private Phylotree phylotree; + + public VcfSampleFileStatistics(List files, Phylotree phylotree) { + this.files = files; + this.phylotree = phylotree; + this.reference = phylotree.getReference(); + + for (File file : files) { + processVcfFile(file); + } + } + + private void processVcfFile(File file) { + + final VCFFileReader vcfReader = new VCFFileReader(file, false); + VCFHeader vcfHeader = vcfReader.getFileHeader(); + + samples += vcfHeader.getGenotypeSamples().size(); + + snpsPerSampleCount = new int[samples]; + for (int i = 0; i < samples; i++) { + snpsPerSampleCount[i] = 0; + } + + for (final VariantContext vc : vcfReader) { + + lines++; + + int position = vc.getStart(); + String refAllele = reference.getReferenceBase(position); + String refAlleleSample = vc.getReference().getBaseString(); + + for (Allele allele : vc.getAlternateAlleles()) { + // ignore insertions + if (allele.getBaseString().length() != 1) { + continue; + } + String variant = position + allele.getBaseString(); + + if (phylotree.getPhylotreeInstance().isHotspot(variant)) { + continue; + } + + variants++; + + if (phylotree.getPhylotreeInstance().isTreePosition(variant)) { + treeHits++; + } + } + + if (refAllele == null) { + outOfRange++; + continue; + } + + if (refAlleleSample.length() == 1 && !refAllele.equals(refAlleleSample)) { + misMatches++; + } + + if (isStrandFlip(refAllele, refAlleleSample)) { + strandFlips++; + continue; + } + + if (isFiltered(vc)) { + + if (vc.getFilters().contains(""DUP"")) { + duplicates++; + } else { + filterFlags++; + } + continue; + } + + if (vc.getAlternateAlleles().size() > 1) { + multiallelics++; + continue; + } + + if (vc.isIndel() || vc.isComplexIndel()) { + indels++; + continue; + } + + passed++; + + if ((vc.getHomRefCount() + vc.getNoCallCount() == vc.getNSamples())) { + monomorphics++; + } + + if (1 - (vc.getNoCallCount() / (double) vc.getNSamples()) < VARIANT_CALL_RATE) { + lowVariantCallRate++; + } + + int i = 0; + for (String sample : vcfHeader.getSampleNamesInOrder()) { + Genotype genotype = vc.getGenotype(sample); + if (genotype.isCalled()) { + snpsPerSampleCount[i] += 1; + } + i++; + } + + } + + for (int i = 0; i < snpsPerSampleCount.length; i++) { + int snps = snpsPerSampleCount[i]; + double sampleCallRate = (double) snps / passed; + if (sampleCallRate < SAMPLE_CALL_RATE) { + lowSampleCallRate++; + } + } + + vcfReader.close(); + + } + + public boolean isFiltered(VariantContext vc) { + Set filters = vc.getFilters(); + return vc.isFiltered() && !filters.contains(""PASS"") && !filters.contains(""."") && !filters.contains(""fa""); + } + + @Override + public boolean isFailed() { + return invalidAlleles > 0; + } + + @Override + public List getCounters() { + + List statistics = new Vector(); + + double treeOverlap = (treeHits / (double) variants) * 100; + + statistics.add(new StatisticCounter(""Files"", files.size())); + statistics.add(new StatisticCounter(""Samples"", samples)); + statistics.add(new StatisticCounter(""Input Variants"", lines)); + statistics.add(new StatisticCounter(""Reference Mismatches"", misMatches, 0)); + statistics.add(new StatisticCounter(""Tree Overlap (%)"", treeOverlap)); + statistics.add(new StatisticCounter(""Strand Flips"", strandFlips, 0)); + statistics.add(new StatisticCounter(""Out Of Range Variants"", outOfRange)); + statistics.add(new StatisticCounter(""Multiallelic Variants"", multiallelics)); + statistics.add(new StatisticCounter(""Indel Variants"", indels)); + statistics.add(new StatisticCounter(""VCF Filtered Variants"", filterFlags)); + statistics.add(new StatisticCounter(""Duplicate Variants"", duplicates)); + statistics.add(new StatisticCounter(""Low Sample Call Rate"", lowSampleCallRate,0)); + statistics.add(new StatisticCounter(""Monomorphic Variants"", monomorphics,0)); + // TODO: use VARIANT_CALL_RATE instead of 90% and extract labels to constants + statistics.add(new StatisticCounter(""Variant Call Rate < 90%"", lowVariantCallRate,0)); + + return statistics; + } + + public static boolean isStrandFlip(String reference, String refAlleleSample) { + + if (refAlleleSample.equals(""A"")) { + return reference.equals(""T""); + } else if (refAlleleSample.equals(""T"")) { + return reference.equals(""A""); + } else if (refAlleleSample.equals(""C"")) { + return reference.equals(""G""); + } else if (refAlleleSample.equals(""G"")) { + return reference.equals(""C""); + } + + return false; + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/annotation/AnnotationSettings.java",".java","1289","83","package genepi.haplogrep3.haplogrep.io.annotation; + +import java.util.List; +import java.util.Vector; + +public class AnnotationSettings { + + private String filename; + + private String source; + + private String url; + + private String refAllele; + + private String altAllele; + + private String chr; + + private List properties = new Vector(); + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRefAllele() { + return refAllele; + } + + public void setRefAllele(String refAllele) { + this.refAllele = refAllele; + } + + public String getAltAllele() { + return altAllele; + } + + public void setAltAllele(String altAllele) { + this.altAllele = altAllele; + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public String getChr() { + return chr; + } + + public void setChr(String chr) { + this.chr = chr; + } + + public void init() { + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/annotation/AnnotationColumn.java",".java","650","45","package genepi.haplogrep3.haplogrep.io.annotation; + +public class AnnotationColumn { + + private String name; + + private String column; + + private boolean show = false; + + private String export = null; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColumn() { + return column; + } + + public void setColumn(String column) { + this.column = column; + } + + public void setShow(boolean show) { + this.show = show; + } + + public boolean isShow() { + return show; + } + + public void setExport(String export) { + this.export = export; + } + + public String getExport() { + return export; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/annotation/IndexFileReader.java",".java","2557","113","package genepi.haplogrep3.haplogrep.io.annotation; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.Map; + +import genepi.io.text.LineReader; +import htsjdk.samtools.util.BlockCompressedInputStream; +import htsjdk.tribble.readers.TabixReader; +import htsjdk.tribble.readers.TabixReader.Iterator; + +public class IndexFileReader { + + class Entry { + public long offset; + public int lines; + } + + private Map index = new HashMap(); + + private BlockCompressedInputStream stream; + + public IndexFileReader(String input) throws NumberFormatException, IOException { + readIndex(input + "".index""); + stream = new BlockCompressedInputStream(new File(input)); + } + + protected void readIndex(String file) throws NumberFormatException, IOException { + BlockCompressedInputStream stream = new BlockCompressedInputStream(new File(file)); + int format = readInt(stream); + if (format != IndexFileWriter.INDEX_FORMAT) { + throw new IOException(""File '"" + file + ""' is not a valid index file.""); + } + + long position = readLong(stream); + while (position != -1) { + long offset = readLong(stream); + if (!index.containsKey(position)) { + Entry entry = new Entry(); + entry.offset = offset; + entry.lines = 1; + index.put(position, entry); + } else { + index.get(position).lines++; + } + position = readLong(stream); + } + stream.close(); + } + + public Iterator query(long position) throws IOException { + + Entry entry = index.get(position); + if (entry != null) { + stream.seek(entry.offset); + + return new Iterator() { + + int count = 0; + + @Override + public String next() throws IOException { + if (count < entry.lines) { + count++; + return stream.readLine(); + } else { + return null; + } + } + }; + } else { + + return new Iterator() { + + @Override + public String next() throws IOException { + return null; + } + }; + } + } + + public void close() { + try { + stream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public long readLong(final InputStream is) throws IOException { + final byte[] buf = new byte[8]; + int read = is.read(buf); + if (read == 8) { + return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getLong(); + } else { + return -1; + } + } + + public int readInt(final InputStream is) throws IOException { + byte[] buf = new byte[4]; + is.read(buf); + return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/annotation/AnnotationFileReader.java",".java","2252","91","package genepi.haplogrep3.haplogrep.io.annotation; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import genepi.io.table.reader.CsvTableReader; +import htsjdk.tribble.readers.TabixReader.Iterator; + +public class AnnotationFileReader { + + private IndexFileReader reader; + + private Map columnsIndex = new HashMap(); + + private char separator = '\t'; + + private int indexRef; + + private int indexAlt; + + private String[] buffer; + + public AnnotationFileReader(String input, List columns, boolean comments, String ref, String alt) + throws IOException { + + CsvTableReader tableReader = new CsvTableReader(input, separator, !comments); + + if (!tableReader.hasColumn(ref)) { + throw new IOException(""Column '"" + ref + ""' not found in file '"" + input + ""'""); + } + indexRef = tableReader.getColumnIndex(ref); + + if (!tableReader.hasColumn(alt)) { + throw new IOException(""Column '"" + alt + ""' not found in file '"" + input + ""'""); + } + indexAlt = tableReader.getColumnIndex(alt); + + for (AnnotationColumn column : columns) { + if (!tableReader.hasColumn(column.getColumn())) { + throw new IOException(""Column '"" + column.getColumn() + ""' not found in file '"" + input + ""'""); + } + int index = tableReader.getColumnIndex(column.getColumn()); + columnsIndex.put(column.getColumn(), index); + } + + buffer = new String[tableReader.getColumns().length]; + + tableReader.close(); + + reader = new IndexFileReader(input); + + } + + public Map query(String chr, int position, String ref, String alt) throws IOException { + + Iterator result = reader.query(position); + String line = result.next(); + + while (line != null) { + + buffer = line.split(""\t"", -1); + + String annoRef = buffer[indexRef]; + String annoAlt = buffer[indexAlt]; + + boolean match = (annoRef.equalsIgnoreCase(ref) && annoAlt.equalsIgnoreCase(alt)); + + if (match) { + Map values = new HashMap<>(); + for (String column : columnsIndex.keySet()) { + int index = columnsIndex.get(column); + values.put(column, buffer[index]); + } + return values; + } + + line = result.next(); + + } + + return null; + } + + public void close() { + reader.close(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/haplogrep/io/annotation/IndexFileWriter.java",".java","1314","51","package genepi.haplogrep3.haplogrep.io.annotation; + +import java.io.File; +import java.io.IOException; + +import htsjdk.samtools.util.BlockCompressedInputStream; +import htsjdk.samtools.util.BlockCompressedOutputStream; +import htsjdk.tribble.util.LittleEndianOutputStream; + +public class IndexFileWriter { + + public static final int INDEX_FORMAT = 270685; + + private File file; + + public IndexFileWriter(File file) { + this.file = file; + } + + public void buildIndex(File indexFile, int column, int skip) throws IOException { + + LittleEndianOutputStream output = new LittleEndianOutputStream(new BlockCompressedOutputStream(indexFile)); + output.writeInt(INDEX_FORMAT); + + BlockCompressedInputStream inputstream = new BlockCompressedInputStream(file); + long offset = inputstream.getFilePointer(); + String line = inputstream.readLine(); + + // skip n lines + for (int i = 0; i < skip; i++) { + offset = inputstream.getFilePointer(); + line = inputstream.readLine(); + + } + // write position and offset to index file + while (line != null) { + String[] tiles = line.split(""\t""); + int position = Integer.parseInt(tiles[column - 1]); + output.writeLong(position); + output.writeLong(offset); + offset = inputstream.getFilePointer(); + line = inputstream.readLine(); + + } + inputstream.close(); + output.close(); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/WebApp.java",".java","1811","46","package genepi.haplogrep3.web; + +import genepi.haplogrep3.web.handlers.ContactPageHandler; +import genepi.haplogrep3.web.handlers.ErrorHandler; +import genepi.haplogrep3.web.handlers.IndexPageHandler; +import genepi.haplogrep3.web.handlers.clades.CladesShowHandler; +import genepi.haplogrep3.web.handlers.groups.GroupsShowHandler; +import genepi.haplogrep3.web.handlers.jobs.JobsCreateHandler; +import genepi.haplogrep3.web.handlers.jobs.JobsDownloadHandler; +import genepi.haplogrep3.web.handlers.jobs.JobsShowHandler; +import genepi.haplogrep3.web.handlers.mutations.MutationsShowHandler; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesIndexHandler; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesSearchHandler; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesShowHandler; +import genepi.haplogrep3.web.util.AbstractErrorHandler; +import genepi.haplogrep3.web.util.AbstractWebApp; + +public class WebApp extends AbstractWebApp { + + public WebApp(int port) { + super(port); + } + + protected void routes() { + route(""index"", new IndexPageHandler()); + route(""contact"", new ContactPageHandler()); + route(""jobs_create"", new JobsCreateHandler()); + route(""jobs_show"", new JobsShowHandler()); + route(""jobs_download"", new JobsDownloadHandler()); + route(""phylogenies_index"", new PhylogeniesIndexHandler()); + route(""phylogenies_show"", new PhylogeniesShowHandler()); + route(""phylogenies_search"", new PhylogeniesSearchHandler()); + route(""clades_show"", new CladesShowHandler()); + route(""groups_show"", new GroupsShowHandler()); + route(""mutations_show"", new MutationsShowHandler(false)); + route(""mutations_with_clade_show"", new MutationsShowHandler(true)); + staticFileTemplate(""/app.js""); + } + + @Override + protected AbstractErrorHandler errorHandler() { + return new ErrorHandler(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/AbstractHandler.java",".java","248","13","package genepi.haplogrep3.web.util; + +import io.javalin.http.Handler; +import io.javalin.http.HandlerType; + +public abstract class AbstractHandler implements Handler { + + public abstract HandlerType getType(); + + public abstract String getPath(); + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/ErrorPage.java",".java","731","36","package genepi.haplogrep3.web.util; + +import org.apache.commons.lang.exception.ExceptionUtils; + +import io.javalin.http.Context; + +public class ErrorPage extends Page { + + private static final long serialVersionUID = 1L; + + public static final String TEMPLATE = ""web/error.view.html""; + + public ErrorPage(Context context) { + super(context, TEMPLATE); + put(""stackTrace"", """"); + } + + public void setTitle(String title) { + put(""title"", title); + } + + public void setMessage(String message) { + put(""message"", message); + } + + public void setException(Throwable exception) { + String stackTrace = ExceptionUtils.getStackTrace(exception); + put(""stackTrace"", stackTrace); + } + + public void render() { + this.context.render(template, this); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/BasisTemplateFileRenderer.java",".java","6210","187","package genepi.haplogrep3.web.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.Map; +import java.util.function.Function; + +import com.google.gson.Gson; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.web.WebApp; +import genepi.haplogrep3.web.util.functions.DecimalFunction; +import genepi.haplogrep3.web.util.functions.DoubleFormatFunction; +import genepi.haplogrep3.web.util.functions.FromJsonFunction; +import genepi.haplogrep3.web.util.functions.IncludeScriptFunction; +import genepi.haplogrep3.web.util.functions.IncludeStyleFunction; +import genepi.haplogrep3.web.util.functions.IsRouteActiveFunction; +import genepi.haplogrep3.web.util.functions.NumberFormatFunction; +import genepi.haplogrep3.web.util.functions.PercentageFunction; +import genepi.haplogrep3.web.util.functions.RouteFunction; +import genepi.haplogrep3.web.util.functions.ToJsonFunction; +import genepi.haplogrep3.web.util.functions.ToNumberFunction; +import genepi.haplogrep3.web.util.functions.widgets.PieChartDataFunction; +import genepi.haplogrep3.web.util.functions.widgets.DatatableFunction; +import genepi.haplogrep3.web.util.functions.widgets.PieChartFunction; +import genepi.io.FileUtil; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; +import io.javalin.http.staticfiles.Location; +import io.javalin.plugin.rendering.FileRenderer; +import io.marioslab.basis.template.Error; +import io.marioslab.basis.template.Template; +import io.marioslab.basis.template.TemplateContext; +import io.marioslab.basis.template.TemplateLoader; +import io.marioslab.basis.template.TemplateLoader.CachingTemplateLoader; +import io.marioslab.basis.template.parsing.Span; + +public class BasisTemplateFileRenderer implements FileRenderer { + + private String root; + + private TemplateLoader loader; + + private Location location; + + private AbstractWebApp server; + + private boolean selfContained = false; + + public BasisTemplateFileRenderer() { + this(App.isDevelopmentSystem() ? ""src/main/resources"" : """", + App.isDevelopmentSystem() ? Location.EXTERNAL : Location.CLASSPATH, null); + this.selfContained = true; + } + + public BasisTemplateFileRenderer(String root, Location location, AbstractWebApp server) { + + this.root = root; + this.location = location; + if (location == Location.EXTERNAL) { + loader = new TemplateLoader.FileTemplateLoader(); + } else { + loader = new MyClasspathTemplateLoader(); + } + + this.server = server; + } + + public boolean isSelfContained() { + return selfContained; + } + + public Location getLocation() { + return location; + } + + public String render(String filePath, Map model, Context context) throws Exception { + + // reload external files on every call (hot reloading for development) + if (location == Location.EXTERNAL) { + loader = new TemplateLoader.FileTemplateLoader(); + } else { + loader = new MyClasspathTemplateLoader(); + } + + TemplateContext templateContext = new TemplateContext(); + for (String name : model.keySet()) { + templateContext.set(name, model.get(name)); + } + + // Add default functions + templateContext.set(""percentage"", new PercentageFunction()); + templateContext.set(""toNumber"", new ToNumberFunction()); + templateContext.set(""decimal"", new DecimalFunction()); + templateContext.set(""formatDouble"", new DoubleFormatFunction()); + templateContext.set(""formatNumber"", new NumberFormatFunction()); + templateContext.set(""includeScript"", new IncludeScriptFunction(this)); + templateContext.set(""includeStyle"", new IncludeStyleFunction(this)); + templateContext.set(""json"", new ToJsonFunction()); + templateContext.set(""fromJson"", new FromJsonFunction()); + // widgets + templateContext.set(""datatable"", new DatatableFunction()); + templateContext.set(""piechart"", new PieChartFunction()); + templateContext.set(""piechartData"", new PieChartDataFunction()); + + templateContext.set(""routeUrl"", new RouteFunction(server)); + + if (context != null && server != null && context.handlerType() != HandlerType.BEFORE) { + String path = context.endpointHandlerPath(); + String route = server.getNameByPath(path); + templateContext.set(""route"", route != null ? route : """"); + templateContext.set(""isRouteActive"", new IsRouteActiveFunction(route != null ? route : """")); + } else { + templateContext.set(""route"", """"); + templateContext.set(""isRouteActive"", new Function() { + @Override + public Boolean apply(String arg0) { + return false; + } + }); + } + + templateContext.set(""gson"", new Gson()); + // application specific helper + + try { + Template template = loadTemplate(filePath); + return template.render(templateContext); + } catch (Exception e) { + return ""Error in template '"" + filePath + ""': "" + e.toString(); + } + + } + + public String render(String filePath, Map model) throws Exception { + + return render(filePath, model, null); + + } + + public Template loadTemplate(String path) { + String filename = """"; + if (path.startsWith(""/"")) { + filename = root + path; + } else { + filename = root + ""/"" + path; + } + return loader.load(filename); + } + + /** + * A TemplateLoader to load templates from the classpath. Extended to support + * relative paths with ../ + **/ + public static class MyClasspathTemplateLoader extends CachingTemplateLoader { + @Override + protected Source loadSource(String path) { + try { + + String filename = FileUtil.getFilename(path); + URI uri = URI.create(path); + String resolvedPath = uri.resolve("""").toString() + filename; + + return new Source(path, MyStreamUtils.readString(WebApp.class.getResourceAsStream(resolvedPath))); + } catch (Throwable t) { + t.printStackTrace(); + Error.error(""Couldn't load template '"" + path + ""'."", new Span(new Source(path, "" ""), 0, 0), t); + throw new RuntimeException(""""); // never reached + } + } + } + + static class MyStreamUtils { + private static String readString(InputStream in) throws IOException { + byte[] buffer = new byte[1024 * 10]; + int read = 0; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return new String(out.toByteArray(), ""UTF-8""); + } + } +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/RouteUtil.java",".java","352","18","package genepi.haplogrep3.web.util; + +import java.util.Map; + +public class RouteUtil { + + public static String path(String path, Map params) { + + String replacedPath = path; + for (String key : params.keySet()) { + replacedPath = replacedPath.replaceAll(""\\{"" + key + ""\\}"", params.get(key).toString()); + } + + return replacedPath; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/FileStorage.java",".java","709","29","package genepi.haplogrep3.web.util; + +import java.io.File; +import java.util.List; +import java.util.Vector; + +import io.javalin.core.util.FileUtil; +import io.javalin.http.UploadedFile; + +public class FileStorage { + + public static List store(List uploadedFiles, String location) { + + List files = new Vector(); + for (UploadedFile uploadedFile : uploadedFiles) { + if (uploadedFile.getSize() > 0) { + String cleanFilename = new File(uploadedFile.getFilename()).getName(); + String filename = location + ""/"" + cleanFilename; + FileUtil.streamToFile(uploadedFile.getContent(), filename); + File file = new File(filename); + files.add(file); + } + } + + return files; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/AbstractErrorHandler.java",".java","207","9","package genepi.haplogrep3.web.util; + +import io.javalin.http.ExceptionHandler; +import io.javalin.http.Handler; + +public abstract class AbstractErrorHandler implements Handler, ExceptionHandler { + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/AbstractWebApp.java",".java","3037","119","package genepi.haplogrep3.web.util; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +import genepi.haplogrep3.App; +import io.javalin.Javalin; +import io.javalin.http.Context; +import io.javalin.http.Handler; +import io.javalin.http.HandlerType; +import io.javalin.http.staticfiles.Location; +import io.javalin.http.staticfiles.StaticFileConfig; +import io.javalin.plugin.rendering.JavalinRenderer; + +public abstract class AbstractWebApp { + + private static final String[] VIEW_EXTENSIONS = { "".html"", "".js"" }; + + public static final String ROOT_DIR = ""/web/public""; + + private int port; + + private Javalin server; + + public AbstractWebApp(int port) { + + this.port = port; + + } + + public void start() { + + server = Javalin.create(); + defaultRoutes(); + routes(); + + if (App.isDevelopmentSystem()) { + + // load templates and static files from external files not from classpath + // auto reloading possible, no restart needed, .... + server._conf.addStaticFiles(new Consumer() { + + @Override + public void accept(StaticFileConfig config) { + config.hostedPath = App.getDefault().getConfiguration().getBaseUrl(); + config.directory = ""src/main/resources"" + ROOT_DIR; + config.location = Location.EXTERNAL; + } + }); + JavalinRenderer.register(new BasisTemplateFileRenderer(""src/main/resources"", Location.EXTERNAL, this), + VIEW_EXTENSIONS); + + } else { + server._conf.addStaticFiles(new Consumer() { + + @Override + public void accept(StaticFileConfig config) { + config.hostedPath = App.getDefault().getConfiguration().getBaseUrl(); + config.directory = ROOT_DIR; + config.location = Location.CLASSPATH; + } + }); + JavalinRenderer.register(new BasisTemplateFileRenderer("""", Location.CLASSPATH, this), VIEW_EXTENSIONS); + + } + + server.start(port); + + while (true) { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + } + + protected void defaultRoutes() { + server.error(404, errorHandler()); + server.exception(Exception.class, errorHandler()); + } + + abstract protected AbstractErrorHandler errorHandler(); + + abstract protected void routes(); + + Map namedRoutes = new HashMap(); + Map pathRoutes = new HashMap(); + + public void route(String route, AbstractHandler handler) { + server.addHandler(handler.getType(), handler.getPath(), handler); + namedRoutes.put(route, handler); + pathRoutes.put(handler.getPath(), route); + } + + public void staticFileTemplate(String filename) { + server.addHandler(HandlerType.GET, filename, new Handler() { + + @Override + public void handle(Context context) throws Exception { + String template = ROOT_DIR + filename; + Page page = new Page(context, template); + page.render(); + } + }); + } + + public AbstractHandler getHandlerByName(String name) { + return namedRoutes.get(name); + } + + public String getNameByPath(String path) { + return pathRoutes.get(path); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/Page.java",".java","1069","47","package genepi.haplogrep3.web.util; + +import java.util.HashMap; + +import genepi.haplogrep3.App; +import io.javalin.http.Context; + +public class Page extends HashMap { + + private static final long serialVersionUID = 1L; + + protected Context context; + + protected String template; + + public Page(Context context, String template) { + this(); + this.context = context; + this.template = template; + } + + public Page() { + put(""application"", App.NAME); + put(""version"", App.VERSION); + put(""baseUrl"", App.getDefault().getConfiguration().getBaseUrl()); + put(""url"", App.getDefault().getConfiguration().getUrl()); + put(""configuration"", App.getDefault().getConfiguration()); + put(""debug"", App.isDevelopmentSystem()); + put(""selfContained"", false); + put(""minimal"", false); + } + + public void render() { + + if (context == null) { + throw new RuntimeException(""Rendering of page not possible: no context set.""); + } + + if (template == null) { + throw new RuntimeException(""Rendering of page not possible: no template set.""); + } + + context.render(template, this); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/graph/Node.java",".java","533","41","package genepi.haplogrep3.web.util.graph; + +public class Node { + + private int id; + + private String label; + + private String color = ""white""; + + public Node(int id, String label) { + this.id = id; + this.label = label; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/graph/Edge.java",".java","555","42","package genepi.haplogrep3.web.util.graph; + +public class Edge { + + private int from; + + private int to; + + private String label; + + public Edge(Node from, Node to, String label) { + this.from = from.getId(); + this.to = to.getId(); + this.label = label; + } + + public int getFrom() { + return from; + } + + public void setFrom(int from) { + this.from = from; + } + + public int getTo() { + return to; + } + + public void setTo(int to) { + this.to = to; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/graph/Graph.java",".java","2194","101","package genepi.haplogrep3.web.util.graph; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +public class Graph { + + private String direction = ""TD""; + + private List nodes = new Vector(); + + private List edges = new Vector(); + + private Map nodeIndex = new HashMap(); + + private Set uniqueEdges = new HashSet(); + + public Node addNode(String name) { + Node node = new Node(nodes.size() + 1, name); + nodes.add(node); + nodeIndex.put(name, node); + return node; + } + + public void addEdge(String from, String to, String label) { + if (uniqueEdges.contains(from + ""|"" + to)) { + return; + } + Node fromNode = nodeIndex.get(from); + Node toNode = nodeIndex.get(to); + + if (fromNode == null) { + fromNode = addNode(from); + } + + if (toNode == null) { + toNode = addNode(to); + } + + Edge edge = new Edge(fromNode, toNode, label); + edges.add(edge); + uniqueEdges.add(from + ""|"" + to); + } + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } + + public List getEdges() { + return edges; + } + + public void setEdges(List edges) { + this.edges = edges; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getDirection() { + return direction; + } + + public String toDot(String layout) { + + String quote = ""\""""; + StringBuffer buffer = new StringBuffer(); + buffer.append(""digraph { ""); + buffer.append(""graph ["" + layout + ""]; ""); + buffer.append(""node [shape = box, style=\""rounded,filled\""]; ""); + + for (Node node : nodes) { + buffer.append(node.getId() + "" [label=\"""" + node.getLabel() + ""\"", fillcolor=\"""" + node.getColor() + + ""\""]; ""); + } + + for (Edge edge : edges) { + buffer.append(quote + edge.getFrom() + quote + "" -> "" + quote + edge.getTo() + quote + "" [label="" + quote + + edge.getLabel() + quote + ""] ;""); + } + buffer.append(""}""); + return buffer.toString(); + + } + + public List toList( String padding, Set nodes) { + List result = new Vector(); + return result; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/DoubleFormatFunction.java",".java","537","20","package genepi.haplogrep3.web.util.functions; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; +import java.util.function.Function; + +public class DoubleFormatFunction implements Function { + + public static DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); + public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(""#.##"", symbols); + + @Override + public String apply(Double number) { + + return DECIMAL_FORMAT.format((double) number); + + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/DecimalFunction.java",".java","885","41","package genepi.haplogrep3.web.util.functions; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; +import java.util.function.Function; + +public class DecimalFunction implements Function { + + public static DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); + public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(""###,###,###"", symbols); + + + + @Override + public String apply(Object number) { + + if (number instanceof Integer) { + + return DECIMAL_FORMAT.format( (int) number); + + } else if (number instanceof Long) { + + return DECIMAL_FORMAT.format((long) number); + + } else if (number instanceof Double) { + + return DECIMAL_FORMAT.format((double) number); + + } else if (number instanceof Float) { + + return DECIMAL_FORMAT.format((float) number); + + } else { + + return ""NaN""; + + } + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/RouteFunction.java",".java","829","34","package genepi.haplogrep3.web.util.functions; + +import java.util.Map; +import java.util.function.BiFunction; + +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.AbstractWebApp; +import genepi.haplogrep3.web.util.RouteUtil; + +public class RouteFunction implements BiFunction, String> { + + private AbstractWebApp server; + + public RouteFunction(AbstractWebApp server) { + this.server = server; + } + + @Override + public String apply(String route, Map params) { + + if (server == null) { + return ""Routing not available""; + } + + AbstractHandler handler = server.getHandlerByName(route); + if (handler == null) { + // TODO: throw TemplateEngine Exception + return ""Route '"" + route + ""' not found.""; + } + + return RouteUtil.path(handler.getPath(), params); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/ToJsonFunction.java",".java","844","32","package genepi.haplogrep3.web.util.functions; + +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.util.function.Function; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializer; + +public class ToJsonFunction implements Function { + + private Gson gson = new Gson(); + + public ToJsonFunction() { + + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(Double.class, (JsonSerializer) (src, typeOfSrc, context) -> { + DecimalFormat df = new DecimalFormat(""#.####""); + df.setRoundingMode(RoundingMode.CEILING); + return new JsonPrimitive(Double.parseDouble(df.format(src))); + }); + gson = builder.create(); + } + + @Override + public String apply(Object object) { + return gson.toJson(object); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/ToNumberFunction.java",".java","285","15","package genepi.haplogrep3.web.util.functions; + +import java.util.function.Function; + +public class ToNumberFunction implements Function { + + @Override + public Number apply(Object number) { + + String string = number.toString(); + return Double.parseDouble(string); + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/FromJsonFunction.java",".java","313","16","package genepi.haplogrep3.web.util.functions; + +import java.util.function.Function; + +import com.google.gson.Gson; + +public class FromJsonFunction implements Function { + + private Gson gson = new Gson(); + + @Override + public Object apply(String json) { + return gson.fromJson(json, Object.class); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/IsRouteActiveFunction.java",".java","383","19","package genepi.haplogrep3.web.util.functions; + +import java.util.function.Function; + +public class IsRouteActiveFunction implements Function { + + private String activeRoute; + + public IsRouteActiveFunction(String activeRoute) { + this.activeRoute = activeRoute; + } + + @Override + public Boolean apply(String route ) { + + return activeRoute.equalsIgnoreCase(route); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/PercentageFunction.java",".java","644","30","package genepi.haplogrep3.web.util.functions; +import java.text.DecimalFormat; +import java.util.function.Function; + +public class PercentageFunction implements Function { + + public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(""###.##'%'""); + + @Override + public String apply(Object number) { + + if (number instanceof Double) { + + double percentage = (double) number * 100; + return DECIMAL_FORMAT.format(percentage); + + } else if (number instanceof Float) { + + double percentage = (float) number * 100; + return DECIMAL_FORMAT.format(percentage); + + } else { + + return ""NaN%""; + + } + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/NumberFormatFunction.java",".java","542","20","package genepi.haplogrep3.web.util.functions; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; +import java.util.function.Function; + +public class NumberFormatFunction implements Function { + + public static DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); + public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(""#.########"", symbols); + + @Override + public String apply(Double number) { + + return DECIMAL_FORMAT.format((double) number); + + + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/IncludeScriptFunction.java",".java","1108","38","package genepi.haplogrep3.web.util.functions; + +import java.util.function.Function; + +import genepi.haplogrep3.web.util.AbstractWebApp; +import genepi.haplogrep3.web.util.BasisTemplateFileRenderer; +import io.marioslab.basis.template.Template; +import io.marioslab.basis.template.TemplateContext; + +public class IncludeScriptFunction implements Function { + + private BasisTemplateFileRenderer renderer; + + public IncludeScriptFunction(BasisTemplateFileRenderer renderer) { + this.renderer = renderer; + } + + @Override + public String apply(String url) { + + String src = url; + + if (renderer.isSelfContained() && !isExternalUrl(url)) { + + System.out.println("" Include javascript "" + url + ""...""); + Template template = renderer.loadTemplate(AbstractWebApp.ROOT_DIR + url); + String content = template.render(new TemplateContext()); + src = Base64Util.encodeBase64(""text/javascript"", content); + } + + return """"; + } + + protected boolean isExternalUrl(String url) { + return url.startsWith(""https://"") || url.startsWith(""http://"") || url.startsWith(""http://""); + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/IncludeStyleFunction.java",".java","1120","41","package genepi.haplogrep3.web.util.functions; + +import java.util.function.Function; + +import genepi.haplogrep3.web.util.AbstractWebApp; +import genepi.haplogrep3.web.util.BasisTemplateFileRenderer; +import io.marioslab.basis.template.Template; +import io.marioslab.basis.template.TemplateContext; + +public class IncludeStyleFunction implements Function { + + + + private BasisTemplateFileRenderer renderer; + + public IncludeStyleFunction(BasisTemplateFileRenderer renderer) { + this.renderer = renderer; + } + + @Override + public String apply(String url) { + + String href = url; + + if (renderer.isSelfContained() && !isExternalUrl(url)) { + + System.out.println("" Include stylesheet "" + url + ""...""); + Template template = renderer.loadTemplate(AbstractWebApp.ROOT_DIR + url); + String content = template.render( new TemplateContext()); + href = Base64Util.encodeBase64(""text/css"", content); + } + + return """"; + } + + protected boolean isExternalUrl(String url) { + return url.startsWith(""https://"") || url.startsWith(""http://"") || url.startsWith(""http://""); + } + + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/Base64Util.java",".java","1796","63","package genepi.haplogrep3.web.util.functions; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; + +import io.javalin.core.util.FileUtil; + +public class Base64Util { + + public static byte[] readBytesFromFile(String filename) throws IOException { + FileInputStream in = new FileInputStream(filename); + byte[] bytes = readBytes(in); + in.close(); + return bytes; + } + + public static byte[] readBytesFromClasspath(String path) throws IOException { + String resolvedPath = resolvePath(path); + InputStream in = FileUtil.class.getResourceAsStream(resolvedPath); + byte[] bytes = readBytes(in); + in.close(); + return bytes; + } + + public static String readString(InputStream in) throws IOException { + byte[] buffer = new byte[1024 * 10]; + int read = 0; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return new String(out.toByteArray(), ""UTF-8""); + } + + public static byte[] readBytes(InputStream in) throws IOException { + byte[] targetArray = new byte[in.available()]; + in.read(targetArray); + return targetArray; + } + + public static String encodeBase64(String mimeType, String content) { + return encodeBase64(mimeType, content.getBytes()); + } + + public static String encodeBase64(String mimeType, byte[] bytes) { + String encodedContent = java.util.Base64.getEncoder().encodeToString(bytes); + String data = ""data:"" + mimeType + "";base64,"" + encodedContent; + return data; + } + + public static String resolvePath(String path) { + String filename = new File(path).getName(); + URI uri = URI.create(path); + String resolvedPath = uri.resolve("""").toString() + filename; + return resolvedPath; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/widgets/PieChartData.java",".java","849","45","package genepi.haplogrep3.web.util.functions.widgets; + +import java.util.List; +import java.util.Vector; + +public class PieChartData { + + private List labels = new Vector(); + + private List values = new Vector(); + + private List colors = new Vector(); + + public PieChartData(List labels, List values, List colors) { + this.labels = labels; + this.values = values; + this.colors = colors; + } + + public List getLabels() { + return labels; + } + + public void setLabels(List labels) { + this.labels = labels; + } + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + public List getColors() { + return colors; + } + + public void setColors(List colors) { + this.colors = colors; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/widgets/PieChartFunction.java",".java","1445","54","package genepi.haplogrep3.web.util.functions.widgets; + +import java.util.function.BiFunction; + +import com.google.gson.Gson; + +public class PieChartFunction implements BiFunction { + + private Gson gson = new Gson(); + + @Override + public String apply(String id, PieChartData data) { + + if (data == null) { + return """"; + } + + try { + StringBuffer code = new StringBuffer(); + code.append(""var data = {""); + code.append(""labels: "" + gson.toJson(data.getLabels()) + "",""); + code.append(""datasets: [{""); + code.append(""label: 'Samples',""); + code.append(""data: "" + gson.toJson(data.getValues()) + "",""); + code.append(""backgroundColor: "" + gson.toJson(data.getColors())); + code.append(""}]""); + code.append(""};""); + code.append(""var config = {""); + code.append(""type: 'doughnut',""); + code.append(""data: data,""); + code.append(""options: {""); + code.append(""plugins: {""); + code.append(""legend: {""); + code.append(""position: 'right', labels:{boxWidth: 20}""); + code.append(""}""); + code.append(""},""); + code.append(""animation: {""); + code.append(""animateRotate: false""); + code.append(""}""); + code.append(""},""); + code.append(""responsive: true,""); + code.append(""maintainAspectRatio: false""); + code.append(""};""); + + code.append(""chart = new Chart(document.getElementById('"" + id + ""'), config);""); + + return code.toString(); + } catch (Exception e) { + e.printStackTrace(); + return """"; + } + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/widgets/PieChartDataFunction.java",".java","1348","54","package genepi.haplogrep3.web.util.functions.widgets; + +import java.util.List; +import java.util.TreeMap; +import java.util.Vector; +import java.util.function.BiFunction; + +import com.google.gson.Gson; + +import genepi.haplogrep3.model.Cluster; +import genepi.haplogrep3.model.Phylotree; + +public class PieChartDataFunction implements BiFunction { + + private Gson gson = new Gson(); + + @Override + public Object apply(String jsonList, Phylotree phylotree) { + + if (jsonList == null || jsonList.trim().isEmpty()) { + return null; + } + + List> list = gson.fromJson(jsonList, List.class); + + List labels = new Vector(); + List values = new Vector(); + List colors = new Vector(); + + // add to treemap to sort by label name + TreeMap map = new TreeMap(); + for (List pair : list) { + map.put(pair.get(0), pair.get(1)); + } + for (Object label : map.keySet()) { + labels.add(label); + values.add(map.get(label)); + if (phylotree.hasClusters()) { + Cluster cluster = phylotree.getClusterByLabel(label.toString()); + if (cluster != null) { + colors.add(cluster.getColor()); + } else { + colors.add(""#000000""); + } + } else { + colors.add(""#000000""); + } + } + + return new PieChartData(labels, values, colors); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/util/functions/widgets/DatatableFunction.java",".java","899","34","package genepi.haplogrep3.web.util.functions.widgets; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import java.util.function.BiFunction; + +import com.google.gson.Gson; + +public class DatatableFunction implements BiFunction { + + + private Gson gson = new Gson(); + + @Override + public String apply(String id, String jsonList) { + + List> list = gson.fromJson(jsonList, List.class); + + List> values = new Vector<>(); + for (List pair: list) { + Map item = new HashMap<>(); + item.put(""k"", pair.get(0)); + item.put(""v"", pair.get(1)); + values.add(item); + } + + String config = ""{paging: false, info: false, searching: false, columns: [{data: 'k'},{data: 'v'}], data: "" + gson.toJson(values) + ""}""; + + return ""$('#"" + id + ""').DataTable("" + config + "");""; + } + +}","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/ErrorHandler.java",".java","862","37","package genepi.haplogrep3.web.handlers; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.web.util.AbstractErrorHandler; +import genepi.haplogrep3.web.util.ErrorPage; +import io.javalin.http.Context; + +public class ErrorHandler extends AbstractErrorHandler { + + public void handle(Context context) throws Exception { + + ErrorPage page = new ErrorPage(context); + page.setTitle(""Error 404""); + page.setMessage(""Page not found.""); + page.render(); + + } + + public void handle(Exception exception, Context context) { + + ErrorPage page = new ErrorPage(context); + page.setTitle(""Error""); + if (exception.getMessage() != null) { + page.setMessage(exception.getMessage()); + } else { + page.setMessage(null); + page.setMessage(exception.getStackTrace().toString()); + } + if (App.isDevelopmentSystem()) { + page.setException(exception); + } + page.render(); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/ContactPageHandler.java",".java","857","38","package genepi.haplogrep3.web.handlers; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class ContactPageHandler extends AbstractHandler { + + public static final String PATH = ""/contact""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/contact.view.html""; + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + Page page = new Page(context, TEMPLATE); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/IndexPageHandler.java",".java","1216","46","package genepi.haplogrep3.web.handlers; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class IndexPageHandler extends AbstractHandler { + + public static final String PATH = ""/""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/index.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + Page page = new Page(context, TEMPLATE); + page.put(""categories"", treeRepository.getCategories()); + page.put(""trees"", treeRepository); + page.put(""examples"", configuration.getExamples()); + page.put(""distances"", Distance.values()); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/clades/CladesShowHandler.java",".java","2747","85","package genepi.haplogrep3.web.handlers.clades; + +import java.util.List; +import java.util.Vector; + +import core.Haplogroup; +import core.Polymorphism; +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationColumn; +import genepi.haplogrep3.model.AnnotatedPolymorphism; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.AnnotationTask; +import genepi.haplogrep3.tasks.PhylotreeGraphBuilder; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesIndexHandler; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import genepi.haplogrep3.web.util.graph.Graph; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class CladesShowHandler extends AbstractHandler { + + public static final String PATH = PhylogeniesIndexHandler.PATH + ""/{phylotree}/haplogroups/{clade}""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/clades/show.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + String phylotreeId = context.pathParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + String clade = context.pathParam(""clade""); + Haplogroup haplogroup = phylotree.getHaplogroup(clade); + if (haplogroup == null) { + throw new Exception(""Clade "" + clade + "" not found.""); + } + + String cluster = """"; + if (phylotree.hasClusters()) { + cluster = phylotree.getNearestCluster(phylotree.getClusters(), clade); + } + + List polymorphisms = phylotree.getPolymorphisms(haplogroup); + AnnotationTask annotationTask = new AnnotationTask(null, phylotree); + annotationTask.loadFiles(); + List annotatedPolymorphisms = annotationTask.getAminoAcidsFromPolys(polymorphisms, null); + + Graph graph = PhylotreeGraphBuilder.buildGraph(phylotree, haplogroup.toString()); + + phylotree.annotate(annotatedPolymorphisms); + + Page page = new Page(context, TEMPLATE); + page.put(""tree"", phylotree); + page.put(""cluster"", cluster); + page.put(""clade"", haplogroup); + page.put(""annotations"", phylotree.getAnnotations()); + page.put(""polymorphisms"", annotatedPolymorphisms); + page.put(""graph"", graph); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/mutations/MutationsShowHandler.java",".java","4252","130","package genepi.haplogrep3.web.handlers.mutations; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationFileReader; +import genepi.haplogrep3.haplogrep.io.annotation.AnnotationSettings; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesIndexHandler; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.BasisTemplateFileRenderer; +import genepi.haplogrep3.web.util.Page; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; +import io.javalin.http.staticfiles.Location; + +public class MutationsShowHandler extends AbstractHandler { + + public static final String PATH = PhylogeniesIndexHandler.PATH + ""/{phylotree}/mutations/{pos}_{ref}_{alt}""; + + public static final String PATH_WITH_HAPLOGROUP = PhylogeniesIndexHandler.PATH + + ""/{phylotree}/haplogroups/{clade}/mutations/{pos}_{ref}_{alt}""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/mutations/show.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + private boolean withClade = false; + + public MutationsShowHandler(boolean withClade) { + this.withClade = withClade; + } + + public void handle(Context context) throws Exception { + + String phylotreeId = context.pathParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + String posString = context.pathParam(""pos""); + String ref = context.pathParam(""ref""); + String alt = context.pathParam(""alt""); + String minimalQueryParam = context.queryParam(""minimal""); + + boolean minimal = (minimalQueryParam != null) && (minimalQueryParam.equalsIgnoreCase(""true"")); + + int pos = Integer.parseInt(posString); + + Map values = new HashMap(); + for (AnnotationSettings annotation : phylotree.getAnnotations()) { + if (phylotree.getAnnotations() != null) { + AnnotationFileReader reader = new AnnotationFileReader(annotation.getFilename(), + annotation.getProperties(), true, annotation.getRefAllele(), annotation.getAltAllele()); + Map result = reader.query(annotation.getChr(), pos, ref, alt); + if (result != null) { + values.putAll(result); + } + reader.close(); + } + } + + String details = ""No annotations found""; + if (phylotree.getTemplate() != null) { + File template = new File(phylotree.getTemplate()); + + if (!template.exists()) { + throw new IOException(""Template file '"" + template.getAbsolutePath() + ""' not found.""); + } + + BasisTemplateFileRenderer render = new BasisTemplateFileRenderer(template.getParentFile().getAbsolutePath(), + Location.EXTERNAL, null); + Map model = new HashMap(); + model.put(""annotations"", values); + model.put(""position"", pos); + model.put(""ref"", ref); + model.put(""alt"", alt); + model.put(""reference"", phylotree.getCategory()); + model.put(""phylotree"", phylotree.getName() + "" ("" + phylotree.getVersion() + "")""); + model.put(""minimal"", minimal); + model.put(""tree"", phylotree); + details = render.render(template.getName(), model); + } + + Page page = new Page(context, TEMPLATE); + page.put(""tree"", phylotree); + page.put(""mutation"", pos + "" ("" + ref + "">"" + alt + "")""); + page.put(""details"", details); + page.put(""values"", values); + page.put(""position"", pos); + page.put(""ref"", ref); + page.put(""alt"", alt); + + if (withClade) { + String haplogroup = context.pathParam(""clade""); + page.put(""clade"", haplogroup); + } else { + page.put(""clade"", """"); + } + page.put(""minimal"", minimal); + page.render(); + + } + + @Override + public String getPath() { + if (withClade) { + return configuration.getBaseUrl() + PATH_WITH_HAPLOGROUP; + } else { + return configuration.getBaseUrl() + PATH; + } + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/phylogenies/PhylogeniesIndexHandler.java",".java","1120","43","package genepi.haplogrep3.web.handlers.phylogenies; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class PhylogeniesIndexHandler extends AbstractHandler { + + public static final String PATH = ""/phylogenies""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/phylogenies/index.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + Page page = new Page(context, TEMPLATE); + page.put(""categories"", treeRepository.getCategories()); + page.put(""trees"", treeRepository); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/phylogenies/PhylogeniesShowHandler.java",".java","1392","49","package genepi.haplogrep3.web.handlers.phylogenies; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class PhylogeniesShowHandler extends AbstractHandler { + + public static final String PATH = PhylogeniesIndexHandler.PATH + ""/{phylotree}""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/phylogenies/show.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + String phylotreeId = context.pathParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + Page page = new Page(context, TEMPLATE); + page.put(""tree"", phylotree); + page.put(""clades"", phylotree.getHaplogroups()); + page.render(); + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/phylogenies/PhylogeniesSearchHandler.java",".java","2551","86","package genepi.haplogrep3.web.handlers.phylogenies; + +import java.util.HashMap; +import java.util.Map; + +import core.Haplogroup; +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.web.handlers.clades.CladesShowHandler; +import genepi.haplogrep3.web.handlers.mutations.MutationsShowHandler; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import genepi.haplogrep3.web.util.RouteUtil; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class PhylogeniesSearchHandler extends AbstractHandler { + + public static final String PATH = PhylogeniesIndexHandler.PATH + ""/{phylotree}/search""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/phylogenies/search.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + String phylotreeId = context.pathParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + String query = context.queryParam(""query""); + + Haplogroup haplogroup = phylotree.getHaplogroup(query); + if (haplogroup != null) { + Map params = new HashMap<>(); + params.put(""phylotree"", phylotree.getIdWithVersion()); + params.put(""clade"", haplogroup.toString()); + String path = RouteUtil.path(CladesShowHandler.PATH, params); + context.redirect(path); + return; + } + + String[] tiles = query.split(""-""); + if (tiles.length != 3) { + tiles = query.split("" ""); + } + if (tiles.length == 3) { + //TODO: check if pos is integer, ref und alt... + Map params = new HashMap<>(); + params.put(""phylotree"", phylotree.getIdWithVersion()); + params.put(""pos"", tiles[0]); + params.put(""ref"", tiles[1]); + params.put(""alt"", tiles[2]); + String path = RouteUtil.path(MutationsShowHandler.PATH, params); + context.redirect(path); + return; + } + + + Page page = new Page(context, TEMPLATE); + page.put(""tree"", phylotree); + page.put(""clades"", phylotree.getHaplogroups()); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/jobs/JobsDownloadHandler.java",".java","1270","53","package genepi.haplogrep3.web.handlers.jobs; + +import java.io.File; +import java.io.FileInputStream; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.io.FileUtil; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class JobsDownloadHandler extends AbstractHandler { + + public static final String PATH = ""/jobs/{job}/{file}""; + + public static final HandlerType TYPE = HandlerType.GET; + + private Configuration configuration = App.getDefault().getConfiguration(); + + private String workspace = configuration.getWorkspace(); + + public void handle(Context context) throws Exception { + + String job = context.pathParam(""job""); + String cleanJob = new File(job).getName(); + + String fileId = context.pathParam(""file""); + String cleanFileId = new File(fileId).getName(); + + String filename = FileUtil.path(workspace, cleanJob, cleanFileId); + File file = new File(filename); + + if (file.exists()) { + context.result(new FileInputStream(file)); + } else { + throw new Exception(""Job or file not found.""); + } + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/jobs/JobsShowHandler.java",".java","2099","80","package genepi.haplogrep3.web.handlers.jobs; + +import java.io.File; +import java.io.FileReader; +import java.util.Date; + +import com.google.gson.Gson; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.Job; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import genepi.io.FileUtil; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class JobsShowHandler extends AbstractHandler { + + public static final String PATH = ""/jobs/{job}""; + + public static final HandlerType TYPE = HandlerType.GET; + + private Configuration configuration = App.getDefault().getConfiguration(); + + private String workspace = configuration.getWorkspace(); + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + public void handle(Context context) throws Exception { + + String jobId = context.pathParam(""job""); + String cleanName = new File(jobId).getName(); + + String filename = FileUtil.path(workspace, cleanName + "".json""); + File jobFile = new File(filename); + + if (jobFile.exists()) { + + Gson gson = new Gson(); + + Job job = gson.fromJson(new FileReader(jobFile), Job.class); + Date now = new Date(); + if (now.after(job.getExpiresOn())) { + throw new Exception(""Job expired.""); + } + + Phylotree phylotree = treeRepository.getById(job.getPhylotree()); + + String template = ""web/jobs/show."" + job.getStatus().name().toLowerCase() + "".view.html""; + + Page page = new Page(context, template); + page.put(""job"", job); + page.put(""genes"", phylotree.getGenes()); + page.put(""phylotree"", phylotree); + + String clades = FileUtil.path(workspace, cleanName, ""clades.json""); + page.put(""clades"", FileUtil.readFileAsString(clades)); + page.render(); + + } else { + throw new Exception(""Job not found.""); + } + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/jobs/JobsCreateHandler.java",".java","5735","185","package genepi.haplogrep3.web.handlers.jobs; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.apache.commons.lang.RandomStringUtils; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Dataset; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.Job; +import genepi.haplogrep3.tasks.JobQueue; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.FileStorage; +import genepi.haplogrep3.web.util.RouteUtil; +import genepi.io.FileUtil; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; +import io.javalin.http.UploadedFile; + +public class JobsCreateHandler extends AbstractHandler { + + public static final String PATH = ""/jobs""; + + public static final HandlerType TYPE = HandlerType.POST; + + public static final String TEMPLATE = ""web/results.json.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + private JobQueue jobQueue = App.getDefault().getJobQueue(); + + private String workspace = configuration.getWorkspace(); + + public void handle(Context context) throws Exception { + + if (!context.isMultipartFormData()) { + throw new Exception(""Uploaded data is not multipart form data.""); + } + + String phylotreeId = context.formParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + String dataset = context.formParam(""dataset""); + + String chipParam = context.formParam(""chip""); + boolean chip = false; + if (chipParam != null) { + chip = chipParam.equalsIgnoreCase(""true""); + } + + String hetLevelParam = context.formParam(""hetLevel""); + double hetLevel = 0.9; + if (hetLevelParam != null) { + hetLevel = Double.parseDouble(hetLevelParam); + } + + if (!(hetLevel >= 0 && hetLevel <= 1)) { + throw new Exception(""Invalid value for hetLevel. (value: "" + hetLevel + "")""); + } + + String distanceParam = context.formParam(""distance""); + Distance distance = Distance.KULCZYNSKI; + if (distanceParam != null) { + distance = Distance.valueOf(distanceParam); + } + + String additionalOutputParam = context.formParam(""additional-output""); + boolean additionalOutput = false; + if (additionalOutputParam != null) { + additionalOutput = additionalOutputParam.equalsIgnoreCase(""true""); + } + + Job job = null; + if (dataset == null) { + List uploadedFiles = context.uploadedFiles(""files""); + job = createJobFromUploadedFiles(phylotree, uploadedFiles, chip, hetLevel, distance, additionalOutput); + } else { + job = createJobFromDataset(phylotree, dataset); + } + + jobQueue.submit(job); + + Map params = new HashMap(); + params.put(""job"", job.getId()); + String path = RouteUtil.path(configuration.getBaseUrl() + JobsShowHandler.PATH, params); + + context.redirect(path); + + } + + public Job createJobFromUploadedFiles(Phylotree phylotree, List uploadedFiles, boolean chip, + double hetLevel, Distance distance, boolean additionalOutput) throws Exception { + + // check min 1 file uploaded and no empty files + boolean emptyFiles = true; + for (UploadedFile uploadedFile : uploadedFiles) { + if (uploadedFile.getSize() > 0) { + emptyFiles = false; + } + } + + if (emptyFiles) { + throw new Exception(""No files uploaded.""); + } + + // check max upload size + for (UploadedFile uploadedFile : uploadedFiles) { + if (uploadedFile.getSize() > configuration.getMaxUploadSizeMb() * 1024 * 1024) { + throw new Exception(""Maximal upload limit of "" + configuration.getMaxUploadSizeMb() + "" MB excited.""); + } + } + + String jobId = RandomStringUtils.randomAlphanumeric(configuration.getJobIdLength()); + while (new File(FileUtil.path(workspace, jobId + "".json"")).exists()) { + jobId = RandomStringUtils.randomAlphanumeric(configuration.getJobIdLength()); + } + + String jobDirectory = FileUtil.path(workspace, jobId); + FileUtil.createDirectory(jobDirectory); + + // store uploaded files + String dataDirectory = FileUtil.path(jobDirectory, ""data""); + FileUtil.createDirectory(dataDirectory); + List files = FileStorage.store(uploadedFiles, dataDirectory); + + return Job.create(jobId, workspace, phylotree, files, distance, chip, hetLevel, additionalOutput); + + } + + public Job createJobFromDataset(Phylotree phylotree, String id) throws Exception { + + Dataset dataset = configuration.getExampleById(id); + + if (dataset == null) { + throw new Exception(""Example '"" + id + ""' not found.""); + } + + File file = new File(dataset.getFile()); + if (!file.exists()) { + throw new Exception(""File '"" + file.getAbsolutePath() + ""' not found.""); + } + + String jobId = RandomStringUtils.randomAlphanumeric(configuration.getJobIdLength()); + while (new File(FileUtil.path(workspace, jobId + "".json"")).exists()) { + jobId = RandomStringUtils.randomAlphanumeric(configuration.getJobIdLength()); + } + + String jobDirectory = FileUtil.path(workspace, jobId); + FileUtil.createDirectory(jobDirectory); + + String dataDirectory = FileUtil.path(jobDirectory, ""data""); + FileUtil.createDirectory(dataDirectory); + + List files = new Vector(); + files.add(file); + + return Job.create(jobId, workspace, phylotree, files, Distance.KULCZYNSKI, dataset.isChip(), 0.9, + dataset.isAdditionalOutput()); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/web/handlers/groups/GroupsShowHandler.java",".java","2277","77","package genepi.haplogrep3.web.handlers.groups; + +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.model.Cluster; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; +import genepi.haplogrep3.tasks.PhylotreeGraphBuilder; +import genepi.haplogrep3.web.handlers.phylogenies.PhylogeniesIndexHandler; +import genepi.haplogrep3.web.util.AbstractHandler; +import genepi.haplogrep3.web.util.Page; +import genepi.haplogrep3.web.util.graph.Graph; +import io.javalin.http.Context; +import io.javalin.http.HandlerType; + +public class GroupsShowHandler extends AbstractHandler { + + public static final String PATH = PhylogeniesIndexHandler.PATH + ""/{phylotree}/clusters/{label}""; + + public static final HandlerType TYPE = HandlerType.GET; + + public static final String TEMPLATE = ""web/groups/show.view.html""; + + private PhylotreeRepository treeRepository = App.getDefault().getTreeRepository(); + + private Configuration configuration = App.getDefault().getConfiguration(); + + public void handle(Context context) throws Exception { + + String phylotreeId = context.pathParam(""phylotree""); + Phylotree phylotree = treeRepository.getById(phylotreeId); + if (phylotree == null) { + throw new Exception(""Phylotree "" + phylotreeId + "" not found.""); + } + + String label = context.pathParam(""label""); + + Cluster cluster = phylotree.getClusterByLabel(label); + if (cluster == null) { + throw new Exception(""Cluster "" + label + "" not found.""); + } + + Set haplogroups = phylotree.getHaplogroupsByCluster(cluster); + for (String node: cluster.getNodes()) { + haplogroups.add(node); + } + Graph graph = PhylotreeGraphBuilder.build(phylotree, haplogroups); + + List sortedHaplogroups = new Vector(haplogroups); + Collections.sort(sortedHaplogroups); + + Page page = new Page(context, TEMPLATE); + page.put(""tree"", phylotree); + page.put(""cluster"", cluster); + page.put(""clades"", sortedHaplogroups); + page.put(""graph"", graph); + page.render(); + + } + + @Override + public String getPath() { + return configuration.getBaseUrl() + PATH; + } + + @Override + public HandlerType getType() { + return TYPE; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/config/Configuration.java",".java","3614","179","package genepi.haplogrep3.config; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.Vector; + +import com.esotericsoftware.yamlbeans.YamlReader; +import com.esotericsoftware.yamlbeans.YamlWriter; + +import genepi.haplogrep3.App; +import genepi.haplogrep3.model.Dataset; + +public class Configuration { + + private int port = App.PORT; + + private int maxUploadSizeMb = 200; + + private List phylotrees; + + private String workspace = ""jobs""; + + private int jobIdLength = 50; + + private int threads = 2; + + private List examples = new Vector(); + + private List repositories = new Vector(); + + private String baseUrl = """"; + + private String url = """"; + + private List navbar = new Vector(); + + private String parent = """"; + + private File configFile; + + public Configuration() { + + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public int getMaxUploadSizeMb() { + return maxUploadSizeMb; + } + + public void setMaxUploadSizeMb(int maxUploadSizeMb) { + this.maxUploadSizeMb = maxUploadSizeMb; + } + + public List getPhylotrees() { + return phylotrees; + } + + public void setPhylotrees(List phylotrees) { + this.phylotrees = phylotrees; + } + + public void setWorkspace(String workspace) { + this.workspace = workspace; + } + + public String getWorkspace() { + return workspace; + } + + public int getJobIdLength() { + return jobIdLength; + } + + public void setJobIdLength(int jobIdLength) { + this.jobIdLength = jobIdLength; + } + + public int getThreads() { + return threads; + } + + public void setThreads(int threads) { + this.threads = threads; + } + + public List getExamples() { + return examples; + } + + public Dataset getExampleById(String id) { + for (Dataset dataset : examples) { + if (dataset.getId().equals(id)) { + return dataset; + } + } + return null; + } + + public void setExamples(List examples) { + this.examples = examples; + } + + public void setRepositories(List repositories) { + this.repositories = repositories; + } + + public List getRepositories() { + return repositories; + } + + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + public String getBaseUrl() { + return baseUrl; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUrl() { + return url; + } + + public List getNavbar() { + return navbar; + } + + public void setNavbar(List navbar) { + this.navbar = navbar; + } + + public static Configuration loadFromFile(File file, String parent) throws IOException { + + YamlReader reader = new YamlReader(new FileReader(file)); + reader.getConfig().setPropertyElementType(Configuration.class, ""phylotrees"", String.class); + reader.getConfig().setPropertyElementType(Configuration.class, ""examples"", Dataset.class); + Configuration configuration = reader.read(Configuration.class); + reader.close(); + + configuration.parent = parent; + configuration.configFile = file; + + for (Dataset dataset : configuration.getExamples()) { + dataset.updateParent(parent); + } + + return configuration; + + } + + public void save() throws IOException { + YamlWriter writer = new YamlWriter(new FileWriter(configFile)); + writer.getConfig().setPropertyElementType(Configuration.class, ""phylotrees"", String.class); + writer.getConfig().setPropertyElementType(Configuration.class, ""examples"", Dataset.class); + writer.write(this); + writer.close(); + + } + + public File getPluginsLocation() { + return new File(parent, ""trees""); + } + + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/main/java/genepi/haplogrep3/config/NavbarLink.java",".java","444","36","package genepi.haplogrep3.config; + +public class NavbarLink { + + private String text; + + private String url; + + private String icon; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/test/java/genepi/haplogrep3/commands/ClassifyCommandTest.java",".java","7246","238","package genepi.haplogrep3.commands; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashSet; + +import org.junit.Test; + +import genepi.io.FileUtil; +import genepi.io.table.reader.CsvTableReader; + +public class ClassifyCommandTest { + + public static String PHYLOTREE = ""phylotree-fu-rcrs@1.0""; + + @Test + public void testWithHsd() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/hsd/H100.hsd""; + command.phylotreeId = PHYLOTREE; + command.output = FileUtil.path(output, ""H100.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.txt""))); + } + + @Test + public void testWithHsdNoFoundSampleVariants() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/hsd/R.hsd""; + command.phylotreeId = PHYLOTREE; + command.output = FileUtil.path(output, ""R.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/R/R.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""R.txt""))); + } + + @Test + public void testWithFasta() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/fasta/H100.fasta""; + command.phylotreeId = PHYLOTREE; + command.output = FileUtil.path(output, ""H100.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.HM625681.1.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.txt""))); + } + + @Test + public void testWithHsdAndHits() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/hsd/H100.hsd""; + command.phylotreeId = PHYLOTREE; + command.hits = 10; + command.output = FileUtil.path(output, ""H100.10.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.10.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.10.txt""))); + } + + @Test + public void testWithHsdAndFastaOutput() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/hsd/H100.hsd""; + command.phylotreeId = PHYLOTREE; + command.writeFasta = true; + command.output = FileUtil.path(output, ""H100.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.txt""))); + + // Reference is now loaded from fasta --> sequence is uppercase. In + // haplogrep-cmd it was lowercase. + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.fasta"").toUpperCase(), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.fasta"")).toUpperCase()); + } + + @Test + public void testFastaWithAlignmentRules() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/fasta/InsertionTest3.fasta""; + command.phylotreeId = PHYLOTREE; + command.writeFasta = true; + command.extendedReport = true; + command.output = FileUtil.path(output, ""InsertionTest3.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + + CsvTableReader reader = new CsvTableReader(FileUtil.path(output, ""InsertionTest3.txt""), '\t'); + assertTrue(reader.next()); + HashSet set = new HashSet(); + + for (String polymorphism : reader.getString(""Input_Sample"").split("" "")) { + set.add(polymorphism); + } + assertFalse(reader.next()); + reader.close(); + + assertFalse(set.contains(""309.1CCT"")); + assertTrue(set.contains(""309.1C"")); + assertTrue(set.contains(""309.2C"")); + assertTrue(set.contains(""315.1C"")); + } + + @Test + public void testFastaWithoutAlignmentRules() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/fasta/InsertionTest3.fasta""; + command.phylotreeId = PHYLOTREE; + command.writeFasta = true; + command.extendedReport = true; + command.skipAlignmentRules = true; + command.output = FileUtil.path(output, ""InsertionTest3.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + + CsvTableReader reader = new CsvTableReader(FileUtil.path(output, ""InsertionTest3.txt""), '\t'); + assertTrue(reader.next()); + HashSet set = new HashSet(); + + for (String polymorphism : reader.getString(""Input_Sample"").split("" "")) { + set.add(polymorphism); + } + assertFalse(reader.next()); + reader.close(); + + assertTrue(set.contains(""309.1CCT"")); + assertFalse(set.contains(""309.1C"")); + assertFalse(set.contains(""309.2C"")); + assertFalse(set.contains(""315.1C"")); + } + + @Test + public void testWithHsdAndQualityControlOutput() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/hsd/H100.hsd""; + command.phylotreeId = PHYLOTREE; + command.writeQc = true; + command.output = FileUtil.path(output, ""H100.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.txt""))); + + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.qc.txt"").replaceAll(""\\."", "",""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.qc.txt"")).replaceAll(""\\."", "","")); + + } + + @Test + public void testWithFastaAndQualityControlOutput() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClassifyCommand command = new ClassifyCommand(); + command.input = ""test-data/fasta/H100.fasta""; + command.phylotreeId = PHYLOTREE; + command.writeQc = true; + command.output = FileUtil.path(output, ""H100.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.HM625681.1.txt""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.txt""))); + + assertEquals(FileUtil.readFileAsString(""test-data/expected/H100/H100.HM625681.1.qc.txt"").replaceAll(""\\."", "",""), + FileUtil.readFileAsString(FileUtil.path(output, ""H100.qc.txt"")).replaceAll(""\\."", "","")); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/test/java/genepi/haplogrep3/commands/AnnotationIndexFileCommandTest.java",".java","442","18","package genepi.haplogrep3.commands; + +import org.junit.Test; + +public class AnnotationIndexFileCommandTest { + + + @Test + public void testWithHsd() throws Exception { + AnnotationIndexCommand command = new AnnotationIndexCommand(); + command.setFile(""/Users/lukfor/Development/git/phylotree-fu-rcrs/src/annotations/gnomad.genomes.v3.1.sites.chrM.reduced_annotations.tsv.gz""); + command.setSkip(1); + command.setStart(2); + command.call(); + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/test/java/genepi/haplogrep3/commands/ClusterHaplogroupsCommandTest.java",".java","799","36","package genepi.haplogrep3.commands; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashSet; + +import org.junit.Test; + +import genepi.io.FileUtil; +import genepi.io.table.reader.CsvTableReader; + +public class ClusterHaplogroupsCommandTest { + + public static String PHYLOTREE = ""phylotree-fu-rcrs@1.0""; + + @Test + public void testClusteringPhylotreeFU() throws Exception { + + String output = ""test-output""; + FileUtil.deleteDirectory(output); + FileUtil.createDirectory(output); + + ClusterHaplogroupsCommand command = new ClusterHaplogroupsCommand(); + command.tree = PHYLOTREE; + command.output = FileUtil.path(output, ""test.txt""); + + int exitCode = command.call(); + + assertEquals(0, exitCode); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","src/test/java/genepi/haplogrep3/tasks/ClassificationTaskTest.java",".java","9839","307","package genepi.haplogrep3.tasks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import genepi.haplogrep3.config.Configuration; +import genepi.haplogrep3.haplogrep.io.readers.impl.StatisticCounterType; +import genepi.haplogrep3.model.AnnotatedSample; +import genepi.haplogrep3.model.Distance; +import genepi.haplogrep3.model.Phylotree; +import genepi.haplogrep3.model.PhylotreeRepository; + +public class ClassificationTaskTest { + + public static String CONFIG_FILE = ""haplogrep3.yaml""; + + public static String PHYLOTREE = ""phylotree-rcrs@17.0""; + + public Phylotree loadPhylotree(String id) throws FileNotFoundException, IOException { + PhylotreeRepository repository = new PhylotreeRepository(); + Configuration configuration = Configuration.loadFromFile(new File(CONFIG_FILE), "".""); + repository.loadFromConfiguration(configuration); + return repository.getById(id); + } + + @Test + public void testWithHsd() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/hsd/H100.hsd"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""Sample1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + } + + @Test + public void testWithPhylotreeRSRS() throws Exception { + + String tree = ""phylotree-rsrs@17.0""; + + Phylotree phylotree = loadPhylotree(tree); + + List files = new ArrayList(); + files.add(new File(""test-data/fasta/H100.fasta"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""HM625681.1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + // this H100 sample expects 51 variants according RSRS + assertEquals(51, firstSample.getAnnotatedPolymorphisms().size()); + + } + + @Test + public void testWithPhylotree16() throws Exception { + + String tree = ""phylotree-rcrs@16.0""; + + Phylotree phylotree = loadPhylotree(tree); + + List files = new ArrayList(); + files.add(new File(""test-data/fasta/H100.fasta"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""HM625681.1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + // this H100 sample expects 15 variants according rCRS + assertEquals(15, firstSample.getAnnotatedPolymorphisms().size()); + } + + @Test + public void testWithPhylotree15FromOnlineRepository() throws Exception { + + String tree = ""phylotree-rcrs@15.0""; + + Phylotree phylotree = loadPhylotree(tree); + + List files = new ArrayList(); + files.add(new File(""test-data/hsd/H100.hsd"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""Sample1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + assertEquals(14, firstSample.getAnnotatedPolymorphisms().size()); + } + + @Test + public void testWithPhylotree17_fu() throws Exception { + + String tree = ""phylotree-fu-rcrs@1.0""; + + Phylotree phylotree = loadPhylotree(tree); + + List files = new ArrayList(); + files.add(new File(""test-data/fasta/L3i2_1.fasta"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""L3i2*2"", firstSample.getSample()); + + // haplogroup only present in phylotree 17 FU (not in previous versions) + assertEquals(""L3i2*2"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + } + + @Test + public void testWithFasta() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/fasta/H100.fasta"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""HM625681.1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + } + + @Test + public void testWithVcf() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/vcf/H100.vcf"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""Sample1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(""14"", task.getCounterByLabel(""Input Variants"").getValue()); + + assertEquals(0, firstSample.getNs()); + assertEquals(1, firstSample.getRanges().length); + } + + @Test + public void testVcfStatistics() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/vcf/H100_complex.vcf"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + assertNull(task.getError()); + assertTrue(task.isSuccess()); + + assertEquals(""1"", task.getCounterByLabel(""Samples"").getValue()); + assertEquals(""1"", task.getCounterByLabel(""Reference Mismatches"").getValue()); + assertEquals(""78.57"", task.getCounterByLabel(""Tree Overlap (%)"").getValue()); + assertEquals(""15"", task.getCounterByLabel(""Input Variants"").getValue()); + assertEquals(""1"", task.getCounterByLabel(""Out Of Range Variants"").getValue()); + assertEquals(""1"", task.getCounterByLabel(""Multiallelic Variants"").getValue()); + assertEquals(""0"", task.getCounterByLabel(""VCF Filtered Variants"").getValue()); + assertEquals(""1"", task.getCounterByLabel(""Duplicate Variants"").getValue()); + assertEquals(""0"", task.getCounterByLabel(""Low Sample Call Rate"").getValue()); + assertEquals(""2"", task.getCounterByLabel(""Variant Call Rate < 90%"").getValue()); + assertEquals(""1"", task.getCounterByLabel(""Strand Flips"").getValue()); + assertEquals(""3"", task.getCounterByLabel(""Monomorphic Variants"").getValue()); + + assertEquals(StatisticCounterType.WARNING, task.getCounterByLabel(""Strand Flips"").getType()); + assertEquals(StatisticCounterType.INFO, task.getCounterByLabel(""Samples"").getType()); + + } + + @Test + public void testVcfStatisticsWGS() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""data/examples/example-wgs.vcf"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + assertTrue(task.isSuccess()); + assertEquals(""50"", task.getCounterByLabel(""Samples"").getValue()); + assertEquals(""0"", task.getCounterByLabel(""Reference Mismatches"").getValue()); + assertEquals(""3,892"", task.getCounterByLabel(""Input Variants"").getValue()); + assertEquals(""20"", task.getCounterByLabel(""Indel Variants"").getValue()); + } + + @Test + public void testWithVcfAndChipParameter() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/vcf/H100.vcf"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.setChip(true); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""Sample1"", firstSample.getSample()); + assertEquals(""L2a1p"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + assertEquals(firstSample.getAnnotatedPolymorphisms().size(), firstSample.getRanges().length); + } + + @Test + public void testWithVcfGz() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/vcf/H100.vcf.gz"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertTrue(task.isSuccess()); + assertEquals(1, task.getSamples().size()); + + AnnotatedSample firstSample = task.getSamples().get(0); + assertEquals(""Sample1"", firstSample.getSample()); + assertEquals(""H100"", firstSample.getClade()); + assertEquals(0, firstSample.getNs()); + + } + + public void testWithUnsupportedFileFormat() throws Exception { + + Phylotree phylotree = loadPhylotree(PHYLOTREE); + + List files = new ArrayList(); + files.add(new File(""test-data/H100.png"")); + + ClassificationTask task = new ClassificationTask(phylotree, files, Distance.KULCZYNSKI); + task.run(); + + assertFalse(task.isSuccess()); + + } + +} +","Java" +"Nucleic acids","genepi/haplogrep3","docs/faq.md",".md","223","5","# FAQ + +## What data is stored by Haplogrep? +Haplogrep deletes the file immediately after the classification has been finished. Each user session is available for 48 hours. Haplogrep don't use any cookies for user tracking. +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/quickstart.md",".md","1194","31","# Quickstart + +There are 3 possibilities how to classify your profiles with Haplogrep. + +## Hosted web service +We provide Haplogrep 3 as a [web-service](https://haplogrep.i-med.ac.at) at the Medical University of Innsbruck. The service allows you upload the data to our service and run Haplogrep without any registration. Your input data is deleted right after classification. The results are available via a unique and shareable link for 7 days. + + +### Local web service + +[Download the latest version](installation.md) of Haplogrep and run the following command: + +```sh +./haplogrep3 server +``` +This will start a local version of Haplogrep at [http://localhost:7000](http://localhost:7000). + + +### Haplogrep CLI + +[Download the latest version](installation.md) of Haplogrep and run the following command: + +```sh +./haplogrep3 classify --tree --input --output +``` + +For the classification with Haplogrep on the command-line, you have to specify the used classification tree and provide a valid input and output file. Click [here](../trees.md) to learn more about trees. To get a list of available trees enter the following command: +```sh +./haplogrep3 trees +``` +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/input-formats.md",".md","1074","20","# Input Formats +Haplogrep supports input data in a text-based (\*.hsd), VCF or fasta format. + +#### FASTA +For alignment, [bwa version 0.7.17](https://github.com/lh3/bwa/releases/tag/v0.7.17) is used. For each input sequence, HaploGrep excludes positions from the tested range that are (1) not covered by the input fragment or (2) has marked with a N in the sequence. + +#### hsd Format +You can also specify your profiles in the original HaploGrep **hsd** format, which is a simple tab-delimited file format consisting of 4 columns (ID, Range, Haplogroup and Polymorphisms). + +``` +Sample1 1-16569 H100 263G 315.1C 750G 1041G 1438G 4769G 8860G 9410G 12358G 13656C 15326G 16189C 16192T 16519C +Sample2 1-16569 ? 73G 263G 315.1C 750G 1438G 3010A 3107C 4769G 5111T 8860G 10257T 12358G 15326G 16145A 16222T 16519C +``` +For readability, the polymorphisms are also tab-delimited (so columns >= 4). A hsd example can be found [here](../data/H100.hsd). + +#### VCF +You can upload a compressed multi-sample VCF file (vcf.gz). A VCF example file can be found [here](../data/example-wgs.vcf). + + +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/getting-started.md",".md","3837","52","# Getting Started + +This guide shows how to classify your data with the Haplogrep web service. + +## Run +Click on [this link](https://haplogrep.i-med.ac.at) to open our web service hosted at the Medical University of Innsbruck. If you want to run it locally, please read about the installation [here](../installation). + +## Uploading Data +After opening our web service, you see the following welcome screen. You can now upload your data in **FASTA**, **VCF** or **text-based** (hsd) format. The following input options are available: + +* Haplogrep detects the file format automatically. Please note that additional input options appear (e.g. for VCF), when selecting a specific input format. +* Select one of the available distance functions ([Kulczynski](../kulczynski), Hamming, Jaccard). +* Select one of the available trees. Learn more about trees [here](../trees). + +![](images/interface/welcome_screen.png) + +## Classifying Haplogroups +After clicking **Upload and Classify** the data is preprocessed, classified, annotated, and results are directly displayed in the web interface. + +## Summary Dashboard +The default tab includes summary statistics on the haplogroups clustered by the top-level haplogroup as defined by PhyloTree and gnomAD. The diagram can also be changed to display results on a haplogroup level. The table includes the numbers for each top-level haplogroup and also displays the frequencies for each defined population in gnomAD. The right hand side of the page includes the results of the quality control step using Haplogrep's rule-based system and displays a link that can be shared with researchers. +![](images/interface/data_classified_dashboard.png) + +## Sample Overview +By clicking on the Samples tab, the samples view will be openend. Each line displays a sample including the (a) name, (b) haplogroup, (c) quality, (d) number of N positions, (e) covered positions, (f) range and (g) input mutations. You can click on each sample to receive sample details. + +![](images/interface/data_classified.png) + +## Sample Details +After clicking on one sample, a details view opens. In this view you will find the following information: + +* All detected [errors and warnings](../errors-warnings) highlighted in yellow. ++ The haplogroup tophit (here: W1c) including the reached quality score in percentage. This is calculated by using one of our provided distance metrics. +* The expected mutations for the tophit (W1c) marked in *green* and *red*. *Green* means that the mutation is required for the tophit and has also been found in the input sample. *Red* means that the mutation is required by the tophit but was not found in the input sample. +* The remaining mutations from the input sample. Hotspots are marked in *green*, local private mutations in *blue* and global private mutations in *red*. +* The detected ranges for the input sample. +* The 20 tophits for each sample (denoted by ""Other Hits""). +* By clicking on a specific variant (here for 750G), all available frequencies and genetic predictors from publicly available databases are displayed. + +![](images/interface/sample_details.png) + +## Sample Filtering +Haplogrep allows to filter your samples according to their status. The screenshot below shows all samples including warnings within the input dataset. + +![](images/interface/data_filtered.png) + +## Export Options +Haplogrep provides numerous export options. Currently you can export your data as a (a) csv file, (b) extended csv file including mutation details, (c) quality control file (csv), (d) an annotated file and (e) a zip file including the report and the uploaded data. If selected, Haplogrep also provides options for (a) fasta and (b) MSA fasta download. +Please click [here](../annotations/#export) for detailed information on exported annotations. + +![](images/interface/export_options.png) +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/mutations.md",".md","1358","24","# Mutation Colouring +When opening the [details view of a sample](../getting-started/#sample-details), mutations are displayed in different colours. + +## Expected Mutations +In general, each haplogroup is defined by a set of expected mutations. Haplogrep informs users if the expected mutations for the tophit are included in the input sample. + +### Expected and Included ![](images/interface/expected_found.png) +Mutations displayed in green are mutations that are **expected by the tophit and also included** in the input sample. + +### Expected But Not Included ![](images/interface/expected_not_found.png) +Mutations displayed in red are mutations that are **expected by the tophit but not included** in the input sample. + +## Remaining Mutations +Remaining mutations of the input sample are separated by its type. + +### Hotspots ![](images/interface/remaining_hotspot.png) +Hotspots mutations are defined by a high number of occurrences in the used phylogenetic tree. + +### Local Private Mutations ![](images/interface/remaining_local-private_mutation.png) +Local private mutations are mutations that are not associated with the tophit but are included in the phylogenetic tree for other haplogroups. + +### Global Private Mutations ![](images/interface/remaining_global-private_mutation.png) +Global private mutations are not found at all in the phylogenetic tree. +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/installation.md",".md","1484","48","# Local Installation + +You can either (a) download and install the web service locally or (b) download the command-line interface. Please click [here](https://haplogrep.i-med.ac.at/haplogrep3) in case you want to use our hosted service. + +## Requirements + +You will need the following things properly installed on your computer. + +* Java 8 or higher + +Haplogrep works on Linux, macOS and Windows. Please note that fasta input files are currently supported for Linux and macOS only. + +## Download and Install + +### Linux or macOS + +Download and install the latest version from our download page using the following commands: + +``` +cd my-haplogrep3-install-folder +wget https://github.com/genepi/haplogrep3/releases/download/v3.2.2/haplogrep3-3.2.2-linux.zip +unzip haplogrep3-3.2.2-linux.zip +./haplogrep3 +``` + +### Windows + +Download the [latest Windows version](https://github.com/genepi/haplogrep3/releases/download/v3.2.2/haplogrep3-3.2.2-windows.zip) from our download page. + +- Open the zip file and extract it content to a folder of choice. + +- Open the PowerShell and navigate to your folder where you extracted the \*.exe file. + +You are now ready to use Haplogrep by running `haplogrep.exe`. + +## Run Haplogrep +The following command starts a web service locally: + +``` +./haplogrep3 server +``` +In case you want to run Haplogrep on the command-line execute the following command: +``` +./haplogrep3 classify +``` +## Parameters +Click [here](../parameters) to learn about all command-line parameters. +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/trees.md",".md","2077","44","# Installation and Usage + +Haplogrep is tree-independent and provides a plugin system to connect different phylogenetic trees with the software. + +## Install Trees +Haplogrep includes 3 trees (Phylotree 17 rCRS and RSRS, Phylotree Forensic Update) by default. +To install one of our other available trees, enter the following command: +``` +./haplogrep3 install-tree phylotree-rcrs@16.0 +``` + +Please have a list of all [available trees](https://genepi.github.io/haplogrep-trees) and commands to install them. + +## Tree Structure +All trees are publicly available on GitHub and consists of the following files: + +* A makefile to build the latest version automatically. +* A YAML file including all required metadata (e.g. name, URL, last update) and links to the required files (e.g. phylogenetic tree, nomenclature rules, hotspots) +* All files linked in the YAML file. The repository includes the phylogentic tree in XML format, the mutations weights, nomenclature rules and the amino acid changes files. +* Required reference files for FASTA alignment. For each reference in fasta format, the files generated by `bwa index` are required. Additionally, a `*dict` file is required. + +Please have a look at [the Phylotree 17 rCRS repository](https://github.com/genepi/phylotree-rcrs-17/) to see the definition of a tree. + +## Add trees +You can integrate your own trees, by setting up a repository similar to [this one](https://github.com/genepi/phylotree-rcrs-17/) and add the following command: +``` +./haplogrep3 install-tree phylotree-rcrs-15/blob/main/src/tree.yaml +``` + +## Share trees +To share trees, you can either add the tree [to our meta repository](https://github.com/genepi/haplogrep-trees) or set up your own repository. To set up your own repository, adapt the `haplogrep3.yaml` file as follows: + +``` +repositories: + - https://raw.githubusercontent.com/genepi/haplogrep-trees/main/trees.json + - https://raw.githubusercontent.com///main/trees.json + +``` + +This setup would then allow you to install trees like this: +``` +./haplogrep3 install-tree my-new-tree@1.0 +``` +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/index.md",".md","724","9","# Welcome to Haplogrep 3! + +Haplogrep 3 is a fast and free haplogroup classification tool. Upload your mtDNA profiles in **FASTA**, **VCF** or **txt-based format** and receive mitochondrial haplogroups, summary statistics and variant annotations in return. We provide Haplogrep 3 as a graphical web service or as a command-line tool for local usage. As of today, Haplogrep have been cited> 1200 times (Google Scholar, February 28 2023). + +![](images/interface/welcome_screen.png) + +## Citation +Schönherr S, Weissensteiner H, Kronenberg F, Forer L. Haplogrep 3 - an interactive haplogroup classification and analysis platform. Nucleic Acids Res. 2023. [https://doi.org/10.1093/nar/gkad284](https://doi.org/10.1093/nar/gkad284) +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/available-trees.md",".md","1078","6","# Available Trees +Haplogrep currently supports different mitochonddrial (mtDNA) phylogenies (e.g. Phylotree 15 - 17, Phylotree Forensic Update) which are provided for different references (rCRS and RSRS). A list of available trees is available [here](https://genepi.github.io/haplogrep-trees). For reproducibility, each tree is hosted in its on repository (e.g. [Phylotree 17](https://github.com/genepi/phylotree-rcrs-17)). + +## Versioning +One of the available trees must be selected before data upload and classification can be started. Please note that the listed versions in Haplogrep (e.g. Phylotree 17.1) combines the used data source (Phylotree) with the versioning introduced by Haplogrep. This means that Phylotree 17.1 (or e.g. Phylotree 17.2 in future) uses Phylotree 17 with the tree-specific files provided by Haplogrep. This allows us to reproduce results even if e.g. annotations, alignment rules or variants weights will change in future. The [Phylogenies](https://haplogrep.i-med.ac.at/phylogenies) includes further information and will also include a changelog. +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/parameters.md",".md","2040","33","# Parameters + +After you have successfully [installed](../installation/) Haplogrep on your local system, you can now run it with the following command. + +``` +./haplogrep3 classify +``` + +## Required Parameters +The following parameters are mandatory. + +|Parameter| Description| +|---|---| +|```--tree``` | Select one of the available trees | +|```--in``` | Please provide the input file name | +|```--out``` | Please provide an output name| + +## Optional Parameters + +Besides the mandatory parameters, we also provide numerous parameters for specific use cases. + +|Parameter| Description| +|---|---| +|```--metric```, ```distance```| To **change the classification metric** to Hamming Distance (```hamming```) or Jaccard (```jaccard```) add this parameter (Default: Kulczynski Measure).| +|```--extend-report```| For additional information on SNPs (e.g. found or remaining polymorphisms) please add the `--extend-report` flag (Default: off).| +|```--tree```| Specify one of the installed trees.| +|```--chip```| If you are using **genotyping arrays**, please add the `--chip` parameter to limit the range to array SNPs only (Default: off, VCF only). To get the same behaviour for hsd files, please add **only** the variants to the range, which are included on the array or in the range you have sequenced (e.g. control region). Range can be sepearted by a semicolon `;`, both ranges and single positions are allowed (e.g. 16024-16569;1-576;8860). | +|```--skip-alignment-rules```| Add this option to skip our rules that fixes the mtDNA nomenclature for fasta import. Click [here](#mtdna-nomenclature) for further information. Applying the rules is the default option since v2.4.0| +|```--hits``` | To export the **best n hits** for each sample add the `--hits` parameter. By default only the tophit is exported.| +|```--write-fasta``` | Write results in fasta format.| +|```--write-fasta-msa``` | Write multiple sequence alignment.| +|```--hetLevel=``` | Add heteroplasmies with a level > from the VCF file to the profile (default: 0.9). | +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/annotations.md",".md","1850","30","# Annotations +Starting with Haplogrep 3, the software includes new features for evaluating haplogroups or variants. This includes the possibility to get a visual representation of each top-level haplogroup including the expected variants for each haplogroup (see [here](https://haplogrep.i-med.ac.at/phylogenies)) or (b) get frequencies for each selected variant in the samples details page. + +## Clusters +We generated 33 top-level clusters according to PhyloTree and gnomAD and (a) group each haplogroup from the phylogeny (b) group each input sample into one of these clusters displayed within the summary dashboard. + +![](images/interface/phylogeny_clusters.png) + + +## Population Frequencies + We also display numerous frequencies for each variant mainly derived from [gnomAD](https://gnomad.broadinstitute.org/). Further annotations are available from the [Helix Mitochondrial database](https://www.helix.com/pages/mitochondrial-variant-database) and functional predictions from [MitImpact](https://mitimpact.css-mendel.it/). + +![](images/interface/variant_annotations.png) + +## Export +Haplogrep allows to export annotations. Currently the following annotations are exported. + +* `ScorePhastCons100V` [MitImpact_db_3.1.0 - *PhastCons_100V*] +* `ScoreMtoolBox` [MitImpact_db_3.1.0 - *MtoolBox_DS*] +* `ScoreAPOGEE` [MitImpact_db_3.1.0 - *APOGEE_score*] +* `PopFreqGnomeAD` [gnomAD v3.1 Frequencies - *popFreq*] +* `VafGnomADHom` [gnomAD v3.1 Annotations - *AF_hom*] +* `VafGnomADHet` [gnomAD v3.1 Annotations - *AF_het*] +* `Maplocus` [Haplogrep Annotation File] +* `AAC` [Haplogrep Annotation File] +* `ScoresMutPred` [Haplogrep Annotation File] +* `VafHelixHet` [Helix Mitochondrial database 20200327 - *Helix_vaf_het*] +* `VafHelixHom` [Helix Mitochondrial database 20200327 - *Helix_vaf_hom*] + +*The source file and source column name are added in brackets.*","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/kulczynski.md",".md","2825","64","# Kulczynski Metric + +Haplogrep supports input data in a text-based (\*.hsd), VCF or fasta format. + +Here we show how Haplogrep's default distance metric (so called Kulczynski measure) works on a concrete example. (Note: this blog post has been updated after receiving a correction from Chris Simpson, Thanks!) + +So let's say this is your input sample in hsd format: + +``` +test 16024-16569;1-576; ? 73G 263G 285T 315.1C 455.1T 523G 524T 16051G 16129A 16188.1C 16249C 16264G +``` +The Kulczynski measure is defined as follows: +``` +(HaplogroupWeight + SampleWeight) * 0.5 +``` + +HaploGrep applies this formula to all haplogroups in Phylotree and finally returns the overall best hit. In this example, I'll calculate the measure only for the best hit, this is in our case U1a2. + +1) First, we have to calculate the HaplogroupWeight: +``` +HaplogroupWeight = FoundPolymorphismsWeight/ExpectedPolymorphismsWeight +``` + +Found Polymorphisms: Polymorphisms from the input sample that are detected (or found) in the currently tested haplogroup (i.e. in our case U1a2) + +Expected Polymorphisms: Polymorphisms that are included (or expected) in the currently tested haplogroup (i.e. in our case U1a2). + +Found polymorphisms + weights: ```455.1T (6.7), 263G (8.8), 285T (10.0), 16249C (4.5), 16129A->2.6, 73G (5.6)``` + +Expected polymorphisms + weights: ```455.1T (6.7), 263G (8.8), 285T (10.0), 16189C (2.0), 16249C (4.5), 16129A (2.6), 73G (5.6)``` + +FoundPolymorphismsWeight: ```6.7 + 8.8 + 10 + 4.5 + 2.6 + 5.6 = 38.2``` + +ExpectedPolymorphismsWeight:```6.7 + 8.8 + 10 + 2 + 4.5 + 2.6 + 5.6 = 40.2``` + +HaplogroupWeight:```41.5 / 43.5 = 0.9540229885``` + +As you can see only 16189C is not found but expected by the haplogroup. + +2) Second, we have to calculate the SampleWeight: +``` +SampleWeight = FoundPolymorphismsWeight/SamplePolymorphismsWeight +``` +Found Polymorphisms: see above + +Sample Polymorphisms: Polymorphisms that are included in the sample and are falling into the specified range (2nd column of hsd, in our case 16024-16569;1-576;) + +Sample polymorphisms (weights):```16264G (0.0), 16188.1C (0.0), 263G (8.8), 311C (0.0), 16129A (2.6), 16051G (4.5), 455.1T (6.7), 523G (0.0), 285T (10.0), 524T (0.0), 16249C (4.5), 73G (5.6)``` + +SamplePolymorphismsWeight: ```8.8 + 2.6 + 4.5 + 6.7 + 10 + 4.5 + 5.6 = 42.7``` + +SampleWeight: ```41.5 / 46 = 0.90217391304``` + +As you can see 16051G is included in the sample but not required by the haplogroup. + +3) Third use the calculate weights and calculate the final measure: +``` +(HaplogroupWeight + SampleWeight) * 0.5 +(0.90217391304 + 0.9540229885) / 2 = 0.92809845077 +``` +The best hit (U1a2) has a quality of 0.928. We also integrated that as an automatic test case here. + +Keep in mind that in a real life scenario the quality of all haplogroups are calculated, sorted and the best 50 hits are returned. +","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/contact.md",".md","411","7","# Contact + +The complete Haplogrep3 source code is available on [GitHub](https://github.com/genepi/haplogrep3). Feel free to create issues and pull requests. Before contacting us, please have a look at the [FAQ page](../faq) first. + +* [Sebastian Schönherr](mailto:sebastian.schoenherr@i-med.ac.at) +* [Hansi Weissensteiner](mailto:hansi.weissensteiner@i-med.ac.at) +* [Lukas Forer](mailto:lukas.forer@i-med.ac.at)","Markdown" +"Nucleic acids","genepi/haplogrep3","docs/errors-warnings.md",".md","1215","24","# Errors and Warnings + +Haplogrep includes different warnings and errors. Please find a list of currently applied measures. + +## Errors + +* The detected haplogroup quality is low. Sample is marked red. Quality <=80% +* The expected haplogroup is not a super group of the detected haplogroup +* Common rCRS polymorphism not found! The sample seems not properly aligned to rCRS +* The sample seems to be aligned to RSRS. Haplogrep only supports rCRS aligned samples +* The sample misses >2 expected polymorphisms + +## Warnings + +* Fasta Alignment check: positions to recheck +* The detected haplogroup does not match the expected haplogroup but represents a valid sub haplogroup +* The sample shows ambiguous best results +* The detected haplogroup quality is moderate. Sample is marked yellow. Quality <= 90% and > 80% +* The sample contains polymorphimsms that are equal to the reference / The sample contains variants according the rCRS +* The sample contains >2 global private mutation(s) that are not known by Phylotree +* The sample contains >=2 local private mutation(s) associated with other Haplogroups +* Different haplogroup with 2 local private remaining mutation(s) found +* The sample contains undetermined variants N +","Markdown"