file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MatchBlockRMA2Formatter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/MatchBlockRMA2Formatter.java
/* * MatchBlockRMA2Formatter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma2; import megan.io.ByteByteInt; import megan.io.IInputReader; import megan.io.IOutputWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; /** * reads and writes the read block fixed part * Daniel Huson, 3.2011 */ public class MatchBlockRMA2Formatter { static public final String DEFAULT_RMA2_0 = "BitScore:float;Identity:float;TaxonId:int;RefSeqID:BBI;"; static public final String DEFAULT_RMA2_1 = "BitScore:float;Identity:float;TaxonId:int;RefSeqID:BBI;"; static public final String DEFAULT_RMA2_5 = "BitScore:float;Identity:float;Expected:float;TaxonId:int;SeedId:int;CogId:int;KeggId:int;PfamId:int;"; private final String format; private int numberOfBytes = 0; // access to commonly used ones: private Object[] bitScore; private Object[] expected; private Object[] percentIdentity; private Object[] taxonId; private Object[] seedId; private Object[] cogId; private Object[] keggId; private Object[] pfamId; private Object[] refSeqId; private Object[][] data; private final HashMap<String, Object[]> name2data = new HashMap<>(); /** * constructs an instance and sets to the given format * */ public MatchBlockRMA2Formatter(String format) { this.format = format; decode(format); } private void decode(String format) { LinkedList<Object[]> list = new LinkedList<>(); StringTokenizer tokenizer = new StringTokenizer(format, ";"); while (tokenizer.hasMoreElements()) { String[] split = tokenizer.nextToken().split(":"); String name = split[0]; String type = split[1]; Object[] object = new Object[]{name, type.charAt(0), null}; switch (type.charAt(0)) { case 'i', 'f' -> numberOfBytes += 4; case 'l' -> numberOfBytes += 8; case 'b' -> numberOfBytes += 1; case 'B' -> numberOfBytes += 6; case 'c' -> numberOfBytes += 2; } name2data.put(name, object); list.add(object); } data = list.toArray(new Object[list.size()][]); // access to standard items set here: bitScore = name2data.get("BitScore"); expected = name2data.get("Expected"); percentIdentity = name2data.get("Identity"); taxonId = name2data.get("TaxonId"); seedId = name2data.get("SeedId"); cogId = name2data.get("CogId"); keggId = name2data.get("KeggId"); pfamId = name2data.get("PfamId"); refSeqId = name2data.get("RefSeqID"); } /** * read the fixed part of the reads block * */ public void read(IInputReader dataIndexReader) throws IOException { for (Object[] dataRecord : data) { switch ((Character) dataRecord[1]) { case 'i' -> dataRecord[2] = dataIndexReader.readInt(); case 'f' -> dataRecord[2] = dataIndexReader.readFloat(); case 'l' -> dataRecord[2] = dataIndexReader.readLong(); case 'b' -> dataRecord[2] = (byte) dataIndexReader.read(); case 'B' -> dataRecord[2] = dataIndexReader.readByteByteInt(); case 'c' -> dataRecord[2] = dataIndexReader.readChar(); } // System.err.println("Read (match): "+ Basic.toString(dataRecord,",")); } } /** * write the fixed part of the reads block * */ public void write(IOutputWriter indexWriter) throws IOException { for (Object[] dataRecord : data) { switch ((Character) dataRecord[1]) { case 'i' -> indexWriter.writeInt((Integer) dataRecord[2]); case 'f' -> indexWriter.writeFloat((Float) dataRecord[2]); case 'l' -> indexWriter.writeLong((Long) dataRecord[2]); case 'b' -> indexWriter.write((Byte) dataRecord[2]); case 'B' -> indexWriter.writeByteByteInt((ByteByteInt) dataRecord[2]); case 'c' -> indexWriter.writeChar((Character) dataRecord[2]); } // System.err.println("Wrote (match): "+ Basic.toString(dataRecord,",")); } } /** * get the value for a name * * @return value */ public Object get(String name) { return name2data.get(name)[2]; } /** * set the value for a name. Does not check that value is of correct type! * */ public void put(String name, Object value) { name2data.get(name)[2] = value; } public boolean hasBitScore() { return bitScore != null; } public Float getBitScore() { return (Float) bitScore[2]; } public void setBitScore(Float value) { bitScore[2] = value; } public boolean hasExpected() { return expected != null; } public Float getExpected() { return (Float) expected[2]; } public void setExpected(Float value) { expected[2] = value; } public boolean hasPercentIdentity() { return percentIdentity != null; } public Float getPercentIdentity() { return (Float) percentIdentity[2]; } public void setPercentIdentity(Float value) { percentIdentity[2] = value; } public boolean hasTaxonId() { return taxonId != null; } public int getTaxonId() { return (Integer) taxonId[2]; } public void setTaxonId(Integer value) { taxonId[2] = value; } public boolean hasSeedId() { return seedId != null; } public int getSeedId() { if (seedId[2] != null) return (Integer) seedId[2]; else return 0; } public void setSeedId(Integer value) { seedId[2] = value; } public boolean hasCogId() { return cogId != null; } public int getCogId() { if (cogId[2] != null) return (Integer) cogId[2]; else return 0; } public void setCogId(Integer value) { cogId[2] = value; } public boolean hasKeggId() { return keggId != null; } public int getKeggId() { if (keggId[2] != null) return (Integer) keggId[2]; else return 0; } public void setKeggId(Integer value) { keggId[2] = value; } public boolean hasPfamId() { return pfamId != null; } public int getPfamId() { if (pfamId[2] != null) return (Integer) pfamId[2]; else return 0; } public void setPfamId(Integer value) { pfamId[2] = value; } public boolean hasRefSeqId() { return refSeqId != null; } public ByteByteInt getRefSeqId() { if (refSeqId != null) return (ByteByteInt) refSeqId[2]; else return ByteByteInt.ZERO; } public void setRefSeqId(ByteByteInt value) { if (refSeqId != null) refSeqId[2] = value; } public int getNumberOfBytes() { return numberOfBytes; } /** * gets the format string * * @return format string */ public String toString() { return format; } }
8,162
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA2Creator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/RMA2Creator.java
/* * RMA2Creator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma2; import megan.data.IReadBlockWithLocation; import megan.data.LocationManager; import megan.data.TextStoragePolicy; import megan.io.InputReader; import megan.io.OutputWriter; import java.io.File; import java.io.IOException; import java.nio.channels.FileChannel; /** * used to create a new RMA 2file * Daniel Huson, 10.2010 */ public class RMA2Creator { private final RMA2File rma2File; private final TextStoragePolicy textStoragePolicy; private final LocationManager locationManager; private final OutputWriter fileWriter; // writer to file private final OutputWriter dumpWriter; // writer to optimal dump file private final OutputWriter tmpWriter; // writer to temporary file for ONBOARD private final InfoSection infoSection; private final RMA2Formatter rma2Formatter; private int numberOfReads = 0; private int numberOfMatches = 0; /** * open the file for creation * */ public RMA2Creator(File file, TextStoragePolicy textStoragePolicy, LocationManager locationManager) throws IOException { rma2File = new RMA2File(file); this.textStoragePolicy = textStoragePolicy; this.locationManager = locationManager; infoSection = rma2File.getInfoSection(); rma2Formatter = infoSection.getRMA2Formatter(); infoSection.setTextStoragePolicy(textStoragePolicy); switch (textStoragePolicy) { case Embed -> { infoSection.setTextFileNames(new String[0]); infoSection.setTextFileSizes(new Long[0]); fileWriter = rma2File.getFileWriter(); // no need to write check_byte here, required by dataindex, because is written in creation method: tmpWriter = rma2File.getTmpIndexFileWriter(); dumpWriter = null; infoSection.setDataDumpSectionStart(fileWriter.getPosition()); } case InRMAZ -> { if (locationManager.getFiles().size() != 1) throw new IOException("Wrong number of dump-file names: " + locationManager.getFileNames().length); infoSection.setTextFileNames(locationManager.getFileNames()); infoSection.setTextFileSizes(new Long[0]); File dumpFile = locationManager.getFile(0); fileWriter = rma2File.getFileWriter(); dumpWriter = rma2File.getDataDumpWriter(dumpFile); tmpWriter = null; infoSection.setDataIndexSectionStart(fileWriter.getPosition()); fileWriter.write(RMA2File.CHECK_BYTE); // required by dataindex } case Reference -> { infoSection.setTextFileNames(locationManager.getFileNames()); infoSection.setTextFileSizes(locationManager.getFileSizes()); fileWriter = rma2File.getFileWriter(); dumpWriter = null; tmpWriter = null; infoSection.setDataIndexSectionStart(fileWriter.getPosition()); fileWriter.write(RMA2File.CHECK_BYTE); // required by dataindex } default -> throw new IOException("Unknown textStoragePolicy: " + textStoragePolicy); } } /** * write a read block to the file * */ public void writeReadBlock(IReadBlockWithLocation readBlock) throws IOException { numberOfReads++; numberOfMatches += readBlock.getNumberOfMatches(); switch (textStoragePolicy) { case Embed -> ReadBlockRMA2.write(rma2Formatter, readBlock, fileWriter, tmpWriter); case InRMAZ -> ReadBlockRMA2.write(rma2Formatter, readBlock, dumpWriter, fileWriter); case Reference -> ReadBlockRMA2.write(rma2Formatter, readBlock, null, fileWriter); default -> throw new IOException("Unknown textStoragePolicy: " + textStoragePolicy); } } /** * close the file. * */ public void close() throws IOException { infoSection.syncLocationManager2InfoSection(locationManager); switch (textStoragePolicy) { case Embed -> { infoSection.setDataDumpSectionEnd(fileWriter.getPosition()); infoSection.setDataIndexSectionStart(fileWriter.getPosition()); // copy the temporary index file to the main file: tmpWriter.close(); InputReader indexReader = rma2File.getTmpIndexFileReader(); FileChannel indexChannel = indexReader.getChannel(); fileWriter.write(RMA2File.CHECK_BYTE); final int bufferSize = 1000000; byte[] buffer = new byte[bufferSize]; long length = indexReader.length(); long total = 1; for (long i = 0; i < length; i += bufferSize) { int count = indexReader.read(buffer, 0, bufferSize); if (total + count > length) count = (int) (length - total); if (count > 0) { fileWriter.write(buffer, 0, count); total += count; } } infoSection.setDataIndexSectionEnd(fileWriter.getPosition()); // there are no classifications (yet), so we dont't write them // empty summary section: infoSection.setAuxiliaryDataStart(fileWriter.getPosition()); infoSection.setAuxiliaryDataEnd(fileWriter.getPosition()); indexReader.close(); indexChannel.close(); rma2File.getIndexTmpFile().delete(); } case InRMAZ -> { dumpWriter.close(); infoSection.setDataIndexSectionEnd(fileWriter.getPosition()); // there are no classifications (yet), so we dont't write them // empty summary section: infoSection.setAuxiliaryDataStart(fileWriter.getPosition()); infoSection.setAuxiliaryDataEnd(fileWriter.getPosition()); } case Reference -> { infoSection.setDataIndexSectionEnd(fileWriter.getPosition()); // there are no classifications (yet), so we dont't write them // empty summary section: infoSection.setAuxiliaryDataStart(fileWriter.getPosition()); infoSection.setAuxiliaryDataEnd(fileWriter.getPosition()); } default -> throw new IOException("Unknown textStoragePolicy: " + textStoragePolicy); } infoSection.setNumberOfReads(numberOfReads); infoSection.setNumberOfMatches(numberOfMatches); infoSection.write(fileWriter); // System.err.println("File size: " + fileWriter.length()); fileWriter.close(); // System.err.println("****** InfoSection:\n" + rma2File.loadInfoSection().toString()); } /** * adds all locations of the source files, if necessary * */ public void setLocations(LocationManager locationManager) { infoSection.setTextFileNames(locationManager.getFileNames()); } /** * get current position of file writer (This is not necessarily the position at which the read gets written) * * @return file writer position */ public long getFileWriterPosition() throws IOException { return fileWriter.getPosition(); } }
8,330
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockRMA2.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/MatchBlockRMA2.java
/* * MatchBlockRMA2.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma2; import jloda.util.StringUtils; import megan.data.*; import megan.io.ByteByteInt; import megan.io.IInputReader; import megan.io.IOutputWriter; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; /** * matchblock for RMA2 * Daniel Huson, 9.2010, 3.2016 */ public class MatchBlockRMA2 implements IMatchBlock { private static final String TAXONOMY = "Taxonomy"; private static final String SEED = "SEED"; private static final String KEGG = "KEGG"; private static final String COG = "EGGNOG"; private final Map<String, Integer> cName2id = new HashMap<>(); private long uid; private float bitScore; private float percentIdentity; private String refSeqId; private float expected; private int length; private boolean ignore; private String text; /** * erase the block (for reuse) */ public void clear() { uid = 0; bitScore = 0; percentIdentity = 0; refSeqId = null; expected = 0; length = 0; ignore = false; text = null; cName2id.clear(); } /** * get the unique identifier for this match (unique within a dataset). * In an RMA file, this is always the file position for the match * * @return uid */ public long getUId() { return uid; } public void setUId(long uid) { this.uid = uid; } /** * gets the id for the named classification * * @return id */ public int getId(String name) { Integer id = cName2id.get(name); return id == null ? 0 : id; } /** * set the id for the named classification * */ public void setId(String name, Integer id) { cName2id.put(name, id); } /** * gets all defined ids * * @return ids */ public int[] getIds(String[] cNames) { int[] ids = new int[cNames.length]; for (int i = 0; i < cNames.length; i++) { ids[i] = getId(cNames[i]); } return ids; } /** * get the taxon id of the match * */ public int getTaxonId() { return getId(TAXONOMY); } public void setTaxonId(int taxonId) { cName2id.put(TAXONOMY, taxonId); } /** * get the score of the match * */ public float getBitScore() { return bitScore; } public void setBitScore(float bitScore) { this.bitScore = bitScore; } /** * get the percent identity * */ public float getPercentIdentity() { return percentIdentity; } public void setPercentIdentity(float percentIdentity) { this.percentIdentity = percentIdentity; } /** * get the refseq id * */ public String getRefSeqId() { return refSeqId; } public void setRefSeqId(String refSeqId) { this.refSeqId = refSeqId; } /** * gets the E-value * */ public void setExpected(float expected) { this.expected = expected; } public float getExpected() { return expected; } /** * gets the match length * */ public void setLength(int length) { this.length = length; } public int getLength() { return length; } /** * get the ignore status * */ public boolean isIgnore() { return ignore; } public void setIgnore(boolean ignore) { this.ignore = ignore; } /** * get the text * */ public String getText() { return text; } @Override public String getTextFirstWord() { return text != null ? StringUtils.getFirstWord(text) : null; } public void setText(String text) { this.text = text; } /** * read a match block * * @return matchBlock */ public static MatchBlockRMA2 read(RMA2Formatter rma2Formatter, long uid, boolean wantMatchData, boolean wantMatchText, float minScore, float maxExpected, TextStorageReader textReader, IInputReader dataIndexReader) throws IOException { MatchBlockRMA2 matchBlock = rma2Formatter.isWantLocationData() ? new MatchBlockFromBlast() : new MatchBlockRMA2(); if (uid == -1) uid = dataIndexReader.getPosition(); else dataIndexReader.seek(uid); // total items to read: float float int bytebyteint char long int = 4+4+4+6+2+8+4=32 if (!wantMatchData && (minScore > 0 || maxExpected < 10000)) wantMatchData = true; // need score or expected, and also get everything else if (wantMatchData) { matchBlock.setUId(uid); MatchBlockRMA2Formatter matchBlockFormatter = rma2Formatter.getMatchBlockRMA2Formatter(); matchBlockFormatter.read(dataIndexReader); if (matchBlockFormatter.hasBitScore()) matchBlock.setBitScore(matchBlockFormatter.getBitScore()); if (matchBlockFormatter.hasExpected()) matchBlock.setExpected(matchBlockFormatter.getExpected()); if (matchBlockFormatter.hasPercentIdentity()) matchBlock.setPercentIdentity(matchBlockFormatter.getPercentIdentity()); if (matchBlockFormatter.hasTaxonId()) matchBlock.setTaxonId(matchBlockFormatter.getTaxonId()); if (matchBlockFormatter.hasSeedId()) matchBlock.setId(SEED, matchBlockFormatter.getSeedId()); if (matchBlockFormatter.hasCogId()) matchBlock.setId(COG, matchBlockFormatter.getCogId()); if (matchBlockFormatter.hasKeggId()) matchBlock.setId(KEGG, matchBlockFormatter.getKeggId()); if (matchBlockFormatter.hasRefSeqId()) matchBlock.setRefSeqId(matchBlockFormatter.getRefSeqId().toString()); if (matchBlock.getBitScore() < minScore || matchBlock.getExpected() > maxExpected) { dataIndexReader.skipBytes(14); // skip the unwanted entries char+long+int return null; } } else { dataIndexReader.skipBytes(rma2Formatter.getMatchBlockRMA2Formatter().getNumberOfBytes()); // skip the unwanted fixed entries } if (wantMatchText) { final Location location = new Location(dataIndexReader.readChar(), dataIndexReader.readLong(), dataIndexReader.readInt()); matchBlock.setText(textReader.getText(location)); if (rma2Formatter.isWantLocationData()) { ((MatchBlockFromBlast) matchBlock).setTextLocation(location); } } else dataIndexReader.skipBytes(14); return matchBlock; } /** * get the size of a match block in the index file * * @return number of bytes in match block */ public static int getBytesInIndexFile(MatchBlockRMA2Formatter matchBlockRMA2Formatter) { return matchBlockRMA2Formatter.getNumberOfBytes() + 14; // 14 for location information } /** * writes a match to the RMA file * * @param indexWriter @throws java.io.IOException */ public static void write(RMA2Formatter rma2Formatter, IMatchBlockWithLocation matchBlock, IOutputWriter dumpWriter, IOutputWriter indexWriter) throws IOException { matchBlock.setUId(indexWriter.getPosition()); Location location = matchBlock.getTextLocation(); if (dumpWriter != null) { if (location == null) { location = new Location(); matchBlock.setTextLocation(location); } location.setFileId(0); location.setPosition(dumpWriter.getPosition()); dumpWriter.writeString(matchBlock.getText()); location.setSize((int) (dumpWriter.getPosition() - location.getPosition())); } // write match to dataindex: MatchBlockRMA2Formatter matchBlockFormatter = rma2Formatter.getMatchBlockRMA2Formatter(); if (matchBlockFormatter.hasBitScore()) matchBlockFormatter.setBitScore(matchBlock.getBitScore()); if (matchBlockFormatter.hasExpected()) matchBlockFormatter.setExpected(matchBlock.getExpected()); if (matchBlockFormatter.hasPercentIdentity()) matchBlockFormatter.setPercentIdentity(matchBlock.getPercentIdentity()); if (matchBlockFormatter.hasTaxonId()) matchBlockFormatter.setTaxonId(matchBlock.getTaxonId()); if (matchBlockFormatter.hasSeedId()) matchBlockFormatter.setSeedId(matchBlock.getId(SEED)); if (matchBlockFormatter.hasCogId()) matchBlockFormatter.setCogId(matchBlock.getId(COG)); if (matchBlockFormatter.hasKeggId()) matchBlockFormatter.setKeggId(matchBlock.getId(KEGG)); if (matchBlockFormatter.hasRefSeqId()) matchBlockFormatter.setRefSeqId(new ByteByteInt(matchBlock.getRefSeqId())); matchBlockFormatter.write(indexWriter); if (location != null) { indexWriter.writeChar((char) location.getFileId()); indexWriter.writeLong(location.getPosition()); indexWriter.writeInt(location.getSize()); } else { indexWriter.writeChar((char) -1); indexWriter.writeLong(-1); indexWriter.writeInt(-1); } } public String toString() { StringWriter w = new StringWriter(); w.write("Match uid: " + uid + "--------\n"); if (getTaxonId() != 0) w.write("taxonId: " + getTaxonId() + "\n"); if (getId(SEED) != 0) w.write("seedId: " + getId(SEED) + "\n"); if (getId(COG) != 0) w.write("cogId: " + getId(COG) + "\n"); if (getId(KEGG) != 0) w.write("keggId: " + getId(KEGG) + "\n"); if (bitScore != 0) w.write("bitScore: " + bitScore + "\n"); if (percentIdentity != 0) w.write("percentIdentity: " + percentIdentity + "\n"); if (refSeqId != null && refSeqId.length() > 0) w.write("refSeqId: " + refSeqId + "\n"); if (expected != 0) w.write("expected: " + expected + "\n"); if (length != 0) w.write("length: " + length + "\n"); if (ignore) w.write("ignore: " + "\n"); w.write("text: " + text + "\n"); return w.toString(); } /** * get the start position of the alignment in the query * * @return query start position */ @Override public int getAlignedQueryStart() { return 0; } /** * get the end position of the alignment in the query * */ @Override public int getAlignedQueryEnd() { return 0; } @Override public int getRefLength() { return 0; } }
11,759
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ConfigRequests.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/accessiondb/ConfigRequests.java
package megan.accessiondb; /** * configuration requests for the SQLite database connections when working with mapping DBs * Daniel Huson, 11.22 */ public class ConfigRequests { private static boolean useTempStoreInMemory=false; private static int cacheSize=-10000; /** * use temp store in memory when creating a mapping DB? * @return */ public static boolean isUseTempStoreInMemory() { return useTempStoreInMemory; } /** * determine whether to request in-memory temp storage. If not requested, default will be used * @param useTempStoreInMemory */ public static void setUseTempStoreInMemory(boolean useTempStoreInMemory) { ConfigRequests.useTempStoreInMemory = useTempStoreInMemory; } /** * cache size to use * @return */ public static int getCacheSize() { return cacheSize; } /** * set the SQLite cache size. Negative values have a special meaning, see SQLite documentation * @param cacheSize */ public static void setCacheSize(int cacheSize) { ConfigRequests.cacheSize = cacheSize; } }
1,042
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AccessAccessionMappingDatabase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/accessiondb/AccessAccessionMappingDatabase.java
/* * AccessAccessionMappingDatabase.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.accessiondb; import jloda.util.Basic; import jloda.util.FileUtils; import jloda.util.StringUtils; import org.sqlite.SQLiteConfig; import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.*; import java.util.function.Function; import java.util.function.IntUnaryOperator; /** * Access to accession mapping database * Original implementation: Syliva Siegel, 2019 * Modified and extended by Daniel Huson, 9.2019 */ public class AccessAccessionMappingDatabase implements Closeable { public enum ValueType {TEXT, INT} private final Connection connection; public static IntUnaryOperator accessionFilter = x -> (x > -1000 ? x : 0); public static Function<String, Boolean> fileFilter = x -> !x.endsWith("_UE"); /** * constructor, opens and maintains connection to database */ public AccessAccessionMappingDatabase(String dbFile) throws IOException, SQLException { if (!FileUtils.fileExistsAndIsNonEmpty(dbFile)) throw new IOException("File not found or unreadable: " + dbFile); final var config = new SQLiteConfig(); config.setCacheSize(ConfigRequests.getCacheSize()); config.setReadOnly(true); connection = config.createConnection("jdbc:sqlite:" + dbFile); var result=executeQueryString("SELECT info_string FROM info WHERE id = 'general';", 1); if (result.size()>0 && !fileFilter.apply(result.get(0))) throw new IOException("Mapping file " + FileUtils.getFileNameWithoutPath(dbFile) + " is intended for use with MEGAN Ultimate Edition, it is not compatible with MEGAN Community Edition"); } /** * get the info string associated with the database. This string can be inserted when creating the DB * * @return info string associated or null if no such string is defined */ public String getInfo() throws SQLException { final var buf = new StringBuilder(); try { buf.append(executeQueryString("SELECT info_string FROM info WHERE id = 'general';", 1).get(0)); } catch (IndexOutOfBoundsException e) { throw new SQLException(e); } for (var name : getClassificationNames()) { buf.append("\n").append(name).append(": ").append(getInfo(name)); } return buf.toString(); } /** * gets the size of the mappings table * * @return size */ public int getSize() throws SQLException { try { return executeQueryInt("SELECT size FROM info WHERE id = 'general';", 1).get(0); } catch (IndexOutOfBoundsException e) { // if the field is empty compute the size and store it in the info table final var size = computeDBSize(); var insertionQuery = "UPDATE info SET size = " + size + " WHERE id = 'general';"; try { executeQueryInt(insertionQuery, 1); } catch (SQLException ex) { // it does not matter whether insertion worked or not. } return size; } } /** * get the index (column) for a classification. In the methods below, we will reference classifications by their index * * @param classificationName name of the classification you want to look for * @return the index in the database for a given classificationName, 1-based */ public int getClassificationIndex(String classificationName) throws SQLException { final var query = "SELECT * FROM mappings LIMIT 1;"; final var metaData = getMetaData(query); // Note that for the database access the index is 1-based // this 1-based index will be returned for (var i = 0; i < metaData.getColumnCount(); i++) { var label = metaData.getColumnLabel(i + 1); if (label.equals(classificationName)) { return i + 1; } } return -1; } /** * get the type for a given classification index * * @param classificationIndex index to be considered * @return the ValueType of the index (either String or integer) */ public ValueType getType(int classificationIndex) throws SQLException { final var query = "SELECT * FROM mappings LIMIT 1;"; final var metaData = getMetaData(query); final var typeName = metaData.getColumnTypeName(classificationIndex); if (typeName.equals("TEXT")) { return ValueType.TEXT; } else if (typeName.equals("INT") || typeName.equals("NUM")) { return ValueType.INT; } return null; } /** * get the size for a given classification index * * @return size for a given classification index or -1 if the classification was not found */ public int getSize(String classificationName) { try { return executeQueryInt("SELECT size FROM info WHERE id = '" + classificationName + "';", 1).get(0); } catch (Exception e) { return 0; } } /** * get the info string for a given classification * * @return info string provided when inserting the reference database or "" if no such string was given */ public String getInfo(String classificationName) throws SQLException { try { final var infoString = executeQueryString("SELECT info_string FROM info WHERE id = '" + classificationName + "';", 1).get(0); return "%s, size: %,d".formatted(infoString, getSize(classificationName)); } catch (IndexOutOfBoundsException e) { throw new SQLException(e); } } public void close() { if (connection != null) { try { connection.close(); } catch (SQLException e) { Basic.caught(e); } } } /** * Checks the cache/ DB for the accession and returns the whole Integer[] of all values associated with that accession * * @param accession accession String to query to database for * @return int[] or null */ public int getValue(String classificationName, String accession) throws SQLException { final var rs = connection.createStatement().executeQuery("SELECT " + classificationName + " FROM mappings WHERE Accession = '" + accession + "';"); while (rs.next()) { final var value = rs.getInt(classificationName); if (value != 0) return accessionFilter.applyAsInt(value); } return 0; } /** * alternative implementation for get * for an array of string accessions the method queries the database at once for all accessions in that array * * @return a HashMap containing the accession and a list of the corresponding classifications */ public HashMap<String, int[]> getValues(String[] accessions, int length) throws SQLException { final var buf = new StringBuilder(); buf.append("select * from mappings where Accession in("); var first = true; for (var i = 0; i < length; i++) { if (first) first = false; else buf.append(", "); buf.append("'").append(accessions[i]).append("'"); } buf.append(");"); final var rs = connection.createStatement().executeQuery(buf.toString()); final var columnCount = rs.getMetaData().getColumnCount(); final var results = new HashMap<String, int[]>(); while (rs.next()) { final var values = new int[columnCount]; for (var i = 2; i <= columnCount; i++) { // database index starts with 1; 1 is the accession everything else is result values[i - 2] = accessionFilter.applyAsInt(rs.getInt(i)); } results.put(rs.getString(1), values); } return results; } /** * for each provided accession, returns ids for all named classifications * * @param accessions queries * @param cNames desired classifications * @return for each accession, the ids for all given classifications, in the same order as the classifications * @throws SQLException */ public int[][] getValues(String[] accessions, int numberOfAccessions, String[] cNames) throws SQLException { final var computedAccessionClassMapping = new int[accessions.length][cNames.length]; var query = "select Accession, %s from mappings where Accession in ('%s');".formatted( StringUtils.toString(cNames, ","), StringUtils.toString(accessions, 0, numberOfAccessions, "', '")); var resultSet = connection.createStatement().executeQuery(query); var columnCount = resultSet.getMetaData().getColumnCount(); var accessionIndexMap = new HashMap<String, Integer>(); for (var index = 0; index < numberOfAccessions; index++) { accessionIndexMap.put(accessions[index], index); } while (resultSet.next()) { var accession = resultSet.getString(1); if (accessionIndexMap.containsKey(accession)) { var array = computedAccessionClassMapping[accessionIndexMap.get(accession)]; //System.err.println(resultSet.getString(1)); for (var c = 1; c < columnCount; c++) { // database index starts with 1; 1 is the accession everything else is result array[c - 1] = accessionFilter.applyAsInt(resultSet.getInt(c + 1)); } } } return computedAccessionClassMapping; } /** * for each provided accession, returns ids for all classifications * * @param accessions queries * @param result results are written here, must have length accessions.size()*number-of-classifications * @throws SQLException */ public void getValues(Collection<String> accessions, int[] result) throws SQLException { var query = "select * from mappings where Accession in ('" + StringUtils.toString(accessions, "', '") + "');"; var rs = connection.createStatement().executeQuery(query); var columnCount = rs.getMetaData().getColumnCount(); var r = 0; while (rs.next()) { for (var i = 1; i < columnCount; i++) { // database index starts with 1; 1 is the accession everything else is result result[r++] = accessionFilter.applyAsInt(rs.getInt(i + 1)); } } } /** * for each provided accession, returns ids for all named classifications * * @param accessions queries * @param cNames desired classifications * @return for each accession and cName, the id * @throws SQLException */ public int[] getValues(Collection<String> accessions, String[] cNames) throws SQLException { var query = "select " + StringUtils.toString(cNames, ",") + " from mappings where Accession in" + " ('" + StringUtils.toString(accessions, "', '") + "');"; var rs = connection.createStatement().executeQuery(query); var columnCount = rs.getMetaData().getColumnCount(); var result = new int[accessions.size() * cNames.length]; var r = 0; while (rs.next()) { for (var i = 0; i < columnCount; i++) { // database index starts with 1; 1 is the accession everything else is result result[r++] = accessionFilter.applyAsInt(rs.getInt(i + 1)); } } return result; } /** * generic method for executing queries with results of type int/Integer * * @param query the SQL query * @return ArrayList containing all query results of the specified type * @throws SQLException if something went wrong with the database */ private ArrayList<Integer> executeQueryInt(String query, int index) throws SQLException { final ResultSet rs = connection.createStatement().executeQuery(query); final ArrayList<Integer> resultlist = new ArrayList<>(); while (rs.next()) { resultlist.add(rs.getInt(index)); } return resultlist; } /** * generic method for executing queries with results of type String * * @param query the SQL query * @param index the index of the result of interest * @return ArrayList containing all query results of the specified type * @throws SQLException if something went wrong with the database */ private ArrayList<String> executeQueryString(String query, int index) throws SQLException { final ResultSet rs = connection.createStatement().executeQuery(query); final ArrayList<String> result = new ArrayList<>(); while (rs.next()) { result.add(rs.getString(index)); } return result; } /** * computes the size of the mappings database by querying the mappings table with count(*) * * @return size of the database or 0 if an error occurred */ private int computeDBSize() throws SQLException { return executeQueryInt("SELECT count(*) FROM mappings;", 1).get(0); } /** * get the list of classification names * * @return a Collection<String> containing all classification names used in the database */ public Collection<String> getClassificationNames() throws SQLException { return executeQueryString("SELECT id FROM info WHERE id != 'general' AND id !='edition' ;", 1); } /** * gets the metadata for a certain query result * * @param query String containing the complete SQL query * @return ResultSetMetaData */ private ResultSetMetaData getMetaData(String query) throws SQLException { return connection.createStatement().executeQuery(query).getMetaData(); } /** * setups up the classification name to output index. * * @return index, or max-int, if classification not included in database */ public int[] setupMapClassificationId2DatabaseRank(final String[] classificationNames) throws SQLException { final int[] result = new int[classificationNames.length]; for (int i = 0; i < classificationNames.length; i++) { final int index = getClassificationIndex(classificationNames[i]); result[i] = (index >= 0 ? index - 2 : Integer.MAX_VALUE); } return result; } public static Collection<String> getContainedClassificationsIfDBExists(String fileName) { if (FileUtils.fileExistsAndIsNonEmpty(fileName)) { try (AccessAccessionMappingDatabase accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(fileName)) { return accessAccessionMappingDatabase.getClassificationNames(); } catch (IOException | SQLException ex) { // ignore } } return Collections.emptySet(); } }
16,029
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CreateAccessionMappingDatabase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/accessiondb/CreateAccessionMappingDatabase.java
/* * CreateAccessionMappingDatabase.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.accessiondb; import jloda.util.*; import org.sqlite.SQLiteConfig; import java.io.File; import java.io.IOException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; /** * setup databases for accession lookup * Original implementation: Syliva Siegel, 2019 * Modified and extended by Daniel Huson, 9.2019 */ public class CreateAccessionMappingDatabase { protected final String databaseFile; protected final ArrayList<String> tables; protected final SQLiteConfig config; /** * creates a new database file at the specified location */ public CreateAccessionMappingDatabase(String databaseFile, String info, boolean overwrite) throws IOException, SQLException { this.databaseFile = databaseFile; this.tables = new ArrayList<>(); // setting database configurations, as suggested by suggested by takrl at // https://stackoverflow.com/questions/784173/what-are-the-performance-characteristics-of-sqlite-with-very-large-database-files config = new SQLiteConfig(); config.setCacheSize(ConfigRequests.getCacheSize()); config.setLockingMode(SQLiteConfig.LockingMode.EXCLUSIVE); config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); config.setTempStore(ConfigRequests.isUseTempStoreInMemory()? SQLiteConfig.TempStore.MEMORY: SQLiteConfig.TempStore.DEFAULT); //config.setJournalMode(SQLiteConfig.JournalMode.WAL); if (overwrite) { // check if file already exists and delete it if that is the case. Opening the DB with sqlite // will automatically create a new database try { final File f = new File(databaseFile); if (f.isDirectory() || !f.getParentFile().exists()) { throw new IOException("Invalid file specification"); } } catch (NullPointerException e) { // if f has no parent directory f.getParentFile will cause NullPointerException // this is still a valid path so catching this exception and do nothing } try { Files.deleteIfExists(Paths.get(databaseFile)); // throws no error if file does not exist } catch (FileSystemException | NullPointerException e) { throw new IOException("Failed to delete existing file"); } execute("CREATE TABLE info(id TEXT PRIMARY KEY, info_string TEXT, size NUMERIC );"); } if (info != null) { if (executeQueryString("SELECT info_string FROM info WHERE id = 'general';", 1).size() == 0) execute("INSERT INTO info VALUES ('general', '" + info + "', NULL);"); else execute("UPDATE info SET info_string='" + info + "' WHERE id='general';"); } } /** * inserts a new classifier into the database (separate table). Merging is done in mergeTables() * * @param classificationName name of the classifier used in the db * @param inputFile path to file * @param description description string to describe the used reference */ public void insertClassification(String classificationName, String inputFile, String description) throws SQLException, IOException { insertClassification(classificationName, inputFile, 0, 1, description); } /** * inserts a new classifier into the database (separate table). Merging is done in mergeTables() * * @param classificationName name of the classifier used in the db * @param inputFile path to file * @param description description string to describe the used reference * @param accessionColumn accession column in input file (0-based) * @param classColumn class column in input file (0-based) */ public void insertClassification(String classificationName, String inputFile, int accessionColumn, int classColumn, String description) throws SQLException, IOException { if (classificationName == null) { throw new NullPointerException("classificationName"); } int count = 0; try (var connection = config.createConnection("jdbc:sqlite:" + this.databaseFile); var statement = connection.createStatement()) { statement.execute("CREATE TABLE " + classificationName + "(Accession TEXT PRIMARY KEY, " + classificationName + "_id NUMBER NOT NULL); "); connection.setAutoCommit(false); try (var insertStmd = connection.prepareStatement("INSERT INTO " + classificationName + " VALUES (?, ?);")) { try (var it = new FileLineIterator(inputFile, true)) { while (it.hasNext()) { final var tokens = it.next().split("\t"); if (accessionColumn < tokens.length && classColumn < tokens.length && NumberUtils.isInteger(tokens[classColumn])) { var accession = tokens[accessionColumn]; var value = NumberUtils.parseInt(tokens[classColumn]); if (value != 0) { insertStmd.setString(1, accession); insertStmd.setInt(2, value); insertStmd.execute(); count++; } } } } } connection.commit(); connection.setAutoCommit(true); // write additional information into the info table statement.execute("INSERT INTO info VALUES ('" + classificationName + "', '" + description + "', " + count + ");"); } System.err.printf("Table %s: added %,d items%n", classificationName, count); tables.add(classificationName); } /** * final merge, merging all reference tables into one * takes a long time */ public void mergeTables() throws SQLException { if (tables.size() < 1) { return; } createNCBIRefTable(); joinTables(); cleanAfterJoin(); } /** * creates a new table using ID_ncbi (=ncbi) as name and depending on the activated reference databases * drops any pre-existing table with the same name */ private void createNCBIRefTable() throws SQLException { System.err.println("Creating accession table..."); var createTableCommand = new StringBuilder("CREATE TABLE Accession AS "); for (var i = 0; i < tables.size(); i++) { if (i > 0) createTableCommand.append(" UNION "); createTableCommand.append("SELECT Accession FROM ").append(tables.get(i)); } createTableCommand.append(";"); execute("DROP TABLE IF EXISTS Accession;", createTableCommand.toString()); } /** * Creates the joining query variably and then performs the join. Resulting table is called ID_mappings (= mappings) */ private void joinTables() throws SQLException { System.err.println("Joining tables..."); // when adding more classifications after initial merging this should enable the user to do so String renameQuery; if (tables.contains("mappings")) { renameQuery = "ALTER TABLE mappings RENAME TO temp;"; tables.add("temp"); tables.remove("mappings"); } else renameQuery = "DROP TABLE IF EXISTS mappings;"; // create query string based on which reference dbs are used var createMappingsCommand = new StringBuilder("CREATE TABLE mappings (Accession PRIMARY KEY "); var fillMappingCommand = new StringBuilder(" INSERT INTO mappings SELECT * FROM Accession AS n "); for (var table : tables) { if (table.equals("temp")) { // add all rows of temp (except accession) createMappingsCommand.append(getTablesAlreadyIncluded()); } else { createMappingsCommand.append(", ").append(table).append(" INT"); } fillMappingCommand.append("LEFT OUTER JOIN ").append(table).append(" USING (").append("Accession").append(") "); } // turn row ids column off createMappingsCommand.append(") WITHOUT ROWID;"); fillMappingCommand.append(";"); // finishing the query // executing the queries execute(renameQuery, createMappingsCommand.toString(), fillMappingCommand.toString()); } /** * get all tables already included in the mappings table (at this point renamed to temp) * * @return tables */ private String getTablesAlreadyIncluded() throws SQLException { var buf = new StringBuilder(); try (var connection = createConnection(); var rs = connection.createStatement().executeQuery("SELECT id FROM info WHERE id != 'general';")) { while (rs.next()) { var s = rs.getString("id"); if (!tables.contains(s)) { buf.append(", ").append(s).append(" INT"); } } } return buf.toString(); } /** * performs the cleanUp after Joining the tables into one. * drops the merged tables and performs a VACUUM */ private void cleanAfterJoin() throws SQLException { System.err.println("Cleaning up..."); tables.add("Accession"); var commands = new String[tables.size() + 1]; for (var i = 0; i < tables.size(); i++) { if (!tables.get(i).equals("mappings")) { commands[i] = "DROP TABLE IF EXISTS " + tables.get(i) + ";"; } } commands[tables.size()] = "VACUUM;"; execute(commands); tables.clear(); tables.add("mappings"); // finally update the size information in the info table var size = computeSize("mappings"); execute("UPDATE info SET size = " + size + " WHERE id = 'general';"); } /** * queries the table tableName and returns the number of rows in that table * * @param tableName name of the table * @return size of the table tableName */ private int computeSize(String tableName) throws SQLException { var count = 0; try (var connection = createConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT count(*) AS q FROM " + tableName + ";")) { while (rs.next()) { count = rs.getInt("q"); // todo: is this correct? } } return count; } /** * adds a new column * */ public void addNewColumn(String classificationName, String inputFile, String description) throws SQLException, IOException { addNewColumn(classificationName, inputFile, 0, description, '\t'); } /** * adds a new column * */ public void addNewColumn(String classificationName, String inputFile, int column, String description, char separator) throws SQLException, IOException { if (classificationName == null) { throw new NullPointerException("classificationName"); } var count = 0; var tokenPos = column + 1; try (var connection = createConnection(); var statement = connection.createStatement()) { statement.execute("ALTER TABLE mappings ADD COLUMN " + classificationName + " INTEGER;"); connection.setAutoCommit(false); try (var insert = connection.prepareStatement("UPDATE mappings SET " + classificationName + "=? WHERE Accession=?")) { try (var it = new FileLineIterator(inputFile, true)) { while (it.hasNext()) { var line = it.next(); var tokens = StringUtils.split(line, separator); if (tokens.length > tokenPos) { var accession = tokens[0]; var value = NumberUtils.parseInt(tokens[tokenPos]); if (value != 0) { insert.setString(2, accession); insert.setInt(1, value); insert.execute(); count++; } } } } } connection.commit(); connection.setAutoCommit(true); statement.execute("INSERT INTO info VALUES ('" + classificationName + "', '" + description + "', " + count + ");"); } } public Connection createConnection() throws SQLException { return config.createConnection("jdbc:sqlite:" + this.databaseFile); } /** * executes a list of commands * * @param commands String[] of complete queries * @throws SQLException if something goes wrong with the database */ public void execute(String... commands) throws SQLException { try (var connection = createConnection()) { execute(connection, commands); } } /** * executes a list of commands */ public static void execute(Connection connection, String... commands) throws SQLException { if (false) System.err.println("execute:\n" + StringUtils.toString(commands, "\n")); var statement = connection.createStatement(); { for (var q : commands) { statement.execute(q); } } } /** * generic method for executing queries with results of type String */ public ArrayList<String> executeQueryString(String query, int index) throws SQLException { try (var connection = createConnection()) { return executeQueryString(connection, query, index); } } /** * generic method for executing queries with results of type String */ public static ArrayList<String> executeQueryString(Connection connection, String query, int index) throws SQLException { var rs = connection.createStatement().executeQuery(query); var result = new ArrayList<String>(); while (rs.next()) { result.add(rs.getString(index)); } return result; } }
15,471
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AccessAccessionAdapter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/accessiondb/AccessAccessionAdapter.java
/* * AccessAccessionAdapter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.accessiondb; import megan.classification.data.IString2IntegerMap; import java.io.IOException; import java.sql.SQLException; /** * adapts database accession mapping * Daniel Huson, 9.2019 */ public class AccessAccessionAdapter implements IString2IntegerMap { private final AccessAccessionMappingDatabase accessAccessionMappingDatabase; private final String classificationName; private final int size; private final String mappingDBFile; /** * constructor * */ public AccessAccessionAdapter(final String mappingDBFile, final String classificationName) throws IOException, SQLException { this.mappingDBFile = mappingDBFile; accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(mappingDBFile); this.classificationName = classificationName; size = accessAccessionMappingDatabase.getSize(classificationName); } @Override public int get(String accession) { try { return accessAccessionMappingDatabase.getValue(classificationName, accession); } catch (Exception e) { return 0; } } @Override public int size() { return size; } @Override public void close() { accessAccessionMappingDatabase.close(); } public String getMappingDBFile() { return mappingDBFile; } public AccessAccessionMappingDatabase getAccessAccessionMappingDatabase() { return accessAccessionMappingDatabase; } }
2,335
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ModifyAccessionMappingDatabase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/accessiondb/ModifyAccessionMappingDatabase.java
/* * ModifyAccessionMappingDatabase.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.accessiondb; import jloda.util.FileLineIterator; import jloda.util.NumberUtils; import org.sqlite.SQLiteConfig; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * Modify SQLITE database * Daniel Huson, 212.2019 */ public class ModifyAccessionMappingDatabase { protected final String databaseFile; protected final SQLiteConfig config; /** * constructor * */ public ModifyAccessionMappingDatabase(String databaseFile) throws IOException, SQLException { this.databaseFile = databaseFile; System.err.println("Database '" + databaseFile + "', current contents: "); try (AccessAccessionMappingDatabase accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(databaseFile)) { System.err.println(accessAccessionMappingDatabase.getInfo()); } config = new SQLiteConfig(); config.setCacheSize(10000); config.setLockingMode(SQLiteConfig.LockingMode.EXCLUSIVE); config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); config.setJournalMode(SQLiteConfig.JournalMode.WAL); } /** * executes a list of commands * * @param commands String[] of complete queries * @throws SQLException if something goes wrong with the database */ private void execute(String... commands) throws SQLException { try (Connection connection = config.createConnection("jdbc:sqlite:" + this.databaseFile); Statement statement = connection.createStatement()) { for (String q : commands) { statement.execute(q); } } } /** * adds a new column * */ public void addNewColumn(String classificationName, String inputFile, String description) throws SQLException, IOException { if (classificationName == null) { throw new NullPointerException("classificationName"); } int count = 0; try (Connection connection = config.createConnection("jdbc:sqlite:" + this.databaseFile); Statement statement = connection.createStatement()) { statement.execute("ALTER TABLE mappings ADD COLUMN '" + classificationName + "' INTEGER;"); connection.setAutoCommit(false); try (PreparedStatement insertStmd = connection.prepareStatement("UPDATE mappings SET '" + classificationName + "'=? WHERE Accession=?")) { try (FileLineIterator it = new FileLineIterator(inputFile, true)) { while (it.hasNext()) { final String[] tokens = it.next().split("\t"); final String accession = tokens[0]; final int value = NumberUtils.parseInt(tokens[1]); if (value != 0) { insertStmd.setString(2, accession); insertStmd.setInt(1, value); insertStmd.execute(); count++; } } } } System.err.println("Committing..."); connection.commit(); connection.setAutoCommit(true); statement.execute("INSERT INTO info VALUES ('" + classificationName + "', '" + description + "', " + count + ");"); } } }
4,239
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ContaminantManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/ContaminantManager.java
/* * ContaminantManager.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.graph.Edge; import jloda.graph.Node; import jloda.util.FileLineIterator; import jloda.util.NumberUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.data.IReadBlock; import megan.viewer.TaxonomyData; import java.io.IOException; import java.io.StringReader; import java.util.BitSet; import java.util.HashSet; import java.util.Set; import static java.io.StreamTokenizer.TT_EOF; /** * represents taxa known to be contaminants of a sample * Daniel Huson, 11.2017 */ public class ContaminantManager { private final Set<Integer> contaminants = new HashSet<>(); private final Set<Integer> contaminantsAndDescendants = new HashSet<>(); /** * read the internal nodes definition. Does not prepare for use * */ public void read(String file) throws IOException { contaminants.clear(); contaminantsAndDescendants.clear(); try (FileLineIterator it = new FileLineIterator(file)) { while (it.hasNext()) { final String aLine = it.next().trim(); if (aLine.length() > 0) { if (Character.isLetter(aLine.charAt(0))) { // is a single taxon name final int taxonId = TaxonomyData.getName2IdMap().get(aLine); if (taxonId != 0) contaminants.add(taxonId); else System.err.println("Failed to identify taxon for: '" + aLine + "'"); } else { try (NexusStreamParser np = new NexusStreamParser(new StringReader(aLine))) { while ((np.peekNextToken()) != TT_EOF) { final String token = np.getWordRespectCase(); final int taxonId; if (NumberUtils.isInteger(token)) taxonId = NumberUtils.parseInt(token); else taxonId = TaxonomyData.getName2IdMap().get(token); if (taxonId > 0) contaminants.add(taxonId); else System.err.println("Failed to identify taxon for: '" + token + "'"); } } } } } } if (contaminants.size() > 0) { setAllDescendentsRec(TaxonomyData.getTree().getRoot(), contaminants.contains((Integer) TaxonomyData.getTree().getRoot().getInfo()), contaminants, contaminantsAndDescendants); System.err.printf("Contaminants: %,d input, %,d total%n", contaminants.size(), contaminantsAndDescendants.size()); } } /** * recursively set the all nodes set * */ private void setAllDescendentsRec(Node v, boolean mustAddToAll, Set<Integer> internalNodes, Set<Integer> allNodes) { if (!mustAddToAll && internalNodes.contains((Integer) v.getInfo())) mustAddToAll = true; if (mustAddToAll) allNodes.add((Integer) v.getInfo()); for (Edge e : v.outEdges()) { setAllDescendentsRec(e.getTarget(), mustAddToAll, internalNodes, allNodes); } } public int inputSize() { return contaminants.size(); } public int size() { return contaminantsAndDescendants.size(); } /** * parse a string of ids and prepare for use * */ public void parseTaxonIdsString(String taxonIdString) { contaminants.clear(); contaminantsAndDescendants.clear(); for (String word : StringUtils.splitOnWhiteSpace(taxonIdString)) { if (NumberUtils.isInteger(word)) { final int taxonId = NumberUtils.parseInt(word); if (taxonId > 0) contaminants.add(taxonId); } } if (contaminants.size() > 0) setAllDescendentsRec(TaxonomyData.getTree().getRoot(), contaminants.contains((Integer) TaxonomyData.getTree().getRoot().getInfo()), contaminants, contaminantsAndDescendants); } /** * determines whether a short read is a contaminant based on whether it has a good alignment against a contaminant * * @return true if contaminant */ public boolean isContaminantShortRead(IReadBlock readBlock, BitSet activeMatches) { for (int i = activeMatches.nextSetBit(0); i != -1; i = activeMatches.nextSetBit(i + 1)) { if (contaminantsAndDescendants.contains(readBlock.getMatchBlock(i).getTaxonId())) return true; } return false; } /** * determines whether a long read is a contaminant based on its assigned taxon * */ public boolean isContaminantLongRead(int assignedTaxon) { return contaminantsAndDescendants.contains(assignedTaxon); } /** * gets all contaminants as string of taxon ids * * @return taxon ids */ public String getTaxonIdsString() { return StringUtils.toString(contaminants, " "); } /** * get iterable over all contaminants * * @return iterable */ public Iterable<Integer> getContaminants() { return contaminants; } }
5,847
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Document.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/Document.java
/* * Document.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.seq.BlastMode; import jloda.swing.util.ColorTableManager; import jloda.swing.util.ILabelGetter; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.CanceledException; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import jloda.util.progress.ProgressCmdLine; import jloda.util.progress.ProgressListener; import megan.algorithms.DataProcessor; import megan.chart.ChartColorManager; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.classification.data.SyncDataTableAndClassificationViewer; import megan.daa.connector.DAAConnector; import megan.daa.io.DAAParser; import megan.data.IConnector; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import megan.ms.client.connector.MSConnector; import megan.rma3.RMA3File; import megan.rma6.RMA6File; import megan.viewer.ClassificationViewer; import megan.viewer.SyncDataTableAndTaxonomy; import megan.viewer.TaxonomyData; import java.awt.*; import java.io.*; import java.util.List; import java.util.*; import static megan.chart.ChartColorManager.SAMPLE_ID; /** * The main document * Daniel Huson 11.2005, 4.2017 */ public class Document { public enum LCAAlgorithm { naive, weighted, longReads; public static LCAAlgorithm valueOfIgnoreCase(String str) { return StringUtils.valueOfIgnoreCase(LCAAlgorithm.class, str); } } public enum ReadAssignmentMode { readCount, readLength, alignedBases, readMagnitude; public static ReadAssignmentMode valueOfIgnoreCase(String label) { return StringUtils.valueOfIgnoreCase(ReadAssignmentMode.class, label); } public String getDisplayLabel() { return switch (this) { case readCount -> "Number of reads"; case readLength -> "Number of bases"; case alignedBases -> "Number of aligned bases"; case readMagnitude -> "Sum of read magnitudes"; }; } } private final static Map<String, String> name2versionInfo = new HashMap<>(); // used to track versions of tree etc private long numberReads = 0; private long additionalReads = 0; public boolean neverOpenedReads = true; private final DataTable dataTable = new DataTable(); private final SelectionSet sampleSelection = new SelectionSet(); private boolean dirty = false; // to true when imported from blast files public final static float DEFAULT_MINSCORE = 50; // this is aimed at reads of length 100 public final static float DEFAULT_MAXEXPECTED = 0.01f; // maximum e-value public final static float DEFAULT_MIN_PERCENT_IDENTITY = 0f; public final static float DEFAULT_TOPPERCENT = 10; // in percent public final static int DEFAULT_MINSUPPORT = 0; public final static float DEFAULT_MINSUPPORT_PERCENT = 0.01f; // in percent public static final LCAAlgorithm DEFAULT_LCA_ALGORITHM_SHORT_READS = LCAAlgorithm.naive; public static final LCAAlgorithm DEFAULT_LCA_ALGORITHM_LONG_READS = LCAAlgorithm.longReads; public final static int DEFAULT_MIN_READ_LENGTH=0; public final static float DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS = 100; public final static float DEFAULT_LCA_COVERAGE_PERCENT_WEIGHTED_LCA = 80; public final static float DEFAULT_LCA_COVERAGE_PERCENT_LONG_READS = 51; public final static float DEFAULT_MINCOMPLEXITY = 0f; public final static float DEFAULT_MIN_PERCENT_READ_TO_COVER = 0f; public final static float DEFAULT_MIN_PERCENT_REFERENCE_TO_COVER = 0f; public static final boolean DEFAULT_USE_IDENTITY = false; public static final boolean DEFAULT_LONG_READS = false; public static final ReadAssignmentMode DEFAULT_READ_ASSIGNMENT_MODE_SHORT_READS = ReadAssignmentMode.readCount; public static final ReadAssignmentMode DEFAULT_READ_ASSIGNMENT_MODE_LONG_READS = ReadAssignmentMode.alignedBases; private float minScore = DEFAULT_MINSCORE; private float maxExpected = DEFAULT_MAXEXPECTED; private float minPercentIdentity = DEFAULT_MIN_PERCENT_IDENTITY; private float topPercent = DEFAULT_TOPPERCENT; private float minSupportPercent = DEFAULT_MINSUPPORT_PERCENT; // if this is !=0, overrides explicit minSupport value and uses percentage of assigned reads private int minSupport = DEFAULT_MINSUPPORT; // min summary count that a node needs to make it into the induced taxonomy private LCAAlgorithm lcaAlgorithm = DEFAULT_LCA_ALGORITHM_SHORT_READS; private float lcaCoveragePercent = DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS; private float minComplexity = DEFAULT_MINCOMPLEXITY; private int minReadLength= DEFAULT_MIN_READ_LENGTH; private float minPercentReadToCover = DEFAULT_MIN_PERCENT_READ_TO_COVER; private float minPercentReferenceToCover = DEFAULT_MIN_PERCENT_READ_TO_COVER; private boolean useIdentityFilter = DEFAULT_USE_IDENTITY; private boolean longReads = DEFAULT_LONG_READS; private boolean useContaminantFilter = false; private long lastRecomputeTime = 0; private final MeganFile meganFile = new MeganFile(); private ProgressListener progressListener = new ProgressCmdLine(); // for efficiency, allow only one private boolean pairedReads = false; // treat reads as paired private int significanceTestCorrection = -1; private boolean highlightContrasts = false; private Director dir; private final SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); private ChartColorManager chartColorManager; private final ILabelGetter sampleLabelGetter; private java.awt.Color[] colorsArray = null; // set of active fViewers private final Set<String> activeViewers = new HashSet<>(); private int pairedReadSuffixLength; private boolean openDAAFileOnlyIfMeganized = true; private ReadAssignmentMode readAssignmentMode = DEFAULT_READ_ASSIGNMENT_MODE_SHORT_READS; /** * constructor */ public Document() { //fullTaxonomy.getInduceTaxonomy(collapsedTaxa, false, inducedTaxonomy); setupChartColorManager(false); sampleLabelGetter = name -> { String label = getSampleAttributeTable().getSampleLabel(name); if (label != null) return label; // return label + " (" + Basic.abbreviateDotDotDot(name, 15) + ")"; else return name; }; setLcaCoveragePercent((float) ProgramProperties.get("WeightedLCAPercent", DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS)); } public Director getDir() { return dir; } public void setDir(Director dir) { this.dir = dir; } /** * setup the chart color manager * */ public void setupChartColorManager(boolean useProgramColorTable) { ChartColorManager.initialize(); if (!useProgramColorTable) { chartColorManager = new ChartColorManager(ColorTableManager.getDefaultColorTable()); chartColorManager.setHeatMapTable(ColorTableManager.getDefaultColorTableHeatMap().getName()); chartColorManager.setSeriesOverrideColorGetter(label -> getSampleAttributeTable().getSampleColor(label)); } else { chartColorManager = ChartColorManager.programChartColorManager; } } /** * erase all reads */ public void clearReads() { dataTable.clear(); setNumberReads(0); } /** * load data from the set file * */ public void loadMeganFile() throws IOException { clearReads(); //getProgressListener().setTasks("Loading MEGAN File", getMeganFile().getName()); if (getMeganFile().isMeganSummaryFile() && !getMeganFile().isMeganServerFile()) { loadMeganSummaryFile(); } else if (getMeganFile().hasDataConnector() || getMeganFile().isMeganServerFile()) { reloadFromConnector(null); } else if (!FileUtils.fileExistsAndIsNonEmpty(getMeganFile().getFileName())) throw new IOException("File doesn't exist or is empty: " + getMeganFile().getFileName()); else throw new IOException("Unknown file error (perhaps invalid file format?)"); lastRecomputeTime = System.currentTimeMillis(); } /** * reload from connector * */ private void reloadFromConnector(String parametersOverride) throws IOException { if (getMeganFile().isMeganServerFile() && getMeganFile().isMeganSummaryFile()) { final MSConnector msConnector = new MSConnector(getMeganFile().getFileName()); msConnector.loadMeganSummaryFile(this); } else if (getMeganFile().hasDataConnector()) { final IConnector connector = getConnector(); SyncArchiveAndDataTable.syncArchive2Summary(getReadAssignmentMode(), getMeganFile().getFileName(), connector, getDataTable(), getSampleAttributeTable()); setNumberReads(getDataTable().getTotalReads()); setAdditionalReads(getDataTable().getAdditionalReads()); getActiveViewers().clear(); getActiveViewers().addAll(Arrays.asList(connector.getAllClassificationNames())); final String parameters = (parametersOverride != null ? parametersOverride : getDataTable().getParameters()); if (parameters != null) { parseParameterString(parameters); } if (connector.getNumberOfReads() > 0) { SyncArchiveAndDataTable.syncRecomputedArchive2Summary(getReadAssignmentMode(), FileUtils.replaceFileSuffix(getMeganFile().getName(), ""), "merge", getDataTable().getBlastMode(), "", connector, dataTable, 0); } getSampleAttributeTable().addAttribute(SampleAttributeTable.HiddenAttribute.Source.toString(), getMeganFile().getFileName(), true); loadColorTableFromDataTable(); } } /** * load color table from data table */ public void loadColorTableFromDataTable() { if (getDataTable().getColorTable() != null) { getChartColorManager().setColorTable(getDataTable().getColorTable(), getDataTable().isColorByPosition()); if (getDataTable().getColorTableHeatMap() != null) { getChartColorManager().setHeatMapTable(getDataTable().getColorTableHeatMap()); getDataTable().setColorTableHeatMap(getChartColorManager().getHeatMapTable().getName()); // this ensures that we save a valid name back to the file } } getChartColorManager().setAttributeStateColorPositions(SAMPLE_ID, getSampleNames()); if (!getChartColorManager().isUsingProgramColors()) getChartColorManager().loadColorEdits(getDataTable().getColorEdits()); } /** * parse an algorithm parameter string * */ public void parseParameterString(String parameters) { if (parameters != null && parameters.length() > 0) { try { NexusStreamParser np = new NexusStreamParser(new StringReader(parameters)); List<String> tokens = np.getTokensRespectCase(null, null); setMinScore(np.findIgnoreCase(tokens, "minScore=", getMinScore())); setMaxExpected(np.findIgnoreCase(tokens, "maxExpected=", getMaxExpected())); setMinPercentIdentity(np.findIgnoreCase(tokens, "minPercentIdentity=", getMinPercentIdentity())); setTopPercent(np.findIgnoreCase(tokens, "topPercent=", getTopPercent())); setMinSupportPercent(np.findIgnoreCase(tokens, "minSupportPercent=", 0f)); setMinSupport((int) np.findIgnoreCase(tokens, "minSupport=", getMinSupport())); setLcaAlgorithm(LCAAlgorithm.naive); // legacy support: { if (np.findIgnoreCase(tokens, "weightedLCA=true", true, false)) setLcaAlgorithm(LCAAlgorithm.weighted); else if (np.findIgnoreCase(tokens, "weightedLCA=false", true, false)) setLcaAlgorithm(LCAAlgorithm.naive); else if (np.findIgnoreCase(tokens, "lcaAlgorithm=NaiveLongRead", true, false)) setLcaAlgorithm(LCAAlgorithm.naive); else if (np.findIgnoreCase(tokens, "lcaAlgorithm=CoverageLongRead", true, false)) setLcaAlgorithm(LCAAlgorithm.longReads); } for (LCAAlgorithm algorithm : LCAAlgorithm.values()) { if (np.findIgnoreCase(tokens, "lcaAlgorithm=" + algorithm, true, false)) { setLcaAlgorithm(algorithm); break; } } setLcaCoveragePercent(np.findIgnoreCase(tokens, "lcaCoveragePercent=", getLcaCoveragePercent())); setMinPercentReadToCover(np.findIgnoreCase(tokens, "minPercentReadToCover=", getMinPercentReadToCover())); setMinPercentReferenceToCover(np.findIgnoreCase(tokens, "minPercentReferenceToCover=", getMinPercentReferenceToCover())); setMinComplexity(np.findIgnoreCase(tokens, "minComplexity=", getMinComplexity())); setMinReadLength(Math.round(np.findIgnoreCase(tokens,"minReadLength=",getMinReadLength()))); if (np.findIgnoreCase(tokens, "longReads=true", true, false)) setLongReads(true); else if (np.findIgnoreCase(tokens, "longReads=false", true, false)) setLongReads(false); if (np.findIgnoreCase(tokens, "pairedReads=true", true, false)) setPairedReads(true); else if (np.findIgnoreCase(tokens, "pairedReads=false", true, false)) setPairedReads(false); if (np.findIgnoreCase(tokens, "identityFilter=true", true, false)) setUseIdentityFilter(true); else if (np.findIgnoreCase(tokens, "identityFilter=false", true, false)) setUseIdentityFilter(false); if (np.findIgnoreCase(tokens, "contaminantFilter=true", true, false)) setUseContaminantFilter(true); else if (np.findIgnoreCase(tokens, "contaminantFilter=false", true, false)) setUseContaminantFilter(false); boolean readAssignmentModeWasSet = false; //legacy support: { if (np.findIgnoreCase(tokens, "useWeightedReadCounts=true", true, false)) { setReadAssignmentMode(ReadAssignmentMode.readLength); // legacy readAssignmentModeWasSet = true; } else if (np.findIgnoreCase(tokens, "useWeightedReadCounts=false", true, false)) { setReadAssignmentMode(ReadAssignmentMode.readCount); // legacy readAssignmentModeWasSet = true; } } for (ReadAssignmentMode readAssignmentMode : ReadAssignmentMode.values()) { if (np.findIgnoreCase(tokens, "readAssignmentMode=" + readAssignmentMode, true, false)) { setReadAssignmentMode(readAssignmentMode); readAssignmentModeWasSet = true; break; } } if (!readAssignmentModeWasSet) setReadAssignmentMode(DEFAULT_READ_ASSIGNMENT_MODE_SHORT_READS); { String fNamesString = (np.findIgnoreCase(tokens, "fNames=", "{", "}", "").trim()); if (fNamesString.length() > 0) { final Set<String> cNames = new HashSet<>(Arrays.asList(fNamesString.split("\\s+"))); if (cNames.size() > 0) { getActiveViewers().clear(); for (final String cName : cNames) { if (cName.length() > 0) { if (ClassificationManager.getAllSupportedClassifications().contains(cName)) getActiveViewers().add(cName); // else System.err.println("Unknown classification name: '" + cName + "': ignored"); } } getActiveViewers().add(Classification.Taxonomy); } } } } catch (IOException e) { Basic.caught(e); } } } /** * write an algorithm parameter string * * @return parameter string */ public String getParameterString() { StringBuilder buf = new StringBuilder(); buf.append("minScore=").append(getMinScore()); buf.append(" maxExpected='").append(getMaxExpected()).append("'"); buf.append(" minPercentIdentity='").append(getMinPercentIdentity()).append("'"); buf.append(" topPercent=").append(getTopPercent()); buf.append(" minSupportPercent=").append(getMinSupportPercent()); buf.append(" minSupport=").append(getMinSupport()); buf.append(" lcaAlgorithm=").append(getLcaAlgorithm().toString()); if (getLcaAlgorithm() == LCAAlgorithm.weighted || getLcaAlgorithm() == LCAAlgorithm.longReads) buf.append(" lcaCoveragePercent=").append(getLcaCoveragePercent()); buf.append(" minPercentReadToCover=").append(getMinPercentReadToCover()); buf.append(" minPercentReferenceToCover=").append(getMinPercentReferenceToCover()); if(getMinComplexity()>0) buf.append(" minComplexity=").append(getMinComplexity()); if(getMinReadLength()>0) buf.append(" minReadLength=").append(getMinReadLength()); buf.append(" longReads=").append(isLongReads()); buf.append(" pairedReads=").append(isPairedReads()); buf.append(" identityFilter=").append(isUseIdentityFilter()); if (isUseContaminantFilter() && dataTable.hasContaminants()) buf.append(" contaminantFilter=").append(isUseContaminantFilter()); buf.append(" readAssignmentMode=").append(getReadAssignmentMode().toString()); if (getActiveViewers().size() > 0) { buf.append(" fNames= {"); for (String cName : getActiveViewers()) { buf.append(" ").append(cName); } buf.append(" }"); } return buf.toString(); } /** * load the set megan summary file */ public void loadMeganSummaryFile() throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtils.getInputStreamPossiblyZIPorGZIP(getMeganFile().getFileName())))) { loadMeganSummary(reader); } } public void loadMeganSummary(BufferedReader reader) throws IOException { getDataTable().read(reader, false); final List<String> sampleNames=getSampleNames(); getSampleAttributeTable().read(reader, sampleNames, true); final List<String> order=getSampleAttributeTable().getSampleOrder(); if(order!=null && order.size()==sampleNames.size() && order.containsAll(sampleNames) && !order.equals(sampleNames)) getDataTable().reorderSamples(order); String parameters = getDataTable().getParameters(); if (parameters != null) { parseParameterString(parameters); } getActiveViewers().clear(); getActiveViewers().addAll(getDataTable().getClassification2Class2Counts().keySet()); loadColorTableFromDataTable(); } /** * get the sample selection * * @return sample selection */ public SelectionSet getSampleSelection() { return sampleSelection; } /** * get the set progress listener * * @return progress listener */ public ProgressListener getProgressListener() { return progressListener; } /** * set the progress listener * */ public void setProgressListener(ProgressListener progressListener) { this.progressListener = progressListener; } /** * gets the document title * * @return title */ public String getTitle() { return getMeganFile().getName(); } public float getMinScore() { return minScore; } public void setMinScore(float minScore) { this.minScore = minScore; } public float getMaxExpected() { return maxExpected; } public void setMaxExpected(float maxExpected) { this.maxExpected = maxExpected; } public float getMinPercentIdentity() { return minPercentIdentity; } public void setMinPercentIdentity(float minPercentIdentity) { this.minPercentIdentity = minPercentIdentity; } public float getTopPercent() { return topPercent; } public void setTopPercent(float topPercent) { this.topPercent = topPercent; } public boolean isLongReads() { return longReads; } public void setLongReads(boolean longReads) { this.longReads = longReads; } /** * process the given reads */ public void processReadHits() throws CanceledException { if (!getMeganFile().isMeganSummaryFile() && getMeganFile().hasDataConnector()) { try { final int readsFound = DataProcessor.apply(this); // rescan size: { getSampleAttributeTable().addAttribute("Size", numberReads, true); } try { saveAuxiliaryData(); } catch (IOException e) { Basic.caught(e); } if (readsFound > getNumberOfReads()) // rounding in comparison mode may cause an increase by 1 setNumberReads(readsFound); if (getNumberOfReads() == 0 && getDir() != null) getDir().getMainViewer().collapseToDefault(); if (sampleAttributeTable.getSampleOrder().size() == 0) sampleAttributeTable.setSampleOrder(getSampleNames()); } finally { getProgressListener().setCancelable(true); } } lastRecomputeTime = System.currentTimeMillis(); } /** * writes auxiliary data to archive * */ public void saveAuxiliaryData() throws IOException { if (getMeganFile().hasDataConnector() && !getMeganFile().isReadOnly()) { if (dir != null) { final var mainViewer = dir.getMainViewer(); if (mainViewer != null) SyncDataTableAndTaxonomy.syncFormattingFromViewer2Summary(mainViewer, getDataTable()); for (String cName : ClassificationManager.getAllSupportedClassifications()) { if (dir.getViewerByClassName(ClassificationViewer.getClassName(cName)) != null && dir.getViewerByClassName(ClassificationViewer.getClassName(cName)) instanceof ClassificationViewer) { ClassificationViewer classificationViewer = (ClassificationViewer) dir.getViewerByClassName(ClassificationViewer.getClassName(cName)); SyncDataTableAndClassificationViewer.syncFormattingFromViewer2Summary(classificationViewer, getDataTable()); } } } getDataTable().setColorTable(getChartColorManager().getColorTableName(), getChartColorManager().isColorByPosition(), getChartColorManager().getHeatMapTable().getName()); getDataTable().setColorEdits(getChartColorManager().getColorEdits()); if (getDataTable().getParameters() == null || getDataTable().getParameters().isEmpty()) getDataTable().setParameters(getParameterString()); getMeganFile().getConnector().putAuxiliaryData(getAuxiliaryData()); } } public Map<String, byte[]> getAuxiliaryData() throws IOException { byte[] userState = getDataTable().getUserStateAsBytes(); byte[] sampleAttributes = getSampleAttributeTable().getBytes(); final Map<String, byte[]> label2data = new HashMap<>(); label2data.put(SampleAttributeTable.USER_STATE, userState); label2data.put(SampleAttributeTable.SAMPLE_ATTRIBUTES, sampleAttributes); return label2data; } public List<String> getClassificationNames() { return new ArrayList<>(getDataTable().getClassification2Class2Counts().keySet()); } /** * get the minimal number of reads required to keep a given taxon * * @return min support */ public int getMinSupport() { return minSupport; } /** * set the minimal number of reads required to hit a givent taxon * */ public void setMinSupport(int minSupport) { this.minSupport = minSupport; } /** * gets the min support percentage value. If this is non-zero, overrides min support value and uses * given percentage of assigned reads * * @return min support percentage */ public float getMinSupportPercent() { return minSupportPercent; } /** * gets the min support percentage * */ public void setMinSupportPercent(float minSupportPercent) { this.minSupportPercent = minSupportPercent; } /** * gets the minimum complexity required of a read * * @return min complexity */ public float getMinComplexity() { return minComplexity; } /** * set the minimum complexity for a read * */ public void setMinComplexity(float minComplexity) { this.minComplexity = minComplexity; } public int getMinReadLength() { return minReadLength; } public void setMinReadLength(int minReadLength) { this.minReadLength = minReadLength; } public float getMinPercentReadToCover() { return minPercentReadToCover; } public void setMinPercentReadToCover(float minPercentReadToCover) { this.minPercentReadToCover = minPercentReadToCover; } public float getMinPercentReferenceToCover() { return minPercentReferenceToCover; } public void setMinPercentReferenceToCover(float minPercentReferenceToCover) { this.minPercentReferenceToCover = minPercentReferenceToCover; } public void setLcaAlgorithm(LCAAlgorithm lcaAlgorithm) { this.lcaAlgorithm = lcaAlgorithm; } public LCAAlgorithm getLcaAlgorithm() { return lcaAlgorithm; } public void setUseContaminantFilter(boolean useContaminantFilter) { this.useContaminantFilter = useContaminantFilter; } public boolean isUseContaminantFilter() { return useContaminantFilter; } /** * is document dirty * * @return true, if dirty */ public boolean isDirty() { return dirty; } /** * set the dirty state * */ public void setDirty(boolean dirty) { this.dirty = dirty; } /** * get number of reads * * @return number of reads */ public long getNumberOfReads() { return numberReads; } /** * set the number of reads * */ public void setNumberReads(long numberReads) { this.numberReads = numberReads; getDataTable().setTotalReads(numberReads); } /** * get additional reads * * @return additional of reads */ public long getAdditionalReads() { return additionalReads; } /** * set the additional of reads * */ public void setAdditionalReads(long additionalReads) { this.additionalReads = additionalReads; getDataTable().setAdditionalReads(additionalReads); } /** * gets the list of samples * * @return sample names */ public List<String> getSampleNames() { return Arrays.asList(getDataTable().getSampleNamesArray()); } /** * get sample names as array. This also ensures that for a file containing only one sample, the sample name always reflects * the current file name * * @return array */ public String[] getSampleNamesAsArray() { return getDataTable().getSampleNamesArray(); } /** * get the number of samples associated with this document * * @return number of samples */ public int getNumberOfSamples() { return dataTable.getNumberOfSamples(); } /** * gets the megan4 summary * * @return megan4 summary */ public DataTable getDataTable() { return dataTable; } /** * gets data for taxon chart. Used by the attributes chart * */ public void getTaxonName2DataSet2SummaryCount(Map<String, Map<String, Number>> label2series2value) { final List<String> samples = getSampleNames(); final String[] id2sample = new String[samples.size()]; for (int i = 0; i < samples.size(); i++) id2sample[i] = samples.get(i); final Map<Integer, float[]> class2counts = dataTable.getClassification2Class2Counts().get(ClassificationType.Taxonomy.toString()); if (class2counts != null) { for (Integer taxId : class2counts.keySet()) { String taxonName = TaxonomyData.getName2IdMap().get(taxId); if (taxonName != null) { Map<String, Number> series2value = label2series2value.computeIfAbsent(taxonName, k -> new TreeMap<>()); float[] counts = class2counts.get(taxId); if (counts != null) { for (int i = 0; i < counts.length; i++) { series2value.put(id2sample[i], counts[i]); } } } } } } /** * load the version of some file. Assumes the file ends on .info * */ static public void loadVersionInfo(String name, String fileName) { try { fileName = FileUtils.replaceFileSuffix(fileName, ".info"); InputStream ins = ResourceManager.getFileAsStream(fileName); BufferedReader r = new BufferedReader(new InputStreamReader(ins)); StringBuilder buf = new StringBuilder(); String aLine; while ((aLine = r.readLine()) != null) buf.append(aLine).append("\n"); r.close(); name2versionInfo.put(name, buf.toString()); } catch (Exception ex) { //System.err.println("No version info for: " + name); name2versionInfo.put(name, null); } } /** * gets the name 2 version info table * * @return version info */ static public Map<String, String> getVersionInfo() { return name2versionInfo; } public float getLcaCoveragePercent() { return lcaCoveragePercent; } public void setLcaCoveragePercent(float lcaCoveragePercent) { this.lcaCoveragePercent = lcaCoveragePercent; } public long getLastRecomputeTime() { return lastRecomputeTime; } public void setLastRecomputeTime(long time) { lastRecomputeTime = time; } public void setSignificanceTestCorrection(int correction) { significanceTestCorrection = correction; } public int getSignificanceTestCorrection() { return significanceTestCorrection; } public boolean isPairedReads() { return pairedReads; } public void setPairedReads(boolean pairedReads) { this.pairedReads = pairedReads; } public MeganFile getMeganFile() { return meganFile; } public boolean isUseIdentityFilter() { return useIdentityFilter; } public void setUseIdentityFilter(boolean useIdentityFilter) { this.useIdentityFilter = useIdentityFilter; } public boolean isHighlightContrasts() { return highlightContrasts; } public void setHighlightContrasts(boolean highlightContrasts) { this.highlightContrasts = highlightContrasts; } public SampleAttributeTable getSampleAttributeTable() { //if (sampleAttributeTable.getSampleOrder().size() == 0) // sampleAttributeTable.getSampleOrder().addAll(getSampleNames()); return sampleAttributeTable; } public ChartColorManager getChartColorManager() { return chartColorManager; } public void setChartColorManager(ChartColorManager chartColorManager) { this.chartColorManager = chartColorManager; } public Color getColorByIndex(int i) { if (colorsArray == null || i >= colorsArray.length) return Color.BLACK; else return colorsArray[i]; } public void setColorByIndex (int i,Color color) { if (colorsArray == null || colorsArray.length < getNumberOfSamples()) { colorsArray = new Color[getNumberOfSamples()]; } colorsArray[i]=color; } /** * gets the set of active functional viewers * * @return active functional viewers */ public Set<String> getActiveViewers() { return activeViewers; } public void setPairedReadSuffixLength(int pairedReadSuffixLength) { this.pairedReadSuffixLength = pairedReadSuffixLength; } public int getPairedReadSuffixLength() { return pairedReadSuffixLength; } /** * gets the blast mode. If it is not yet known, infers it and sets the data table attribute, if necessary * * @return blast mode */ public BlastMode getBlastMode() { BlastMode blastMode = dataTable.getBlastMode(); if (blastMode == BlastMode.Unknown) { if (meganFile.isDAAFile()) { dataTable.setBlastMode(0, DAAParser.getBlastMode(meganFile.getFileName())); } else if (meganFile.isRMA3File()) { try (final RMA3File rma3File = new RMA3File(meganFile.getFileName(), "r")) { dataTable.setBlastMode(0, rma3File.getBlastMode()); } catch (IOException ignored) { } } else if (meganFile.isRMA6File()) { try (final RMA6File rma6File = new RMA6File(meganFile.getFileName(), "r")) { dataTable.setBlastMode(0, rma6File.getHeaderSectionRMA6().getBlastMode()); } catch (IOException ignored) { } } } if (blastMode == BlastMode.Unknown && !meganFile.isMeganSummaryFile() && meganFile.hasDataConnector() && !meganFile.isMeganServerFile()) { try (IReadBlockIterator it = meganFile.getConnector().getAllReadsIterator(1, 10, true, true)) { while (it.hasNext()) { IReadBlock readBlock = it.next(); if (readBlock.getNumberOfAvailableMatchBlocks() > 0) { IMatchBlock matchBlock = readBlock.getMatchBlock(0); if (matchBlock.getText() != null) { if (matchBlock.getText().contains("Frame")) { dataTable.setBlastMode(0, BlastMode.BlastX); } else if (matchBlock.getText().contains("Strand")) { dataTable.setBlastMode(0, BlastMode.BlastN); } else { dataTable.setBlastMode(0, BlastMode.Classifier); } } break; } } } catch (IOException e) { Basic.caught(e); } } return dataTable.getBlastMode(); } public void setBlastMode(BlastMode blastMode) { dataTable.setBlastMode(0, blastMode); } // all the sample stuff below here is chaotic and really needs to be reimplemented... public void renameSample(String oldName, String newName) throws IOException { int pid = StringUtils.getIndex(oldName, getSampleNames()); if (pid != -1) renameSample(pid + 1, newName); } private void renameSample(Integer pid, String newName) throws IOException { if (getSampleNames().contains(newName)) throw new IOException("Can't change sample name, name already used: " + newName); String currentName = getDataTable().getSampleNamesArray()[pid - 1]; getDataTable().changeSampleName(pid - 1, newName); getSampleAttributeTable().renameSample(currentName, newName, true); setDirty(true); try { processReadHits(); } catch (CanceledException e) { Basic.caught(e); } if (getDir() != null) getDir().getMainViewer().setDoReInduce(true); } /** * extract named samples from the given document * */ public void extractSamples(Collection<String> samples, Document srcDoc) { getDataTable().clear(); srcDoc.getDataTable().extractSamplesTo(samples, getDataTable()); getSampleAttributeTable().clear(); getSampleAttributeTable().addTable(srcDoc.getSampleAttributeTable().extractTable(samples), false, true); getSampleAttributeTable().getAttributeOrder().clear(); getSampleAttributeTable().setAttributeOrder(srcDoc.getSampleAttributeTable().getAttributeOrder()); getSampleAttributeTable().getSampleOrder().clear(); getSampleAttributeTable().getSampleOrder().addAll(samples); } /** * add named sample to given document * */ public void addSample(String sample, Document docToAdd) { getDataTable().addSample(sample, docToAdd.getDataTable()); Set<String> samples = new HashSet<>(); samples.add(sample); getSampleAttributeTable().addTable(docToAdd.getSampleAttributeTable().extractTable(samples), false, true); } /** * add named sample to given document * */ public void addSample(String sample, float sampleSize, int srcId, BlastMode blastMode, Map<String, Map<Integer, float[]>> classification2class2counts) { getDataTable().addSample(sample, sampleSize, blastMode, srcId, classification2class2counts); activeViewers.addAll(classification2class2counts.keySet()); } public void reorderSamples(Collection<String> newOrder) throws IOException { getDataTable().reorderSamples(newOrder); getDir().getMainViewer().getSeriesList().sync(Arrays.asList(getDataTable().getOriginalSamples()), null, true); setDirty(true); try { processReadHits(); } catch (CanceledException e) { Basic.caught(e); } getDir().getMainViewer().setDoReInduce(true); } public float getNumberOfReads(String sample) { int i = StringUtils.getIndex(sample, getDataTable().getSampleNamesArray()); if (i == -1) return -1; else return getDataTable().getSampleSizes()[i]; } public IConnector getConnector() { try { IConnector connector = getMeganFile().getConnector(isOpenDAAFileOnlyIfMeganized()); if (connector instanceof DAAConnector) { ((DAAConnector) connector).setLongReads(isLongReads()); } return connector; } catch (IOException e) { Basic.caught(e); } return null; } /** * get the sample label getter * * @return sample label getter */ public ILabelGetter getSampleLabelGetter() { return sampleLabelGetter; } /** * close connector, if there is one */ public void closeConnector() { if (!getMeganFile().isMeganSummaryFile() && getMeganFile().hasDataConnector()) { try { if (isDirty()) { if (getMeganFile().isReadOnly()) System.err.println("File is read-only, discarding changes"); else { if (getParameterString() != null) saveAuxiliaryData(); else System.err.println("Parameter string is null..."); } } MeganFile.removeUIdFromSetOfOpenFiles(getMeganFile().getName(), getMeganFile().getConnector().getUId()); getMeganFile().setFileName(""); } catch (IOException e) { Basic.caught(e); } } } public void setOpenDAAFileOnlyIfMeganized(boolean openDAAFileOnlyIfMeganized) { this.openDAAFileOnlyIfMeganized = openDAAFileOnlyIfMeganized; } private boolean isOpenDAAFileOnlyIfMeganized() { return openDAAFileOnlyIfMeganized; } public ReadAssignmentMode getReadAssignmentMode() { return readAssignmentMode; } public void setReadAssignmentMode(ReadAssignmentMode readAssignmentMode) { this.readAssignmentMode = readAssignmentMode; } }
42,346
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadAssignmentCalculator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/ReadAssignmentCalculator.java
/* * ReadAssignmentCalculator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.swing.util.ProgramProperties; import jloda.util.interval.IntervalTree; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.util.ReadMagnitudeParser; /** * calcuates the values that appear is assigned reads in tree representations * Daniel Huson, 4.2107 */ public class ReadAssignmentCalculator { private final Document.ReadAssignmentMode mode; public ReadAssignmentCalculator(Document.ReadAssignmentMode mode) { this.mode = mode; ReadMagnitudeParser.setUnderScoreEnabled(ProgramProperties.get("allow-read-weights-underscore", false)); } /** * compute the assignment value for this read * * @return assignment value */ public int compute(IReadBlock readBlock, IntervalTree<Object> intervals) { return switch (mode) { default /* case readCount */ -> 1; case readLength -> Math.max(1, readBlock.getReadLength()); case alignedBases -> computeCoveredBases(readBlock, intervals); case readMagnitude -> ReadMagnitudeParser.parseMagnitude(readBlock.getReadHeader(), true); }; } /** * computes the number of bases covered by any alignments * * @return covered bases */ private static int computeCoveredBases(IReadBlock readBlock, IntervalTree<Object> intervals) { if (intervals == null) intervals = new IntervalTree<>(); else intervals.clear(); for (int m = 0; m < readBlock.getNumberOfAvailableMatchBlocks(); m++) { final IMatchBlock matchBlock = readBlock.getMatchBlock(m); intervals.add(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd(), matchBlock); } return intervals.getCovered(); } }
2,627
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TaxonomyEditing.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/TaxonomyEditing.java
/* * TaxonomyEditing.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.graph.Edge; import jloda.graph.Node; import jloda.phylo.PhyloTree; import jloda.util.parse.NexusStreamParser; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.*; /** * supports taxonomy editing * Daniel Huson, 2.2011 */ class TaxonomyEditing { private final List<Edit> list = new LinkedList<>(); private final HashMap<Integer, String> newTaxId2TaxName = new HashMap<>(); /** * applies all edit operations to given tree * */ public void apply(PhyloTree tree, Map<Integer, Node> taxId2Node) { for (Edit edit : list) { switch (edit.type) { case Edit.APPEND: if (taxId2Node.get(edit.taxId) != null) System.err.println("Can't append node, taxId already present: " + edit.taxId); else if (taxId2Node.get(edit.parentId) == null) System.err.println("Can't append node, parentId not present: " + edit.parentId); else { Node v = taxId2Node.get(edit.parentId); if (v != null) { Node w = tree.newNode(); tree.setInfo(w, edit.taxId); tree.newEdge(v, w); taxId2Node.put(edit.taxId, w); System.err.println("Appended node " + edit.taxId + " below " + edit.parentId); } } break; case Edit.DELETE: if (taxId2Node.get(edit.taxId) == null) System.err.println("Can't delete node, taxId not present: " + edit.taxId); else { Node v = taxId2Node.get(edit.taxId); if (v != null) { if (v.getInDegree() == 1) { Node p = v.getFirstInEdge().getOpposite(v); for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getOpposite(v); tree.newEdge(p, w); } tree.deleteNode(v); taxId2Node.remove(edit.taxId); System.err.println("Removed node " + edit.taxId); } } } break; case Edit.RENAME: // do nothing break; default: System.err.println("Unknown edit type: " + edit.type); break; } } } /** * apply the edits to the tax mapping * */ public void apply(Map<Integer, String> taxId2TaxName, Map<String, Integer> taxName2TaxId) { for (Edit edit : list) { switch (edit.type) { case Edit.APPEND -> { taxId2TaxName.put(edit.taxId, edit.taxName); taxName2TaxId.put(edit.taxName, edit.taxId); } case Edit.RENAME -> { taxId2TaxName.put(edit.taxId, edit.taxName); taxName2TaxId.put(edit.taxName, edit.taxId); } case Edit.DELETE -> { taxId2TaxName.remove(edit.taxId); taxName2TaxId.remove(edit.taxName); } default -> { } } } } public void addRemove(int taxId) { list.add(new Edit(taxId)); } public void addAppend(int parentId, int taxId, String taxName) { list.add(new Edit(parentId, taxId, taxName)); newTaxId2TaxName.put(taxId, taxName); } public Iterator<Edit> iterator() { return list.iterator(); } public String toString() { StringWriter w = new StringWriter(); for (Edit edit : list) { w.write(edit.toString() + ";"); } return w.toString(); } public int fromString(String string) throws IOException { NexusStreamParser np = new NexusStreamParser(new StringReader(string)); int count = 0; while (np.peekMatchAnyTokenIgnoreCase("A R")) { Edit edit = Edit.parse(np); if (edit != null) { list.add(edit); np.matchIgnoreCase(";"); } count++; } return count; } } class Edit { public final static int DELETE = 1; public final static int APPEND = 2; public final static int RENAME = 3; public int parentId; public int taxId; public String taxName; public int type; public Edit() { } public Edit(int taxId) { this.taxId = taxId; type = DELETE; } private Edit(int taxId, String taxName) { this.taxId = taxId; this.taxName = taxName; type = RENAME; } public Edit(int parentId, int taxId, String taxName) { this.parentId = parentId; this.taxId = taxId; this.taxName = taxName; type = APPEND; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public int getTaxId() { return taxId; } public void setTaxId(int taxId) { this.taxId = taxId; } public String getTaxName() { return taxName; } public void setTaxName(String taxName) { this.taxName = taxName; } public int getType() { return type; } public void setType(int type) { this.type = type; } /** * write the edit * */ public String toString() { return switch (type) { case APPEND -> "A " + parentId + " " + taxId + " '" + taxName + "'"; case DELETE -> "D " + taxId; case RENAME -> "R " + taxId + " '" + taxName + "'"; default -> "NONE"; }; } /** * attempts to parse an edit string * * @return edit or null */ public static Edit fromString(String string) throws IOException { return parse(new NexusStreamParser(new StringReader(string))); } /** * parse an edit object * * @return edit object */ public static Edit parse(NexusStreamParser np) throws IOException { if (np.peekMatchIgnoreCase("A")) { np.matchIgnoreCase("A"); return new Edit(np.getInt(), np.getInt(), np.getWordRespectCase()); } else if (np.peekMatchIgnoreCase("D")) { np.matchIgnoreCase("D"); return new Edit(np.getInt()); } else if (np.peekMatchIgnoreCase("R")) { np.matchIgnoreCase("R"); return new Edit(np.getInt(), np.getWordRespectCase()); } else return null; } }
7,876
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShapeAndLabelManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/ShapeAndLabelManager.java
/* * ShapeAndLabelManager.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.util.Basic; import jloda.util.NodeShape; import jloda.util.parse.NexusStreamParser; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * manage shapes and labels to be set by sampleViewer and shown by clusterViewer * Daniel Huson, 4.2013 * todo: need to intergrate this */ class ShapeAndLabelManager { private final Map<String, String> sample2label = new HashMap<>(); private final Map<String, NodeShape> sample2shape = new HashMap<>(); /** * get the set label * * @return label */ public String getLabel(String sample) { String label = sample2label.get(sample); if (label == null) return sample; else return label; } /** * set label to use for sample * */ public void setLabel(String sample, String label) { sample2label.put(sample, label); } /** * erase labels */ public void clearLabels() { sample2label.clear(); } /** * are any labels defined? * * @return true, if defined */ public boolean hasLabels() { return sample2label.size() > 0; } /** * get shape for sample * * @return shape */ public NodeShape getShape(String sample) { NodeShape shape = sample2shape.get(sample); return Objects.requireNonNullElse(shape, NodeShape.Oval); } /** * set shape to use with sample * */ public void setShape(String sample, NodeShape shape) { sample2shape.put(sample, shape); } /** * erase shapes */ public void clearShapes() { sample2shape.clear(); } /** * are any shapes defined? * * @return true, if shapes defined */ public boolean hasShapes() { return sample2shape.size() > 0; } /** * write label map as a line * * @return line */ public String getLabelMapAsLine() { StringBuilder buf = new StringBuilder(); for (String sample : sample2label.keySet()) { buf.append(" '").append(sample).append("': '").append(sample2label.get(sample)).append("'"); } buf.append(";"); return buf.toString(); } /** * write shape map as a line * * @return line */ public String getShapeMapAsLine() { StringBuilder buf = new StringBuilder(); for (String sample : sample2shape.keySet()) { buf.append(" '").append(sample).append("': '").append(sample2shape.get(sample)).append("'"); } buf.append(";"); return buf.toString(); } /** * parse label map from line * */ public void parseLabelMapFromLine(String labelMapAsLine) { NexusStreamParser np = new NexusStreamParser(new StringReader(labelMapAsLine)); try { while (!np.peekMatchIgnoreCase(";")) { String sample = np.getWordRespectCase(); np.matchIgnoreCase(":"); String label = np.getWordRespectCase(); sample2label.put(sample, label); } } catch (IOException ex) { Basic.caught(ex); } } /** * parse label map from line * */ public void parseShapeMapFromLine(String shapeMapAsLine) { NexusStreamParser np = new NexusStreamParser(new StringReader(shapeMapAsLine)); try { while (!np.peekMatchIgnoreCase(";")) { String sample = np.getWordRespectCase(); np.matchIgnoreCase(":"); String shapeLabel = np.getWordRespectCase(); NodeShape shape = NodeShape.valueOfIgnoreCase(shapeLabel); sample2shape.put(sample, shape); } } catch (IOException ex) { Basic.caught(ex); } } }
4,775
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Director.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/Director.java
/* * Director.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.fx.util.ProgramExecutorService; import jloda.swing.commands.CommandManager; import jloda.swing.director.*; import jloda.swing.message.MessageWindow; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ProgressDialog; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.CanceledException; import jloda.util.progress.ProgressCmdLine; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import megan.util.WindowUtilities; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Future; /** * the megan director * Daniel Huson, 2005 */ public class Director implements IDirectableViewer, IDirector { private int id; private MainViewer viewer; private final Document doc; private boolean docInUpdate = false; private final List<IDirectableViewer> viewers = new LinkedList<>(); private final List<IDirectorListener> directorListeners = new LinkedList<>(); private Future future; private boolean internalDocument = false; // will this remain hidden private IProjectsChangedListener projectsChangedListener; private boolean locked = false; /** * create a new director * */ public Director(Document doc) { this.doc = doc; } /** * add a viewer to this doc * */ public IDirectableViewer addViewer(IDirectableViewer viewer) { if (viewer instanceof MainViewer) this.viewer = (MainViewer) viewer; viewers.add(viewer); directorListeners.add(viewer); ProjectManager.projectWindowChanged(this, viewer, true); return viewer; } /** * remove a viewer from this doc * */ public void removeViewer(IDirectableViewer viewer) { viewers.remove(viewer); directorListeners.remove(viewer); ProjectManager.projectWindowChanged(this, viewer, false); if (viewers.isEmpty()) ProjectManager.removeProject(this); } /** * returns the list of viewers * * @return viewers */ public List<IDirectableViewer> getViewers() { return viewers; } /** * waits until all viewers are uptodate */ private void WaitUntilAllViewersAreUptoDate() { while (!isAllViewersUptodate()) { try { Thread.sleep(10); } catch (Exception ignored) { } } } /** * returns true, if all viewers are uptodate * * @return true, if all viewers uptodate */ private boolean isAllViewersUptodate() { for (IDirectableViewer viewer : viewers) { if (!viewer.isUptoDate()) { //System.err.println("not up-to-date: "+viewer.getTitle()+" "+viewer.getClass().get()); return false; } } return true; } /** * notify listeners that viewers should be updated * * @param what what should be updated? */ public void notifyUpdateViewer(final String what) { if (what.equals(TITLE) && MessageWindow.getInstance() != null) { MessageWindow.getInstance().setTitle("Messages - " + ProgramProperties.getProgramVersion()); } synchronized (directorListeners) { for (IDirectorListener directorListener : directorListeners) { final IDirectorListener d = directorListener; final Runnable runnable = () -> { try { d.setUptoDate(false); d.updateView(what); } catch (Exception ex) { Basic.caught(ex); } finally { d.setUptoDate(true); } }; if (SwingUtilities.isEventDispatchThread()) runnable.run(); else SwingUtilities.invokeLater(runnable); } } } /** * notify listeners to prevent user input */ public void notifyLockInput() { if (!locked) { synchronized (directorListeners) { IDirectorListener[] listeners = directorListeners.toArray(new IDirectorListener[0]); for (IDirectorListener directorListener : listeners) { if (directorListener != this) directorListener.lockUserInput(); } } ProjectManager.updateWindowMenus(); } locked = true; } /** * notify listeners to allow user input */ public void notifyUnlockInput() { if (locked) { synchronized (directorListeners) { IDirectorListener[] listeners = directorListeners.toArray(new IDirectorListener[0]); for (IDirectorListener directorListener : listeners) { if (directorListener != this) directorListener.unlockUserInput(); } } ProjectManager.updateWindowMenus(); } locked = false; } /** * returns true, if currently locked * * @return locked */ public boolean isLocked() { return locked; } /** * notify all director event listeners to destroy themselves */ private void notifyDestroyViewer() throws CanceledException { synchronized (directorListeners) { while (directorListeners.size() > 0) { // need to do this in this way because destroyView may modify this list IDirectorListener directorListener = directorListeners.get(0); if (directorListener != this) directorListener.destroyView(); if (directorListeners.size() > 0 && directorListeners.get(0) == directorListener) directorListeners.remove(0); } } // now remove all viewers while (viewers.size() > 0) { removeViewer(viewers.get(0)); } if (projectsChangedListener != null) ProjectManager.removeProjectsChangedListener(projectsChangedListener); if (future != null && !future.isDone()) { try { future.cancel(true); } catch (Exception ex) { // Basic.caught(ex); } future = null; } } /** * execute a command within the swing thread * */ public boolean executeImmediately(final String command) { throw new RuntimeException("Internal error: OLD executeImmediately()"); } /** * execute a command. Lock all viewer input, then request to doc to execute command * */ public void execute(final String command) { throw new RuntimeException("Internal error: OLD execute()"); } /** * execute a command within the swing thread * */ public boolean executeImmediately(final String command, CommandManager commandManager) { System.err.println("Executing: " + command); try { if (doc.getProgressListener() == null) { ProgressListener progressListener = new ProgressPercentage(); doc.setProgressListener(progressListener); } if (commandManager != null) commandManager.execute(command); else throw new Exception("Internal error: commandManager==null"); if (viewer == null || !viewer.isLocked()) { notifyUpdateViewer(Director.ENABLE_STATE); WaitUntilAllViewersAreUptoDate(); notifyUnlockInput(); } return true; } catch (CanceledException ex) { System.err.println("USER CANCELED EXECUTE"); NotificationsInSwing.showInformation("USER CANCELED EXECUTE"); return false; } catch (Exception ex) { NotificationsInSwing.showError("Command failed: " + ex.getMessage()); return false; } } /** * execute a command. Lock all viewer input, then request to doc to execute command * */ public void execute(final String command, final CommandManager commandManager) { if (ProgramProperties.isUseGUI()) { Component parentComponent; Object parent = commandManager.getParent(); if (parent instanceof IDirectableViewer) parentComponent = ((IDirectableViewer) parent).getFrame(); else if (parent instanceof JDialog) parentComponent = (JDialog) parent; else parentComponent = getParent(); execute(command, commandManager, parentComponent); } else executeImmediately(command, commandManager); } /** * execute a command. Lock all viewer input, then request to doc to execute command * */ public void execute(final String command, final CommandManager commandManager, final Component parent) { if (ProgramProperties.isUseGUI()) { if (command.length() > 1) System.err.println("Executing: " + command); if (docInUpdate) // shouldn't happen! System.err.println("Warning: execute(" + command + "): concurrent execution"); notifyLockInput(); future = ProgramExecutorService.getInstance().submit(() -> { docInUpdate = true; // final ProgressListener progressDialog=new ProgressPercentage(); final ProgressListener progressDialog = ProgramProperties.isUseGUI() ? new ProgressDialog("", "", parent) : new ProgressPercentage(); progressDialog.setDebug(Basic.getDebugMode()); doc.setProgressListener(progressDialog); long start = System.currentTimeMillis(); boolean ok = false; try { if (commandManager != null) { commandManager.execute(command); ok = true; } else throw new Exception("Internal error: commandManager==null"); } catch (CanceledException ex) { System.err.println("USER CANCELED EXECUTE"); } catch (Exception ex) { Basic.caught(ex); NotificationsInSwing.showError("Execute failed: " + ex); } notifyUpdateViewer(Director.ALL); WaitUntilAllViewersAreUptoDate(); notifyUnlockInput(); doc.getProgressListener().close(); doc.setProgressListener(null); docInUpdate = false; final int timeInSeconds = (int) ((System.currentTimeMillis() - start) / 1000); if (ok && timeInSeconds > 8) // if it took more than 8 seconds to complete, notify { NotificationsInSwing.showInformation("Command completed (" + timeInSeconds + "s): " + command); } }); } else executeImmediately(command, commandManager); } /** * returns the parent viewer * * @return viewer */ private Component getParent() { if (viewer != null) return viewer.getFrame(); else return null; } /** * returns a viewer of the given class * * @return viewer of the given class, or null */ public IDirectableViewer getViewerByClass(Class aClass) { for (IDirectableViewer o : getViewers()) { IDirectableViewer viewer = o; if (viewer.getClass().equals(aClass)) return viewer; } return null; } /** * returns a viewer of the given class * * @return viewer of the given class, or null */ public <T> IDirectableViewer getViewerByAssignableFrom(Class<T> aClass) { for (IDirectableViewer o : getViewers()) { IDirectableViewer viewer = o; if (aClass.isAssignableFrom(viewer.getClass())) return viewer; } return null; } /** * returns a viewer by class name * * @return viewer that has the given className */ public IDirectableViewer getViewerByClassName(String className) { for (IDirectableViewer viewer : getViewers()) { try { final Method method = viewer.getClass().getMethod("getClassName", (Class<?>[]) null); if (method != null) { final String name = (String) method.invoke(viewer, (Object[]) null); if (name.equals(className)) return viewer; } } catch (Exception ignored) { } if (viewer.getClass().getName().equals(className)) return viewer; } return null; } public int getID() { return id; } public void setID(int id) { this.id = id; } public Document getDocument() { return doc; } /** * close everything directed by this director */ public void close() throws CanceledException { notifyDestroyViewer(); } public void updateView(String what) { } /** * ask view to prevent user input */ public void lockUserInput() { } /** * ask view to allow user input */ public void unlockUserInput() { } /** * ask view to destroy itself */ public void destroyView() { } /** * set uptodate state * */ public void setUptoDate(boolean flag) { } /** * is viewer uptodate? * * @return uptodate */ public boolean isUptoDate() { return true; } /** * return the frame associated with the viewer * * @return frame */ public JFrame getFrame() { return null; } /** * gets the title * * @return title */ public String getTitle() { return doc.getTitle(); } /** * get the main viewer * * @return main viewer */ public MainViewer getMainViewer() { return viewer; } /** * are we currently updating the document? * * @return true, if are in rescan */ public boolean isInUpdate() { return docInUpdate; } /** * open all necessary files at startup * */ public void executeOpen(final String taxonomyFileName, final String[] meganFiles, final String initCommand) { System.err.println("Opening startup files"); final CommandManager commandManager = getMainViewer().getCommandManager(); if (docInUpdate) // shouldn't happen! System.err.println("Warning: executeOpen: concurrent execution"); notifyLockInput(); Runnable runnable = () -> { docInUpdate = true; ProgressListener progressDialog = ProgramProperties.isUseGUI() ? new ProgressDialog("Open startup files", "", getParent()) : new ProgressCmdLine("Open startup files", ""); progressDialog.setDebug(Basic.getDebugMode()); doc.setProgressListener(progressDialog); try { if (taxonomyFileName != null && taxonomyFileName.length() > 0) { if (ResourceManager.fileExists(taxonomyFileName)) commandManager.execute("load taxonomyFile='" + taxonomyFileName + "';"); else throw new IOException("Can't read taxonomy file: <" + taxonomyFileName + ">"); } if (meganFiles != null && meganFiles.length > 0) { StringBuilder buf = new StringBuilder(); for (String fileName : meganFiles) { fileName = fileName.trim(); if (fileName.length() > 0) { File file = new File(fileName); if (file.canRead()) { buf.append("open file='").append(fileName).append("';"); } else { System.err.println("Warning: Can't read MEGAN file: '" + fileName + "'"); } } } if (buf.toString().length() > 0) commandManager.execute(buf.toString()); } getMainViewer().setDoReInduce(true); getMainViewer().setDoReset(true); commandManager.execute(";"); if (initCommand != null && initCommand.length() > 0) { String[] tokens = initCommand.split(";"); for (String command : tokens) { if (command.equalsIgnoreCase("quit")) System.exit(0); else executeImmediately(command + ";", commandManager); } } } catch (CanceledException ex) { System.err.println("USER CANCELED EXECUTE"); } catch (Exception ex) { Basic.caught(ex); NotificationsInSwing.showError("Execute failed: " + ex); } if (TaxonomyData.getTree().getRoot() == null) { NotificationsInSwing.showError(viewer.getFrame(), "Initialization files not found. Please reinstall the program."); executeImmediately("quit;", commandManager); } notifyUpdateViewer(Director.ALL); WaitUntilAllViewersAreUptoDate(); notifyUnlockInput(); progressDialog.close(); doc.setProgressListener(null); docInUpdate = false; }; if (ProgramProperties.isUseGUI()) future = ProgramExecutorService.getInstance().submit(runnable); else runnable.run(); } /** * set the dirty flag * */ public void setDirty(boolean dirty) { getDocument().setDirty(dirty); } /** * get the dirty flag * * @return dirty */ public boolean getDirty() { return getDocument().isDirty(); } /** * gets a new director and makes the main viewer visible * * @return new director */ public static Director newProject() { return newProject(true); } /** * gets a new director * * @param visible show main viewer be visible? * @return new director */ public static Director newProject(boolean visible) { return newProject(visible, false); } /** * gets a new director * * @param visible show main viewer be visible? * @return new director */ public static Director newProject(boolean visible, boolean internalDocument) { Document doc = new Document(); Director dir = new Director(doc); dir.setInternalDocument(internalDocument); doc.setDir(dir); dir.setID(ProjectManager.getNextID()); final MainViewer viewer = new MainViewer(dir, visible); if (!dir.isInternalDocument()) { dir.projectsChangedListener = () -> viewer.getCommandManager().updateEnableState("Compare..."); ProjectManager.addProjectsChangedListener(dir.projectsChangedListener); } ProjectManager.addProject(dir, viewer); return dir; } /** * show the message window */ public static void showMessageWindow() { if (ProgramProperties.isUseGUI() && MessageWindow.getInstance() != null) { MessageWindow.getInstance().startCapturingOutput(); WindowUtilities.toFront(MessageWindow.getInstance().getFrame()); } } /** * gets the command manager associated with the main viewer * * @return command manager */ public CommandManager getCommandManager() { return getMainViewer().getCommandManager(); } @Override public boolean isInternalDocument() { return internalDocument; } @Override public void setInternalDocument(boolean internalDocument) { this.internalDocument = internalDocument; } /** * get the name of the class * * @return class name */ @Override public String getClassName() { return "Director"; } }
21,753
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationType.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/ClassificationType.java
/* * ClassificationType.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; /** * all known classifications * Daniel Huson, 1.2013 */ public enum ClassificationType { /** * standard types of classifications: */ Taxonomy, SEED, KEGG, COG, REFSEQ, PFAM; /** * gets the short name used in IO * * @return short name of type */ public static String getShortName(ClassificationType type) { if (type == Taxonomy) return "TAX"; else if (type == REFSEQ) return "REF"; else return type.toString(); } /** * gets the short name used in IO * * @return short name of type */ public static String getShortName(String fullName) { if (fullName.equals(Taxonomy.toString())) return "TAX"; else if (fullName.equals(REFSEQ.toString())) return "REF"; else return fullName; } /** * gets the full name used in IO * * @return short name of type */ public static String getFullName(String shortName) { return switch (shortName) { case "TAX" -> Taxonomy.toString(); case "REF" -> REFSEQ.toString(); default -> shortName; }; } }
2,052
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganFile.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/MeganFile.java
/* * MeganFile.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.util.FileUtils; import jloda.util.Pair; import megan.daa.connector.DAAConnector; import megan.data.IConnector; import megan.data.merge.MergeConnector; import megan.ms.client.connector.MSConnector; import megan.rma2.RMA2Connector; import megan.rma2.RMA2File; import megan.rma3.RMA3Connector; import megan.rma6.RMA6Connector; import java.io.File; import java.io.IOException; import java.util.*; /** * manages MEGAN file associated with a document, can be an RMA file, a summary file or a MEGAN server file * Daniel Huson, 11.2012 */ public class MeganFile { private final static Map<Pair<String, Long>, Integer> openFiles = new HashMap<>(); private String fileName = null; private Type fileType = Type.UNKNOWN_FILE; private boolean meganServerFile = false; private boolean readOnly = false; private Boolean hasDAAConnector=null; private IConnector connector; public enum Type {UNKNOWN_FILE, RMA1_FILE, RMA2_FILE, RMA3_FILE, RMA6_FILE, DAA_FILE, MEGAN_SUMMARY_FILE} private final ArrayList<String> mergedFiles =new ArrayList<>(); public MeganFile() { } /** * set the megan file from an existing file * */ public void setFileFromExistingFile(String fileName, boolean readOnly) { if (!fileName.equals(this.fileName)) connector = null; this.fileName = fileName; this.readOnly = readOnly; hasDAAConnector=null; meganServerFile = fileName.contains("::"); if (fileName.toLowerCase().endsWith(".rma1")) { fileType = Type.RMA1_FILE; } else if (fileName.toLowerCase().endsWith(".rma2")) { fileType = Type.RMA2_FILE; } else if (fileName.toLowerCase().endsWith(".rma3")) { fileType = Type.RMA3_FILE; } else if (fileName.toLowerCase().endsWith(".rma6")) { fileType = Type.RMA6_FILE; } else if (fileName.toLowerCase().endsWith(".rma")) { int version = RMA2File.getRMAVersion(new File(fileName)); if (version == 1) fileType = Type.RMA1_FILE; else if (version == 2) fileType = Type.RMA2_FILE; else if (version == 3) fileType = Type.RMA3_FILE; else if (version == 6) fileType = Type.RMA6_FILE; else fileType = Type.UNKNOWN_FILE; } else if (fileName.toLowerCase().endsWith(".daa")) { fileType = Type.DAA_FILE; } else if (fileName.toLowerCase().endsWith(".meg") || fileName.toLowerCase().endsWith(".megan") || fileName.toLowerCase().endsWith(".meg.gz") || fileName.toLowerCase().endsWith(".megan.gz")) { fileType = Type.MEGAN_SUMMARY_FILE; setMergedFiles(determineMergedFiles(fileName)); } else fileType = Type.UNKNOWN_FILE; } public boolean isMeganSummaryFile() { return fileType == Type.MEGAN_SUMMARY_FILE; } /** * set new file of given type * */ public void setFile(String fileName, Type fileType) { if (fileName == null || !fileName.equals(this.fileName)) connector = null; this.fileName = fileName; this.fileType = fileType; readOnly = false; hasDAAConnector=null; } /** * is the set file ok to read? * */ public void checkFileOkToRead() throws IOException { if (isMeganServerFile()) return; File file = new File(fileName); if (!file.canRead()) throw new IOException("File not readable: " + fileName); switch (fileType) { case RMA1_FILE -> throw new IOException("RMA version 1 not supported: " + fileName); case RMA2_FILE -> { int version = RMA2File.getRMAVersion(file); if (version != 2) throw new IOException("RMA version (" + version + ") not supported: " + fileName); if (!file.canWrite()) setReadOnly(true); } case RMA3_FILE, RMA6_FILE, DAA_FILE, MEGAN_SUMMARY_FILE -> { if (!file.canWrite()) setReadOnly(true); } default -> throw new IOException("File has unknown type: " + fileName); } } /** * is file ok to read? * * @return true, if ok to read */ public boolean isOkToRead() { try { checkFileOkToRead(); return true; } catch (IOException ex) { return false; } } public String getFileName() { return Objects.requireNonNullElse(fileName, "Untitled"); } public void setFileName(String fileName) { if (fileName == null || !fileName.equals(this.fileName)) { connector = null; meganServerFile=false; } this.fileName = fileName; } public Type getFileType() { return fileType; } public void setFileType(Type fileType) { this.fileType = fileType; } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } public boolean isMeganServerFile() { return meganServerFile; } public boolean isUnsupportedRMA1File() { return fileType == Type.RMA1_FILE; } public boolean isRMA2File() { return fileType == Type.RMA2_FILE; } public boolean isRMA3File() { return fileType == Type.RMA3_FILE; } public boolean isRMA6File() { return fileType == Type.RMA6_FILE; } public boolean isDAAFile() { return fileType == Type.DAA_FILE; } /** * does file have a data connector associated with it * * @return true, if data connector present */ public boolean hasDataConnector() { if(hasDAAConnector==null) { try { hasDAAConnector = fileName != null && fileName.length() > 0 && (fileType.toString().startsWith("RMA") || fileType.toString().startsWith("DAA") || (fileType == Type.MEGAN_SUMMARY_FILE && MergeConnector.canOpenAllConnectors(getMergedFiles()))); } catch (IOException e) { hasDAAConnector=false; } } return hasDAAConnector; } /** * get the data connector associated with the file * * @return data connector */ public IConnector getConnector() throws IOException { return getConnector(true); } /** * get the data connector associated with the file * * @return data connector */ IConnector getConnector(boolean openDAAFileOnlyIfMeganized) throws IOException { if (connector == null) { if (isMeganServerFile()) { return new MSConnector(fileName); } switch (fileType) { case RMA2_FILE: { connector = new RMA2Connector(fileName); break; } case RMA3_FILE: { connector = new RMA3Connector(fileName); break; } case RMA6_FILE: { connector = new RMA6Connector(fileName); break; } case DAA_FILE: { synchronized (DAAConnector.syncObject) { boolean save = DAAConnector.openDAAFileOnlyIfMeganized; DAAConnector.openDAAFileOnlyIfMeganized = openDAAFileOnlyIfMeganized; connector = new DAAConnector(fileName); DAAConnector.openDAAFileOnlyIfMeganized = save; } break; } case MEGAN_SUMMARY_FILE: { if(getMergedFiles().size()>0) { connector = new MergeConnector(getFileName(), getMergedFiles()); break; } // else fall through to default: } default: throw new IOException("File type '" + fileType + "': not supported"); } } return connector; } /** * gets a short name for the file * * @return short name */ public String getName() { if (fileName == null) return "Untitled"; else return FileUtils.getFileNameWithoutPath(fileName); } /** * add the unique identify of a file to the set of open files * */ public static void addUIdToSetOfOpenFiles(String name, long uId) { final Pair<String, Long> pair = new Pair<>(name, uId); openFiles.merge(pair, 1, Integer::sum); } /** * removes the UID of a file from the set of open files * */ public static void removeUIdFromSetOfOpenFiles(String name, long uId) { final Pair<String, Long> pair = new Pair<>(name, uId); Integer count = openFiles.get(pair); if (count == null || count < 2) { openFiles.keySet().remove(pair); } else openFiles.put(pair, count - 1); } /** * determines whether UID of file is present in the set of all open files * * @return true, if present */ public static boolean isUIdContainedInSetOfOpenFiles(String name, long uId) { final Pair<String, Long> pair = new Pair<>(name, uId); Integer count = openFiles.get(pair); return count != null && count > 0; } /** * gets the names of all source files embedded in a comparison file * * @return embedded source files */ private static ArrayList<String> determineEmbeddedSourceFiles(String fileName) { final var doc = new Document(); doc.getMeganFile().setFile(fileName, Type.MEGAN_SUMMARY_FILE); try { doc.loadMeganFile(); } catch (Exception e) { //Basic.caught(e); } return doc.getSampleAttributeTable().getSourceFiles(); } /** * gets the names of all source files embedded in a comparison file * * @return embedded source files */ private static Collection<String> determineMergedFiles(String fileName) { final var doc = new Document(); doc.getMeganFile().setFile(fileName, Type.MEGAN_SUMMARY_FILE); try { doc.loadMeganFile(); } catch (Exception e) { //Basic.caught(e); } return new ArrayList<>(Arrays.asList(doc.getDataTable().getMergedFiles())); } public ArrayList<String> getMergedFiles() { return mergedFiles; } public void setMergedFiles(Collection<String> mergedFiles) { if (mergedFiles != null) { try { if(!MergeConnector.canOpenAllConnectors(mergedFiles)) { throw new IOException(); } else hasDAAConnector=true; } catch (IOException e) { System.err.println("Warning: Merged file: embedded input files not found"); return; } this.mergedFiles.addAll(mergedFiles); } } public static boolean hasReadableDAAConnector (String fileName) { var meganFile=new MeganFile(); meganFile.setFileFromExistingFile(fileName,true); return meganFile.isOkToRead() && meganFile.hasDataConnector(); } }
12,371
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SyncArchiveAndDataTable.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/SyncArchiveAndDataTable.java
/* * SyncArchiveAndDataTable.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.seq.BlastMode; import jloda.swing.util.ProgramProperties; import jloda.util.FileUtils; import jloda.util.StringUtils; import megan.classification.IdMapper; import megan.data.IClassificationBlock; import megan.data.IConnector; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * synchronize between archive and data table * Daniel Huson, 6.2010 */ public class SyncArchiveAndDataTable { /** * synchronizes recomputed data from an archive to a summary and also parameters * */ static public void syncRecomputedArchive2Summary(Document.ReadAssignmentMode readAssignmentMode, String dataSetName, String algorithmName, BlastMode blastMode, String parameters, IConnector connector, DataTable table, int additionalReads) throws IOException { final String[] classifications = connector.getAllClassificationNames(); table.clear(); table.setCreator(ProgramProperties.getProgramName()); table.setCreationDate((new Date()).toString()); table.setAlgorithm(ClassificationType.Taxonomy.toString(), algorithmName); table.setParameters(parameters); table.setTotalReads(connector.getNumberOfReads()); table.setAdditionalReads(additionalReads); table.setSamples(new String[]{dataSetName}, new Long[]{connector.getUId()}, new float[]{connector.getNumberOfReads()}, new BlastMode[]{blastMode}); for (String classification : classifications) { IClassificationBlock classificationBlock = connector.getClassificationBlock(classification); if (classificationBlock != null) syncClassificationBlock2Summary(readAssignmentMode, 0, 1, classificationBlock, table); } } /** * sync the content of an archive to the Megan4Summary. Formatting is obtained from the aux block, while * classifications are obtained from the classification blocks * * @param readAssignmentMode if null, first determines this from user state table */ public static void syncArchive2Summary(Document.ReadAssignmentMode readAssignmentMode, String fileName, IConnector connector, DataTable table, SampleAttributeTable sampleAttributeTable) throws IOException { table.clear(); var label2data = connector.getAuxiliaryData(); if (label2data.containsKey(SampleAttributeTable.USER_STATE)) { syncAux2Summary(fileName, label2data.get(SampleAttributeTable.USER_STATE), table); } if (readAssignmentMode == null && table.getParameters() != null) { var doc = new Document(); doc.parseParameterString(table.getParameters()); readAssignmentMode = doc.getReadAssignmentMode(); } if (label2data.containsKey(SampleAttributeTable.SAMPLE_ATTRIBUTES)) { sampleAttributeTable.read(new StringReader(new String(label2data.get(SampleAttributeTable.SAMPLE_ATTRIBUTES))), null, true); if (sampleAttributeTable.getSampleSet().size() > 0) { var sampleName = sampleAttributeTable.getSampleSet().iterator().next(); var name = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(fileName), ""); if (!sampleName.equals(name)) sampleAttributeTable.renameSample(sampleName, name, false); } } else { var name = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(fileName), ""); sampleAttributeTable.addSample(name, new HashMap<>(), true, true); } // fix some broken files that contain two lines of metadata... if (sampleAttributeTable.getSampleSet().size() > 1) { var sampleName = FileUtils.getFileNameWithoutPath(fileName); if (sampleAttributeTable.getSampleSet().contains(sampleName)) sampleAttributeTable.removeSample(sampleName); } var classifications = connector.getAllClassificationNames(); for (var classification : classifications) { final var classificationBlock = connector.getClassificationBlock(classification); if (classificationBlock != null) syncClassificationBlock2Summary(readAssignmentMode, 0, 1, classificationBlock, table); } } /** * sync classification block to the summary */ private static void syncClassificationBlock2Summary(Document.ReadAssignmentMode readAssignmentMode, int dataSetId, int totalDataSets, final IClassificationBlock classificationBlock, DataTable table) { boolean useWeights = (readAssignmentMode != Document.ReadAssignmentMode.readCount); final Map<Integer, float[]> classId2count = new HashMap<>(); table.setClass2Counts(classificationBlock.getName(), classId2count); for (Integer classId : classificationBlock.getKeySet()) { float sum = (useWeights ? classificationBlock.getWeightedSum(classId) : classificationBlock.getSum(classId)); if (sum > 0) { classId2count.computeIfAbsent(classId, k -> new float[totalDataSets]); classId2count.get(classId)[dataSetId] += sum; } } if (table.getAdditionalReads() > 0) { classId2count.computeIfAbsent(IdMapper.NOHITS_ID, k -> new float[totalDataSets]); classId2count.get(IdMapper.NOHITS_ID)[dataSetId] += (int) table.getAdditionalReads(); } } /** * sync bytes from aux block to summary * */ static public void syncAux2Summary(String fileName, byte[] bytes, DataTable table) throws IOException { if (bytes != null) { var string = StringUtils.toString(bytes); if (string.startsWith(DataTable.MEGAN6_SUMMARY_TAG_NOT_USED_ANYMORE) || string.startsWith(DataTable.MEGAN4_SUMMARY_TAG) || string.startsWith("!MEGAN4")) { try(var r = new BufferedReader(new StringReader(string))) { table.read(r, true); } } else if (string.startsWith("!MEGAN")) // is MEGAN3 summary { System.err.println("Archive is in an old format, upgrading to MEGAN6"); try(var r = new BufferedReader(new StringReader(string))) { table.importMEGAN3SummaryFile(fileName, r, false); } } } } }
7,170
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DataTable.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/DataTable.java
/* * DataTable.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.seq.BlastMode; import jloda.util.*; import org.apache.commons.lang.ArrayUtils; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; /** * megan data table. Keeps a summary of all data and also holds metadata * Daniel Huson, 6.2010 */ public class DataTable { public static final String MEGAN6_SUMMARY_TAG_NOT_USED_ANYMORE = "@MEGAN6"; // some early versions of MEGAN6 use this, but later versions do not public static final String MEGAN4_SUMMARY_TAG = "@MEGAN4"; // new type of file: private static final String MEGAN6SummaryFormat_NotUsedAnyMore = "Summary6"; private static final String MEGAN4SummaryFormat = "Summary4"; private static final String MEGAN3SummaryFormat = "Summary"; // tags used in file: private final static String CONTENT_TYPE = "@ContentType"; private final static String CREATION_DATE = "@CreationDate"; private final static String CREATOR = "@Creator"; private final static String NAMES = "@Names"; private final static String BLAST_MODE = "@BlastMode"; private final static String DISABLED = "@Disabled"; private final static String NODE_FORMATS = "@NodeFormats"; private final static String EDGE_FORMATS = "@EdgeFormats"; private static final String ALGORITHM = "@Algorithm"; private static final String NODE_STYLE = "@NodeStyle"; private static final String COLOR_TABLE = "@ColorTable"; private static final String COLOR_EDITS = "@ColorEdits"; private static final String PARAMETERS = "@Parameters"; private static final String CONTAMINANTS = "@Contaminants"; private static final String TOTAL_READS = "@TotalReads"; private static final String ADDITIONAL_READS = "@AdditionalReads"; private static final String COLLAPSE = "@Collapse"; private static final String SIZES = "@Sizes"; private static final String UIDS = "@Uids"; private static final String MERGED_FILES ="@MergedFiles"; // variables: private String contentType = MEGAN4SummaryFormat; private String creator = ProgramProperties.getProgramName(); private String creationDate = null; private long totalReads = -1; private long additionalReads = -1; private double totalReadWeights = -1; private final Vector<String> sampleNames = new Vector<>(); private final Vector<BlastMode> blastModes = new Vector<>(); private final Vector<Float> sampleSizes = new Vector<>(); private final Vector<Long> sampleUIds = new Vector<>(); private final Vector<String> mergedFiles = new Vector<>(); private final Set<String> disabledSamples = new HashSet<>(); private DataTable originalData = null; private final Map<String, Set<Integer>> classification2collapsedIds = new HashMap<>(); private final Map<String, String> classification2algorithm = new HashMap<>(); private final Map<String, String> classification2NodeStyle = new HashMap<>(); private final Map<String, String> classification2NodeFormats = new HashMap<>(); private final Map<String, String> classification2EdgeFormats = new HashMap<>(); private String colorTable = null; private String colorTableHeatMap = null; private String colorEdits = null; private boolean colorByPosition = false; private String parameters; private String contaminants; private final Map<String, Map<Integer, float[]>> classification2class2counts = new HashMap<>(); /** * constructor */ public DataTable() { } /** * erase the summary block */ public void clear() { creationDate = null; sampleNames.clear(); blastModes.clear(); sampleSizes.clear(); sampleUIds.clear(); disabledSamples.clear(); mergedFiles.clear(); totalReads = -1; additionalReads = -1; totalReadWeights = -1; classification2collapsedIds.clear(); classification2NodeStyle.clear(); classification2algorithm.clear(); classification2NodeFormats.clear(); classification2EdgeFormats.clear(); parameters = null; classification2class2counts.clear(); // don't clear contaminants } /** * read a complete file * */ public void read(BufferedReader r, boolean headerOnly) throws IOException { try { Set<String> disabledSamples = new HashSet<>(); clear(); int lineNumber = 0; String aLine; while ((aLine = r.readLine()) != null) { lineNumber++; aLine = aLine.trim(); if (aLine.isEmpty() || aLine.startsWith("#")) continue; final String[] tokens = aLine.split("\t"); if (lineNumber == 1 && (aLine.equals(MEGAN6_SUMMARY_TAG_NOT_USED_ANYMORE) || aLine.equals(MEGAN4_SUMMARY_TAG) || aLine.equals("!MEGAN4"))) continue; if (aLine.equals("BEGIN_METADATA_TABLE") || aLine.equals("END_OF_DATA_TABLE")) // everything below this token is sample attribute break; // BEGIN_METADATA_TABLE is for legacy purposes only and is no longer used or supported if (aLine.startsWith("@")) { switch (tokens[0]) { case CONTENT_TYPE -> { var buf = new StringBuilder(); for (var i = 1; i < tokens.length; i++) buf.append(" ").append(tokens[i]); contentType = buf.toString().trim(); if (!contentType.startsWith(MEGAN6SummaryFormat_NotUsedAnyMore) && !contentType.startsWith(MEGAN4SummaryFormat)) throw new IOException("Wrong content type: " + contentType + ", expected: " + MEGAN4SummaryFormat); } case CREATOR -> { var buf = new StringBuilder(); for (var i = 1; i < tokens.length; i++) buf.append(" ").append(tokens[i]); creator = buf.toString().trim(); } case CREATION_DATE -> { var buf = new StringBuilder(); for (var i = 1; i < tokens.length; i++) buf.append(" ").append(tokens[i]); creationDate = buf.toString().trim(); } case BLAST_MODE -> { for (var i = 1; i < tokens.length; i++) { var blastMode = BlastMode.valueOfIgnoreCase(tokens[i]); if (blastMode == null) blastMode = BlastMode.Unknown; blastModes.add(blastMode); } } case NAMES -> sampleNames.addAll(Arrays.asList(tokens).subList(1, tokens.length)); case DISABLED -> disabledSamples.addAll(Arrays.asList(tokens).subList(1, tokens.length)); case MERGED_FILES -> mergedFiles.addAll(Arrays.asList(tokens).subList(1, tokens.length)); case UIDS -> { for (var i = 1; i < tokens.length; i++) if (tokens[i] != null && !tokens[i].equals("null")) sampleUIds.add(Long.parseLong(tokens[i])); } case SIZES -> { for (int i = 1; i < tokens.length; i++) sampleSizes.add(NumberUtils.parseFloat(tokens[i])); } case TOTAL_READS -> totalReads = (Long.parseLong(tokens[1])); case ADDITIONAL_READS -> additionalReads = (Long.parseLong(tokens[1])); case COLLAPSE -> { if (tokens.length > 1) { String data = tokens[1]; Set<Integer> collapsedIds = new HashSet<>(); classification2collapsedIds.put(data, collapsedIds); for (int i = 2; i < tokens.length; i++) collapsedIds.add(Integer.parseInt(tokens[i])); } } case ALGORITHM -> { if (tokens.length > 1) { String data = tokens[1]; StringBuilder buf = new StringBuilder(); for (int i = 2; i < tokens.length; i++) buf.append(" ").append(tokens[i]); classification2algorithm.put(data, buf.toString().trim()); } } case NODE_STYLE -> { if (tokens.length > 1) { String data = tokens[1]; StringBuilder buf = new StringBuilder(); for (int i = 2; i < tokens.length; i++) buf.append(" ").append(tokens[i]); classification2NodeStyle.put(data, buf.toString().trim()); } } case COLOR_TABLE -> { colorTable = tokens[1]; colorByPosition = false; for (int k = 2; k < tokens.length; k++) { if (tokens[k].equals("byPosition")) colorByPosition = true; else colorTableHeatMap = tokens[k]; } } case COLOR_EDITS -> { if (tokens.length > 1) { colorEdits = StringUtils.toString(tokens, 1, tokens.length - 1, "\t"); } else colorEdits = null; } case NODE_FORMATS -> { if (tokens.length > 1) { String data = tokens[1]; StringBuilder buf = new StringBuilder(); for (int i = 2; i < tokens.length; i++) buf.append(" ").append(tokens[i]); classification2NodeFormats.put(data, buf.toString().trim()); } } case EDGE_FORMATS -> { if (tokens.length > 1) { String data = tokens[1]; StringBuilder buf = new StringBuilder(); for (int i = 2; i < tokens.length; i++) buf.append(" ").append(tokens[i]); classification2EdgeFormats.put(data, buf.toString().trim()); } } case PARAMETERS -> { if (tokens.length > 1) { StringBuilder buf = new StringBuilder(); for (int i = 1; i < tokens.length; i++) buf.append(" ").append(tokens[i]); parameters = buf.toString().trim(); } } case CONTAMINANTS -> { if (tokens.length > 1) { StringBuilder buf = new StringBuilder(); for (int i = 1; i < tokens.length; i++) buf.append(" ").append(tokens[i]); setContaminants(buf.toString().trim()); } } default -> System.err.println("Line: " + lineNumber + ": Skipping unknown token: " + tokens[0]); } } else { if (headerOnly) break; if (tokens.length > 2) { String classification = ClassificationType.getFullName(tokens[0]); Integer classId = Integer.parseInt(tokens[1]); Map<Integer, float[]> class2counts = classification2class2counts.computeIfAbsent(classification, k -> new HashMap<>()); float[] counts = class2counts.get(classId); if (counts == null) { counts = new float[Math.min(getNumberOfSamples(), tokens.length - 2)]; class2counts.put(classId, counts); } for (int i = 2; i < Math.min(tokens.length, counts.length + 2); i++) { counts[i - 2] = Float.parseFloat(tokens[i]); } } else System.err.println("Line " + lineNumber + ": Too few tokens in classification: " + aLine); } } if (disabledSamples.size() > 0) { disableSamples(disabledSamples); } if (blastModes.size() < getNumberOfSamples()) { for (int i = blastModes.size(); i < getNumberOfSamples(); i++) { blastModes.add(BlastMode.Unknown); } } } catch (IOException ex) { Basic.caught(ex); throw ex; } catch (Exception ex) { Basic.caught(ex); throw new IOException(ex); } } /** * returns the user state as bytes (for saving to auxiliary data in RMA file) * * @return bytes of auxiliary data */ public byte[] getUserStateAsBytes() throws IOException { StringWriter w = new StringWriter(); w.write(MEGAN4_SUMMARY_TAG + "\n"); writeHeader(w); return w.toString().getBytes(StandardCharsets.UTF_8); } /** * write the datatable * */ public void write(Writer w) throws IOException { boolean useOriginal = (originalData != null && disabledSamples.size() > 0); write(w, useOriginal); } /** * write data to writer * * @param useOriginal use original data, if set */ private void write(Writer w, boolean useOriginal) throws IOException { if (useOriginal) { originalData.disabledSamples.addAll(disabledSamples); originalData.write(w, false); originalData.disabledSamples.clear(); } else { // write the header: writeHeader(w); // write the data: for (String classification : classification2class2counts.keySet()) { final Map<Integer, float[]> class2counts = classification2class2counts.get(classification); classification = ClassificationType.getShortName(classification); for (Integer classId : class2counts.keySet()) { float[] counts = class2counts.get(classId); if (counts != null) { w.write(classification + "\t" + classId); for (int i = 0; i < getNumberOfSamples(); i++) { w.write("\t" + (i < counts.length ? StringUtils.removeTrailingZerosAfterDot("" + counts[i]) : 0)); } w.write("\n"); } } } w.write("END_OF_DATA_TABLE\n"); } } /** * write the header to a writer * */ private void writeHeader(Writer w) throws IOException { w.write(String.format("%s\t%s\n", CREATOR, (creator != null ? creator : ProgramProperties.getProgramName()))); w.write(String.format("%s\t%s\n", CREATION_DATE, (creationDate != null ? creationDate : ((new Date()).toString())))); w.write(String.format("%s\t%s\n", CONTENT_TYPE, getContentType())); w.write(String.format("%s\t%s\n", NAMES, StringUtils.toString(sampleNames, "\t"))); w.write(String.format("%s\t%s\n", BLAST_MODE, StringUtils.toString(blastModes, "\t"))); if (!disabledSamples.isEmpty()) { w.write(String.format("%s\t%s\n", DISABLED, StringUtils.toString(disabledSamples, "\t"))); } if(!mergedFiles.isEmpty()) { w.write(String.format("%s\t%s\n", MERGED_FILES, StringUtils.toString(mergedFiles, "\t"))); } if (!sampleUIds.isEmpty()) { w.write(String.format("%s\t%s\n", UIDS, StringUtils.toString(sampleUIds, "\t"))); } if (!sampleSizes.isEmpty()) { w.write(String.format("%s\t%s\n", SIZES, StringUtils.removeTrailingZerosAfterDot(StringUtils.toString(sampleSizes, "\t")))); } if (totalReads != -1) w.write(String.format("%s\t%d\n", TOTAL_READS, totalReads)); if (additionalReads != -1) w.write(String.format("%s\t%d\n", ADDITIONAL_READS, additionalReads)); for (String classification : classification2collapsedIds.keySet()) { Set<Integer> collapsed = classification2collapsedIds.get(classification); if (collapsed != null && collapsed.size() > 0) { w.write(String.format("%s\t%s\t%s\n", COLLAPSE, classification, StringUtils.toString(collapsed, "\t"))); } } for (String classification : classification2algorithm.keySet()) { String algorithm = classification2algorithm.get(classification); if (algorithm != null) { w.write(String.format("%s\t%s\t%s\n", ALGORITHM, classification, algorithm)); } } if (parameters != null) w.write(String.format("%s\t%s\n", PARAMETERS, parameters)); if (hasContaminants()) w.write(String.format("%s\t%s\n", CONTAMINANTS, getContaminants())); for (String classification : classification2NodeStyle.keySet()) { String nodeType = classification2NodeStyle.get(classification); if (nodeType != null) { w.write(String.format("%s\t%s\t%s\n", NODE_STYLE, classification, nodeType)); } } if (colorTable != null) w.write(String.format("%s\t%s%s\t%s\n", COLOR_TABLE, colorTable, (colorByPosition ? "\tbyPosition" : ""), getColorTableHeatMap())); if (colorEdits != null) w.write(String.format("%s\t%s\n", COLOR_EDITS, colorEdits)); for (String classification : classification2NodeFormats.keySet()) { String formatting = classification2NodeFormats.get(classification); if (formatting != null) { w.write(String.format("%s\t%s\t%s\n", NODE_FORMATS, classification, formatting)); } } for (String classification : classification2EdgeFormats.keySet()) { String formatting = classification2EdgeFormats.get(classification); if (formatting != null) w.write(String.format("%s\t%s\t%s\n", EDGE_FORMATS, classification, formatting)); } } /** * get the header in pretty print (HTML) * * @return header */ public String getHeaderPrettyPrint() throws IOException { Writer w = new StringWriter(); w.write("<b>" + CREATOR.substring(1) + ":</b> " + (creator != null ? creator : ProgramProperties.getProgramName()) + "<br>"); w.write("<b>" + CREATION_DATE.substring(1) + ":</b>" + (creationDate != null ? creationDate : "unknown") + "<br>"); w.write("<b>" + CONTENT_TYPE.substring(1) + ":</b>" + getContentType() + "<br>"); w.write("<b>" + NAMES.substring(1) + ":</b>"); for (String dataName : sampleNames) w.write(" " + dataName); w.write("<br>"); w.write("<b>" + BLAST_MODE.substring(1) + ":</b>"); for (BlastMode blastMode : blastModes) w.write(" " + blastMode.toString()); w.write("<br>"); if (mergedFiles.size() > 0) { w.write("<b>" + MERGED_FILES.substring(1) + ":</b>"); for (var file : mergedFiles) w.write(" " + file); w.write("<br>"); } if (sampleUIds.size() > 0) { w.write("<b>" + UIDS.substring(1) + ":</b>"); for (Long dataUid : sampleUIds) w.write(" " + dataUid); w.write("<br>"); } if (sampleSizes.size() > 0) { w.write("<b>" + SIZES.substring(1) + ":</b>"); for (float dataSize : sampleSizes) w.write(" " + dataSize); w.write("<br>"); } if (totalReads != -1) w.write(String.format("<b>%s:</b> %d<br>\n", TOTAL_READS.substring(1), totalReads)); if (additionalReads != -1) w.write(String.format("<b>%s:</b> %d<br>\n", ADDITIONAL_READS.substring(1), additionalReads)); w.write("<b>Classifications:</b> "); for (String classification : classification2class2counts.keySet()) { Map<Integer, float[]> class2counts = classification2class2counts.get(classification); int size = class2counts != null ? class2counts.size() : 0; w.write(String.format("%s (%d classes)", classification, size)); } w.write("<br>\n"); for (String classification : classification2algorithm.keySet()) { String algorithm = classification2algorithm.get(classification); if (algorithm != null) { w.write(String.format("<b>%s:</b> %s: %s<br>\n", ALGORITHM.substring(1), classification, algorithm)); } } if (parameters != null) w.write(String.format("<b>%s:</b> %s<br>\n", PARAMETERS.substring(1), parameters)); if (hasContaminants()) w.write(String.format("<b>%s:</b> %d taxa<br>\n", CONTAMINANTS.substring(1), StringUtils.countWords(getContaminants()))); if (colorTable != null) w.write(String.format("<b>ColorTable:</b> %s%s <b>HeatMapColorTable:</b> %s<br>\n", colorTable, (colorByPosition ? " byPosition" : ""), colorTableHeatMap)); if (colorEdits != null) w.write(String.format("<b>ColorEdits:</b> %s<br>\n", StringUtils.abbreviateDotDotDot(colorEdits, 50))); return w.toString(); } /** * get summary * * @return header */ public String getSummary() throws IOException { Writer w = new StringWriter(); w.write(String.format("%s\t%s\n", CREATOR, (creator != null ? creator : ProgramProperties.getProgramName()))); w.write(String.format("%s\t%s\n", CREATION_DATE, (creationDate != null ? creationDate : ((new Date()).toString())))); w.write(String.format("%s\t%s\n", CONTENT_TYPE, getContentType())); w.write(String.format("%s\t%s\n", NAMES, StringUtils.toString(sampleNames, "\t"))); w.write(String.format("%s\t%s\n", BLAST_MODE, StringUtils.toString(blastModes, "\t"))); if (mergedFiles.size() > 0) { w.write(String.format("%s\t%s\n", MERGED_FILES, StringUtils.toString(mergedFiles, "\t"))); } if (sampleUIds.size() > 0) { w.write(String.format("%s\t%s\n", UIDS, StringUtils.toString(sampleUIds, "\t"))); } if (sampleSizes.size() > 0) { w.write(String.format("%s\t%s\n", SIZES, StringUtils.toString(sampleSizes, "\t"))); } if (totalReads != -1) w.write(String.format("%s\t%d\n", TOTAL_READS, totalReads)); if (additionalReads != -1) w.write(String.format("%s\t%d\n", ADDITIONAL_READS, additionalReads)); w.write("Classifications:\n"); for (String classification : classification2class2counts.keySet()) { Map<Integer, float[]> class2counts = classification2class2counts.get(classification); int size = class2counts != null ? class2counts.size() : 0; w.write(" " + classification + " (" + size + " classes)"); } w.write("\n"); for (var classification : classification2algorithm.keySet()) { var algorithm = classification2algorithm.get(classification); if (algorithm != null) { w.write(String.format("%s\t%s\t%s\n", ALGORITHM, classification, algorithm)); } } if (parameters != null) w.write(String.format("%s\t%s\n", PARAMETERS, parameters)); if (hasContaminants()) w.write(String.format("%s\t%s\n", CONTAMINANTS, getContaminants())); return w.toString(); } /** * imports a MEGAN3-summary file * */ public void importMEGAN3SummaryFile(String fileName, BufferedReader r, boolean headerOnly) throws IOException { int lineNumber = 0; try (r) { String aLine; sampleNames.clear(); sampleNames.add(FileUtils.getFileBaseName(fileName)); blastModes.clear(); contaminants = null; while ((aLine = r.readLine()) != null) { lineNumber++; aLine = aLine.trim(); if (aLine.length() == 0 || aLine.startsWith("#")) continue; if (lineNumber == 1 && aLine.equals("!MEGAN")) continue; if (aLine.startsWith("@")) // preamble { int separatorPos = aLine.indexOf("="); if (separatorPos == -1) throw new IOException("Line " + lineNumber + ": Can't parse: " + aLine); String first = aLine.substring(0, separatorPos); String second = aLine.substring(separatorPos + 1); switch (first) { case CONTENT_TYPE: if (!second.equals(MEGAN3SummaryFormat)) throw new IOException("Wrong format: " + second); setContentType(MEGAN4SummaryFormat + "\t(imported from MEGAN3 " + second + " format)"); break; case CREATOR: setCreator(second); break; case CREATION_DATE: setCreationDate(second); break; case PARAMETERS: setParameters(second); break; case ALGORITHM: setAlgorithm(ClassificationType.Taxonomy.toString(), second); break; case COLLAPSE: if (second.length() > 0) { String[] tokens = second.split(";"); Set<Integer> collapse = new HashSet<>(); for (String token : tokens) { collapse.add(Integer.parseInt(token)); } setCollapsed(ClassificationType.Taxonomy.toString(), collapse); } break; case NODE_FORMATS: setNodeFormats(ClassificationType.Taxonomy.toString(), second); break; case EDGE_FORMATS: setEdgeFormats(ClassificationType.Taxonomy.toString(), second); break; case "@Format": // ignore break; case TOTAL_READS: totalReads = Integer.parseInt(second); totalReadWeights = totalReads; break; } } else if (!headerOnly)// data line { String[] tokens = aLine.split(" "); if (tokens.length == 3) { int classId = Integer.parseInt(tokens[0]); int value = Integer.parseInt(tokens[2]); setClassification2Class2Count(ClassificationType.Taxonomy.toString(), classId, 0, value); } } } if (!headerOnly) determineSizesFromTaxonomyClassification(); } } /** * determine the size of datasets from the taxonomy classification */ private void determineSizesFromTaxonomyClassification() { // determine sizes: Map<Integer, float[]> class2count = classification2class2counts.get(ClassificationType.Taxonomy.toString()); if (class2count != null) { float[] sizes = new float[getNumberOfSamples()]; for (Integer classId : class2count.keySet()) { float[] counts = class2count.get(classId); if (counts != null) { for (int i = 0; i < getNumberOfSamples(); i++) { if (counts[i] > 0) sizes[i] += counts[i]; } } } sampleSizes.clear(); for (float size : sizes) sampleSizes.add(size); } } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } /** * gets the classification2class2counts mapping * * @return mapping */ public Map<String, Map<Integer, float[]>> getClassification2Class2Counts() { return classification2class2counts; } /** * set the classification2class2count value for a given classification, classId, datasetid and count * */ public void setClassification2Class2Count(String classification, int classId, int sampleId, float count) { Map<Integer, float[]> class2count = classification2class2counts.get(classification); if (class2count == null) class2count = new HashMap<>(); classification2class2counts.put(classification, class2count); float[] counts = class2count.get(classId); if (counts == null) { counts = new float[getNumberOfSamples()]; class2count.put(classId, counts); } counts[sampleId] = count; } /** * gets all non-disabled sample names * * @return sample names */ public String[] getSampleNamesArray() { return sampleNames.toArray(new String[0]); } public Collection<String> getSampleNames() { return new ArrayList<>(sampleNames); } /** * gets all blast modes * * @return blast modes */ public BlastMode[] getBlastModes() { BlastMode[] result = new BlastMode[getNumberOfSamples()]; for (int i = 0; i < result.length; i++) { if (i < blastModes.size()) { result[i] = blastModes.get(i); } else result[i] = BlastMode.Unknown; } return result; } /** * gets the first blast mode * * @return blast mode */ public BlastMode getBlastMode() { if (blastModes.size() > 0) return blastModes.get(0); else return BlastMode.Unknown; } public void setBlastMode(int index, BlastMode blastMode) { blastModes.ensureCapacity(index + 1); blastModes.insertElementAt(blastMode, index); } /** * set basic stuff about samples * */ public void setSamples(String[] names, Long[] uids, float[] sizes, BlastMode[] modes) { sampleNames.clear(); if (names != null) sampleNames.addAll(Arrays.asList(names)); mergedFiles.clear(); sampleUIds.clear(); if (uids != null) sampleUIds.addAll(Arrays.asList(uids)); sampleSizes.clear(); if (sizes != null) { for (float size : sizes) sampleSizes.add(size); } blastModes.clear(); if (modes != null) { if (modes.length == 1) { // if there is 1 or more samples and only one mode given, apply to all for (String name : sampleNames) blastModes.add(modes[0]); } else blastModes.addAll(Arrays.asList(modes)); } else { for (int i = 0; i < getNumberOfSamples(); i++) blastModes.add(BlastMode.Unknown); } } public float[] getSampleSizes() { final float[] sizes = new float[sampleSizes.size()]; for (int i = 0; i < sizes.length; i++) sizes[i] = sampleSizes.get(i); return sizes; } public Long[] getSampleUIds() { return sampleUIds.toArray(new Long[0]); } public String[] getMergedFiles() { return mergedFiles.toArray(new String[0]); } public void setMergedFiles(String name, Collection<String> mergedFiles) { if(name!=null) { sampleNames.clear(); sampleNames.add(name); } this.mergedFiles.clear(); this.mergedFiles.addAll(mergedFiles); } /** * get the algorithm string for a classification * * @return algorithm string */ public String getAlgorithm(String classification) { return classification2algorithm.get(classification); } /** * set the algorithm string for a classification * */ public void setAlgorithm(String classification, String algorithm) { classification2algorithm.put(classification, algorithm); } /** * get the parameters string for the dataset * * @return parameters string */ public String getParameters() { return parameters; } /** * set the parameters string * */ public void setParameters(String parameters) { this.parameters = parameters; } /** * get the contaminants string * * @return string or null */ public String getContaminants() { return contaminants; } /** * set the contaminants string or null * */ public void setContaminants(String contaminants) { this.contaminants = contaminants; } public boolean hasContaminants() { return contaminants != null && contaminants.length() > 0; } /** * set the formatting string for a classification * */ public void setNodeFormats(String classification, String format) { if (format == null || format.length() == 0) classification2NodeFormats.put(classification, null); else classification2NodeFormats.put(classification, format); } /** * get the node type string for a classification * * @return formatting string */ public String getNodeStyle(String classification) { return classification2NodeStyle.get(classification); } /** * get the node type string for a classification * * @return formatting string */ public String getNodeStyle(String classification, String defaultValue) { String style = classification2NodeStyle.get(classification); if (style != null) return style; else return defaultValue; } /** * set the node type string for a classification * * @param nodeStyle Possible values: circle, heatmap, heatmap2, barchart, coxcombs, piechart */ public void setNodeStyle(String classification, String nodeStyle) { if (nodeStyle == null || nodeStyle.length() == 0) classification2NodeStyle.put(classification, null); else classification2NodeStyle.put(classification, nodeStyle); } /** * get the formatting string for a classification * * @return formatting string */ public String getNodeFormats(String classification) { return classification2NodeFormats.get(classification); } /** * set the formatting string for a classification * */ public void setEdgeFormats(String classification, String format) { if (format == null || format.length() == 0) classification2EdgeFormats.put(classification, null); else classification2EdgeFormats.put(classification, format); } /** * get the formatting string for a classification * * @return formatting string */ public String getEdgeFormats(String classification) { return classification2EdgeFormats.get(classification); } /** * get the collapsed ids for the named classification * * @return set of collapsed ids */ public Set<Integer> getCollapsed(String classification) { return classification2collapsedIds.get(classification); } /** * sets the set of collapsed ids for a classification * */ public void setCollapsed(String classification, Set<Integer> collapsedIds) { classification2collapsedIds.put(classification, collapsedIds); } /** * gets the content type * */ private String getContentType() { return contentType; } /** * sets the content type * */ private void setContentType(String contentType) { this.contentType = contentType; } public Map<Integer, float[]> getClass2Counts(ClassificationType classification) { return classification2class2counts.get(classification.toString()); } public Map<Integer, float[]> getClass2Counts(String classification) { return classification2class2counts.get(classification); } public void setClass2Counts(String classification, Map<Integer, float[]> classId2count) { classification2class2counts.put(classification, classId2count); } public void setTotalReads(long totalReads) { this.totalReads = totalReads; } public long getTotalReads() { if (totalReads > 0) return totalReads; else return 0; } public void setTotalReadWeights(double totalReadWeights) { this.totalReadWeights = totalReadWeights; } public double getTotalReadWeights() { if (totalReadWeights > 0) return totalReadWeights; else return totalReads; } public void setAdditionalReads(long additionalReads) { this.additionalReads = additionalReads; } public long getAdditionalReads() { if (additionalReads > 0) return additionalReads; else return 0; } /** * copy the given Megan4Summary * */ private void copy(DataTable megan4Table) { clear(); StringWriter sw = new StringWriter(); try { megan4Table.write(sw, false); read(new BufferedReader(new StringReader(sw.toString())), false); } catch (IOException e) { Basic.caught(e); } } public String toString() { StringWriter w = new StringWriter(); try { write(w, false); } catch (IOException e) { Basic.caught(e); } return w.toString(); } /** * replace an existing sample name * */ public void changeSampleName(Integer pid, String newName) { sampleNames.set(pid, newName); } /** * removes samples * */ private void removeSamples(Collection<String> toDelete) { var dead = new HashSet<Integer>(); for (var name : toDelete) { dead.add(StringUtils.getIndex(name, sampleNames)); } if(dead.size()>0) { mergedFiles.clear(); // System.err.println("Existing sample name: "+Basic.toString(sampleNames,",")); var top = sampleNames.size(); for (var pid = top - 1; pid >= 0; pid--) { if (dead.contains(pid)) { sampleNames.remove(pid); sampleSizes.remove(pid); if (sampleUIds.size() > pid) sampleUIds.remove(pid); if (blastModes.size() > pid) blastModes.remove(pid); } } var alive = sampleNames.size(); // System.err.println("Remaining sample name: "+Basic.toString(sampleNames,",")); for (var class2counts : classification2class2counts.values()) { for (var classId : class2counts.keySet()) { var counts = class2counts.get(classId); if (counts != null) { var newCounts = new float[alive]; var k = 0; for (var i = 0; i < counts.length; i++) { if (!dead.contains(i)) { newCounts[k++] = counts[i]; } class2counts.put(classId, newCounts); } } } } totalReads = 0; for (var size : sampleSizes) { totalReads += size; } } } public String getColorTable() { return colorTable; } public void setColorTableHeatMap(String colorTableHeatMap) { this.colorTableHeatMap = colorTableHeatMap; } public String getColorTableHeatMap() { return colorTableHeatMap; } public void setColorTable(String colorTable, boolean colorByPosition, String colorTableHeatMap) { this.colorTable = colorTable; this.colorByPosition = colorByPosition; this.colorTableHeatMap = colorTableHeatMap; } public boolean isColorByPosition() { return colorByPosition; } public String getColorEdits() { return colorEdits; } public void setColorEdits(String colorEdits) { this.colorEdits = colorEdits; } /** * add the named sample from the given source * */ public void addSample(String sample, DataTable source) { DataTable target = this; if (!Arrays.asList(target.getSampleNamesArray()).contains(sample)) { int srcId = StringUtils.getIndex(sample, source.sampleNames); target.sampleSizes.add(source.sampleSizes.get(srcId)); target.sampleNames.add(sample); target.sampleUIds.add(System.currentTimeMillis()); if (srcId < blastModes.size()) target.blastModes.add(blastModes.get(srcId)); int tarId = StringUtils.getIndex(sample, target.sampleNames); for (String classification : source.classification2class2counts.keySet()) { Map<Integer, float[]> sourceClass2counts = source.classification2class2counts.get(classification); Map<Integer, float[]> targetClass2counts = target.classification2class2counts.computeIfAbsent(classification, k -> new HashMap<>()); for (Integer classId : sourceClass2counts.keySet()) { float[] sourceCounts = sourceClass2counts.get(classId); if (sourceCounts != null && srcId < sourceCounts.length && sourceCounts[srcId] != 0) { float[] targetCounts = targetClass2counts.get(classId); float[] newCounts = new float[tarId + 1]; if (targetCounts != null) { System.arraycopy(targetCounts, 0, newCounts, 0, targetCounts.length); } newCounts[tarId] = sourceCounts[srcId]; targetClass2counts.put(classId, newCounts); } } } target.totalReads += source.sampleSizes.get(srcId); } } /** * add the named sample * */ public void addSample(String sample, float sampleSize, BlastMode mode, int srcId, Map<String, Map<Integer, float[]>> sourceClassification2class2counts) { if (!Arrays.asList(this.getSampleNamesArray()).contains(sample)) { this.sampleSizes.add(sampleSize); this.sampleNames.add(sample); this.sampleUIds.add(System.currentTimeMillis()); this.blastModes.add(mode); int tarId = StringUtils.getIndex(sample, this.sampleNames); for (String classification : sourceClassification2class2counts.keySet()) { Map<Integer, float[]> sourceClass2counts = sourceClassification2class2counts.get(classification); Map<Integer, float[]> targetClass2counts = this.classification2class2counts.computeIfAbsent(classification, k -> new HashMap<>()); for (int classId : sourceClass2counts.keySet()) { float[] sourceCounts = sourceClass2counts.get(classId); if (sourceCounts != null && srcId < sourceCounts.length && sourceCounts[srcId] != 0) { float[] targetCounts = targetClass2counts.get(classId); float[] newCounts = new float[tarId + 1]; if (targetCounts != null) { System.arraycopy(targetCounts, 0, newCounts, 0, targetCounts.length); } newCounts[tarId] = sourceCounts[srcId]; targetClass2counts.put(classId, newCounts); } } } this.totalReads += sampleSize; } } /** * extract a set of samples to the given target * */ public void extractSamplesTo(Collection<String> samples, DataTable target) { Set<String> toDelete = new HashSet<>(sampleNames); toDelete.removeAll(samples); target.copy(this); target.removeSamples(toDelete); } /** * merge the named samples * */ public void mergeSamples(Collection<String> samples, String newName) { if (sampleNames.contains(newName)) return; var pids = new HashSet<Integer>(); BlastMode mode = null; for (var name : samples) { int pid = StringUtils.getIndex(name, sampleNames); if (pid == -1) { System.err.println("No such sample: " + name); return; } pids.add(pid); if (mode == null) { mode = (pid < blastModes.size() ? blastModes.get(pid) : BlastMode.Unknown); } else if (mode != BlastMode.Unknown && blastModes.get(pid) != mode) mode = BlastMode.Unknown; } var reads = 0f; for (var pid : pids) { reads += sampleSizes.get(pid); } sampleSizes.add(reads); sampleNames.add(newName); sampleUIds.add(System.currentTimeMillis()); blastModes.add(mode); var tarId = StringUtils.getIndex(newName, sampleNames); for (var class2counts : classification2class2counts.values()) { for (var classId : class2counts.keySet()) { var counts = class2counts.get(classId); if (counts != null) { var newLength = Math.max(counts.length + 1, tarId + 1); var newCounts = new float[newLength]; System.arraycopy(counts, 0, newCounts, 0, counts.length); var sum = 0; for (var pid : pids) { if (pid < counts.length && counts[pid] != 0) sum += counts[pid]; } newCounts[tarId] = sum; class2counts.put(classId, newCounts); } } } for (var size : sampleSizes) { totalReads += size; } } /** * reorder samples * */ public void reorderSamples(Collection<String> newOrder) throws IOException { final var order = new Integer[newOrder.size()]; var i = 0; for (String sample : newOrder) { int pid = StringUtils.getIndex(sample, getSampleNamesArray()); if (pid == -1) throw new IOException("Can't reorder: unknown sample: " + sample); order[i++] = pid; } final var datasetNames = modify(order, getSampleNamesArray()); final var uids = modify(order, getSampleUIds()); final var sizes = modify(order, getSampleSizes()); final var modes = modify(order, getBlastModes()); setSamples(datasetNames, uids, sizes, modes); final var classification2Class2Counts = getClassification2Class2Counts(); for (var classification : classification2Class2Counts.keySet()) { final var class2Counts = classification2Class2Counts.get(classification); final var keys = new HashSet<>(class2Counts.keySet()); for (var classId : keys) { var values = class2Counts.get(classId); if (values != null) { values = modify(order, values); class2Counts.put(classId, values); } } } } /** * modify an array according to the given order * * @return modified array, possibly with changed length */ private static String[] modify(Integer[] order, String[] array) { var tmp = new String[order.length]; var pos = 0; for (var id : order) { if (id < array.length) tmp[pos++] = array[id]; } return tmp; } /** * modify an array according to the given order * * @return modified array, possibly with changed length */ private static float[] modify(Integer[] order, float[] array) { var tmp = new float[order.length]; var pos = 0; for (var id : order) { if (id < array.length) tmp[pos++] = array[id]; } return tmp; } /** * modify an array according to the given order * * @return modified array, possibly with changed length */ private static Long[] modify(Integer[] order, Long[] array) { var tmp = new Long[order.length]; var pos = 0; for (var id : order) { if (id < array.length) tmp[pos++] = array[id]; } return tmp; } /** * modify an array according to the given order * * @return modified array, possibly with changed length */ private static BlastMode[] modify(Integer[] order, BlastMode[] array) { var tmp = new BlastMode[order.length]; var pos = 0; for (var id : order) { if (id < array.length) tmp[pos++] = array[id]; } return tmp; } /** * disable some of the samples * */ private void disableSamples(Collection<String> sampleNames) { var size = disabledSamples.size(); var newDisabled = new HashSet<String>(); newDisabled.addAll(disabledSamples); newDisabled.addAll(sampleNames); if (newDisabled.size() != size) { if (originalData == null) { originalData = new DataTable(); originalData.copy(this); } copyEnabled(newDisabled, originalData); disabledSamples.clear(); disabledSamples.addAll(newDisabled); } } /** * enable the given set of samples * * @return true, if changed */ public boolean setEnabledSamples(Collection<String> names) { var oldDisabled = new HashSet<>(disabledSamples); var newDisabled = new HashSet<String>(); if (originalData != null) newDisabled.addAll(originalData.sampleNames); else newDisabled.addAll(sampleNames); newDisabled.removeAll(names); if (originalData == null) { originalData = new DataTable(); originalData.copy(this); } copyEnabled(newDisabled, originalData); return !disabledSamples.equals(oldDisabled); } /** * enable a set of samples * */ public void enableSamples(Collection<String> sampleNames) { var size = disabledSamples.size(); disabledSamples.removeAll(sampleNames); if (size != disabledSamples.size()) { if (originalData == null) { originalData = new DataTable(); originalData.copy(this); } Set<String> newDisabled = new HashSet<>(disabledSamples); copyEnabled(newDisabled, originalData); } } /** * copy the enabled samples from the original data * */ private void copyEnabled(Set<String> disabledSamples, DataTable originalData) { clear(); var origSampleNames = originalData.getSampleNamesArray(); var activeIndices = new BitSet(); for (var i = 0; i < origSampleNames.length; i++) { if (!disabledSamples.contains(origSampleNames[i])) { activeIndices.set(i); } } var origSampleUIds = originalData.getSampleUIds(); var origSampleSizes = originalData.getSampleSizes(); var origBlastModes = originalData.getBlastModes(); sampleNames.clear(); var totalReads = 0; for (var origIndex = 0; origIndex < origSampleNames.length; origIndex++) { if (activeIndices.get(origIndex)) { sampleNames.addElement(origSampleNames[origIndex]); if (origSampleUIds != null && origSampleUIds.length > origIndex) sampleUIds.addElement(origSampleUIds[origIndex]); if (origBlastModes != null && origBlastModes.length > origIndex) blastModes.addElement(origBlastModes[origIndex]); sampleSizes.addElement(origSampleSizes[origIndex]); totalReads += origSampleSizes[origIndex]; } } setTotalReads(totalReads); // write the data: for (var classification : originalData.classification2class2counts.keySet()) { var origClass2counts = originalData.classification2class2counts.get(classification); var class2counts = classification2class2counts.computeIfAbsent(classification, k -> new HashMap<>()); for (var classId : origClass2counts.keySet()) { var origCounts = origClass2counts.get(classId); var counts = new float[activeIndices.cardinality()]; var index = 0; for (var origIndex = 0; origIndex < origCounts.length; origIndex++) { if (activeIndices.get(origIndex)) { counts[index++] = origCounts[origIndex]; } } class2counts.put(classId, counts); } } this.disabledSamples.addAll(disabledSamples); } public Set<String> getDisabledSamples() { return new HashSet<>(disabledSamples); } public int getNumberOfSamples() { return sampleNames.size(); } public String[] getOriginalSamples() { if (disabledSamples.size() > 0 && originalData != null) return originalData.getSampleNamesArray(); else return getSampleNamesArray(); } /** * gets the indices of the given samples * * @return ids */ public BitSet getSampleIds(Collection<String> samples) { var sampleIds = new BitSet(); var sampleNames = getSampleNamesArray(); for (var i = 0; i < sampleNames.length; i++) { if (samples.contains(sampleNames[i])) sampleIds.set(i); } return sampleIds; } public void clearCollapsed() { classification2collapsedIds.clear(); } public int getSampleId(String sample) { return CollectionUtils.getIndex(sample,getSampleNamesArray()); } }
54,859
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectionSet.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/SelectionSet.java
/* * SelectionSet.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import java.util.*; /** * maintains selection state of labels * Daniel Huson, 1.2013 */ public class SelectionSet { private boolean selectionIsChanging = false; private final Set<String> selectedLabels = new HashSet<>(); private final List<SelectionListener> selectionListenerList = new LinkedList<>(); private final SelectionListener listener = (labels, selected) -> { }; /** * set the selection state of the label * */ public void setSelected(String label, boolean selected) { if (!selectionIsChanging) { selectionIsChanging = true; try { int currentSize = size(); if (selected) this.selectedLabels.add(label); else this.selectedLabels.remove(label); if (currentSize != size()) { fireChanged(Collections.singletonList(label), selected); } } finally { selectionIsChanging = false; } } } /** * sets the selection state of a collection of labels * */ public void setSelected(java.util.Collection<String> labels, boolean selected) { if (!selectionIsChanging) { selectionIsChanging = true; try { int currentSize = size(); if (selected) this.selectedLabels.addAll(labels); else this.selectedLabels.removeAll(labels); if (currentSize != size()) fireChanged(labels, selected); } finally { selectionIsChanging = false; } } } /** * is label selected? * * @return true, if selected */ public boolean isSelected(String label) { return selectedLabels.contains(label); } public Set<String> getAll() { return selectedLabels; } public void clear() { if (!selectionIsChanging) { selectionIsChanging = true; try { Set<String> selected = new HashSet<>(this.selectedLabels); this.selectedLabels.clear(); fireChanged(selected, false); } finally { selectionIsChanging = false; } } } public int size() { return selectedLabels.size(); } private void fireChanged(java.util.Collection<String> labels, boolean select) { for (SelectionListener selectionListener : selectionListenerList) { selectionListener.changed(labels, select); } } public void addSampleSelectionListener(SelectionListener selectionListener) { selectionListenerList.add(selectionListener); } public void removeSampleSelectionListener(SelectionListener selectionListener) { selectionListenerList.remove(selectionListener); } public void removeAllSampleSelectionListeners() { selectionListenerList.clear(); } public interface SelectionListener { void changed(java.util.Collection<String> labels, boolean selected); } }
4,006
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SampleAttributeTable.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/core/SampleAttributeTable.java
/* * SampleAttributeTable.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.core; import jloda.util.*; import java.awt.*; import java.io.*; import java.text.DateFormat; import java.text.ParseException; import java.util.List; import java.util.*; /** * holds a table of metadata * Daniel Huson, 12.2012 */ public class SampleAttributeTable { public enum Type {String, Integer, Float, Date} public static final String SAMPLE_ATTRIBUTES = "SAMPLE_ATTRIBUTES"; public static final String USER_STATE = "USER_STATE"; public static final String SAMPLE_ID = "#SampleID"; public static final String DescriptionAttribute = "Description"; public enum HiddenAttribute { Shape, Color, Label, Source, GroupId; /** * get the prefix used to identify hidden attributes * * @return prefix */ static String getPrefix() { return "@"; } /** * hidden attributes start with @ * */ public String toString() { return getPrefix() + super.toString(); } /** * get the value for the given label * * @return attribute */ public HiddenAttribute getEnum(String label) { if (label.startsWith(getPrefix())) return valueOf(label.substring(1)); else return valueOf(label); } } private final Table<String, String, Object> table = new Table<>(); private final ArrayList<String> sampleOrder = new ArrayList<>(); private final ArrayList<String> attributeOrder = new ArrayList<>(); private final Map<String, Type> attribute2type = new HashMap<>(); private String description = null; /** * erase the table */ public void clear() { description = null; table.clear(); sampleOrder.clear(); attributeOrder.clear(); attribute2type.clear(); } /** * add a metadata table * */ public void addTable(SampleAttributeTable sampleAttributeTable, boolean allowReplaceSample, boolean allowAddAttribute) { boolean changed = false; for (String sample : sampleAttributeTable.getSampleSet()) { if (allowReplaceSample || !table.rowKeySet().contains(sample)) { if (addSample(sample, sampleAttributeTable.getAttributesToValues(sample), true, allowAddAttribute)) changed = true; } } } /** * extract a metadata table containing the named samples * * @return the new table */ public SampleAttributeTable extractTable(Collection<String> samples) { SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); for (String sample : getSampleOrder()) { if (samples.contains(sample)) { sampleAttributeTable.addSample(sample, getAttributesToValues(sample), true, true); } } sampleAttributeTable.attributeOrder.clear(); sampleAttributeTable.attributeOrder.addAll(attributeOrder); for (String attribute : attribute2type.keySet()) { sampleAttributeTable.attribute2type.put(attribute, attribute2type.get(attribute)); } sampleAttributeTable.removeUndefinedAttributes(); return sampleAttributeTable; } /** * merges a set of samples and produces a new sample * * @return true, if merged */ public SampleAttributeTable mergeSamples(Collection<String> samples, String newName) { SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); Map<String, Object> attribute2value = new HashMap<>(); for (String attribute : getAttributeSet()) { boolean valueMismatch = false; Object previousValue = null; for (String sample : samples) { Object value = table.get(sample, attribute); if (value != null) { if (previousValue == null) previousValue = value; else if (!value.equals(previousValue)) { valueMismatch = true; break; } } } if (!valueMismatch && previousValue != null) { attribute2value.put(attribute, previousValue); } } sampleAttributeTable.addSample(newName, attribute2value, true, true); return sampleAttributeTable; } /** * add a sample to the table * * @return true, if added */ public boolean addSample(String sample, Map<String, Object> attribute2value, boolean allowReplaceSample, boolean allowAddAttribute) { if (!table.rowKeySet().contains(sample)) { sampleOrder.add(sample); } if (allowReplaceSample || !table.rowKeySet().contains(sample)) { for (String attribute : attribute2value.keySet()) { if (allowAddAttribute || getAttributeSet().contains(attribute)) put(sample, attribute, attribute2value.get(attribute)); } //put(sample, SampleAttributeTable.SAMPLE_ID, sample); return true; } return false; } /** * set the sample order * */ public void setSampleOrder(List<String> sampleNames) { sampleOrder.clear(); sampleOrder.addAll(sampleNames); for (String sampleName : sampleNames) { if (!table.rowKeySet().contains(sampleName)) table.put(sampleName, HiddenAttribute.Color.toString(), null); } } /** * remove a sample from the table * */ public void removeSample(String name) { if (table.rowKeySet().contains(name)) { table.rowKeySet().remove(name); sampleOrder.remove(name); } } /** * rename a sample * */ public void renameSample(String sample, String newName, boolean allowReplaceSample) { if (allowReplaceSample || !table.rowKeySet().contains(newName) && sampleOrder.contains(sample)) { sampleOrder.set(sampleOrder.indexOf(sample), newName); final Map<String, Object> row = table.row(sample); if (row != null) { table.rowKeySet().remove(sample); for (String key : row.keySet()) { table.put(newName, key, row.get(key)); } } } } /** * duplicate an existing sample * * @return true, if duplicated */ public boolean duplicateSample(String sample, String newName, boolean allowReplaceSample) { if (allowReplaceSample || !table.rowKeySet().contains(newName)) { Map<String, Object> row = table.row(sample); return addSample(newName, row, true, false); } return false; } /** * add an attribute with same value to all samples * */ public void addAttribute(String attribute, Object value, boolean allowReplaceAttribute) { boolean change = false; if (allowReplaceAttribute || !table.columnKeySet().contains(attribute)) { for (String sample : getSampleOrder()) { put(sample, attribute, value); } change = true; } } /** * add an attribute * * @return true, if added */ public boolean addAttribute(String attribute, Map<String, Object> sample2value, boolean allowReplaceAttribute, boolean allowAddSample) { if (allowReplaceAttribute || !table.columnKeySet().contains(attribute)) { if (sample2value.size() > 0) { for (String sample : sample2value.keySet()) { if (allowAddSample || getSampleSet().contains(sample)) put(sample, attribute, sample2value.get(sample)); } } else { for (String sample : getSampleSet()) { put(sample, attribute, null); } } return true; } return false; } /** * remove an attribute * */ public void removeAttribute(String attribute) { attributeOrder.remove(attribute); attribute2type.keySet().remove(attribute); table.removeColumn(attribute); } /** * remove a collection of attributes * */ private void removeAttributes(Collection<String> attributes) { attributeOrder.removeAll(attributes); attribute2type.keySet().removeAll(attributes); for (String attribute : attributes) { table.removeColumn(attribute); } } /** * duplicate an existing attribute * * @return true, if duplicated */ public boolean duplicateAttribute(String attribute, String newName, boolean allowReplaceSample) { if (allowReplaceSample || !table.columnKeySet().contains(newName)) { Map<String, Object> samples2values = table.column(attribute); boolean result = addAttribute(newName, samples2values, true, false); if (result) attribute2type.put(newName, attribute2type.get(attribute)); return result; } return false; } /** * expands an existing attribute * * @return number of columns added */ public int expandAttribute(String attribute, boolean allowReplaceAttribute) { final Set<Object> values = new TreeSet<>(getSamples2Values(attribute).values()); final ArrayList<String> newOrder = new ArrayList<>(getAttributeOrder().size() + values.size()); newOrder.addAll(getAttributeOrder()); int pos = newOrder.indexOf(attribute); int count = 0; for (Object value : values) { final String attributeName = attribute + ":" + value; if (!getAttributeOrder().contains(attributeName)) { Map<String, Object> samples2values = new HashMap<>(); for (String sample : getSampleOrder()) { samples2values.put(sample, get(sample, attribute).equals(value) ? 1 : 0); } boolean result = addAttribute(attributeName, samples2values, allowReplaceAttribute, false); if (result) { attribute2type.put(attributeName, Type.Integer); count++; newOrder.add(pos + count, attributeName); } } } setAttributeOrder(newOrder); return count; } /** * removes all attributes for which no sample has a defined value */ private void removeUndefinedAttributes() { LinkedList<String> undefined = new LinkedList<>(); for (String attribute : getAttributeSet()) { Map<String, Object> sample2values = getSamples2Values(attribute); boolean ok = false; for (String sample : sample2values.keySet()) { if (sample2values.get(sample) != null) { ok = true; break; } } if (!ok) undefined.add(attribute); } if (undefined.size() > 0) removeAttributes(undefined); } /** * gets the set type of an attribute * * @return type */ public Type getAttributeType(String attribute) { Type type = attribute2type.get(attribute); if (type == null) { setAttributeTypeFromValues(attribute); type = attribute2type.get(attribute); } return type; } private void setAttributeType(String attribute, Type type) { attribute2type.put(attribute, type); } public ArrayList<String> getSampleOrder() { return sampleOrder; } public List<String> getAttributeOrder() { return attributeOrder; } public void setAttributeOrder(Collection<String> attributeOrder) { this.attributeOrder.clear(); this.attributeOrder.addAll(attributeOrder); } public Set<String> getSampleSet() { return table.rowKeySet(); } private Set<String> getAttributeSet() { return table.columnKeySet(); } /** * gets attribute to values mapping for named sample * * @return map */ public Map<String, Object> getAttributesToValues(String sample) { return table.row(sample); } /** * gets sample to values mapping for named attribute * * @return map */ public Map<String, Object> getSamples2Values(String attribute) { return table.column(attribute); } public int getNumberOfSamples() { return table.rowKeySet().size(); } public int getNumberOfAttributes() { return table.columnKeySet().size(); } public int getNumberOfUnhiddenAttributes() { int count = 0; for (String attribute : getAttributeOrder()) if (!isHiddenAttribute(attribute) && !isSecretAttribute(attribute)) count++; return count; } public ArrayList<String> getUnhiddenAttributes() { ArrayList<String> list = new ArrayList<>(getNumberOfAttributes()); for (String attribute : getAttributeOrder()) if (!isHiddenAttribute(attribute) && !isSecretAttribute(attribute)) list.add(attribute); return list; } /** * get the value for a given sample and attribute * * @return value or null */ public Object get(String sample, String attribute) { if (attribute.equals(SAMPLE_ID)) return sample; else return table.get(sample, attribute); } /** * get the value for a given sample and attribute * * @return value or null */ private Object get(String sample, HiddenAttribute attribute) { return table.get(sample, attribute.toString()); } /** * put a value in the table * */ public void put(String sample, String attribute, Object value) { if (!sampleOrder.contains(sample)) sampleOrder.add(sample); if (!attributeOrder.contains(attribute)) attributeOrder.add(attribute); table.put(sample, attribute, value); } /** * put a value in the table * */ public void put(String sample, HiddenAttribute attribute, Object value) { put(sample, attribute.toString(), value); } /** * gets the color of a sample * * @return sample color */ public Color getSampleColor(String sampleName) { Object colorValue = get(sampleName, SampleAttributeTable.HiddenAttribute.Color); if (colorValue instanceof Integer) { return new Color((Integer) colorValue); } else return null; } /** * set the color associated with a sample * * @param color or null */ public void putSampleColor(String sampleName, Color color) { put(sampleName, SampleAttributeTable.HiddenAttribute.Color, color != null ? color.getRGB() : null); } /** * is some sample colored * * @return true, if some sample colored */ public boolean isSomeSampleColored() { for (String sample : getSampleOrder()) { if (get(sample, HiddenAttribute.Color) != null) return true; } return false; } /** * set the shape associated with a sample * */ public void putSampleShape(String sampleName, String shape) { put(sampleName, HiddenAttribute.Shape, shape); } /** * get the shape associated with a sample * * @return shape */ public String getSampleShape(String sampleName) { Object shape = get(sampleName, HiddenAttribute.Shape); if (shape != null) return shape.toString(); else return null; } /** * get the sample label * * @return label */ public String getSampleLabel(String sampleName) { Object label = get(sampleName, HiddenAttribute.Label); if (label != null) return label.toString(); else return null; } /** * set the group id associated with a sample * */ public void putGroupId(String sampleName, String id) { put(sampleName, HiddenAttribute.GroupId, id); } /** * get the group id associated with a sample * * @return join label */ public String getGroupId(String sampleName) { Object obj = get(sampleName, HiddenAttribute.GroupId); if (obj == null) return null; else return obj.toString(); } /** * are there any groups defined? * * @return true, if at least one sample has a group */ public boolean hasGroups() { for (String sampleName : sampleOrder) { if (getGroupId(sampleName) != null) return true; } return false; } /** * put the label to be used for the sample * */ public void putSampleLabel(String sampleName, String label) { put(sampleName, SampleAttributeTable.HiddenAttribute.Label, label); } /** * look at all values for a given attribute and set its type * */ private void setAttributeTypeFromValues(String attribute) { boolean isFloat = true; boolean isInteger = true; boolean isDate = true; for (String sample : getSampleSet()) { Object value = get(sample, attribute); if (value != null) { String label = value.toString(); if (label.length() > 0) { if (!NumberUtils.isInteger(label)) isInteger = false; if (!NumberUtils.isFloat(label)) isFloat = false; if (!StringUtils.isDate(label)) isDate = false; } } } Type type; if (isDate) type = Type.Date; else if (isInteger) type = Type.Integer; else if (isFloat) type = Type.Float; else type = Type.String; setAttributeType(attribute, type); for (String sample : getSampleSet()) { Object value = get(sample, attribute); if (value != null) { String label = value.toString(); if (label != null) { label = label.trim(); if (label.length() > 0) { switch (type) { case Date: if (!(value instanceof Date)) try { put(sample, attribute, DateFormat.getDateInstance().parse(label)); } catch (ParseException e) { Basic.caught(e); } break; case Integer: if (!(value instanceof Integer)) put(sample, attribute, Integer.parseInt(label)); break; case Float: if (!(value instanceof Float)) put(sample, attribute, Float.parseFloat(label)); break; default: case String: if (!(value instanceof String)) put(sample, attribute, label); break; } } } } } } /** * set the attribute types from given values */ private void setAllAttributeTypesFromValues() { for (String attribute : getAttributeSet()) { setAttributeTypeFromValues(attribute); } } /** * gets all source files embedded in this file * * @return embedded source files */ public ArrayList<String> getSourceFiles() { final ArrayList<String> sourceFiles = new ArrayList<>(); for (String sample : sampleOrder) { final Object obj = get(sample, SampleAttributeTable.HiddenAttribute.Source); if (obj != null) { sourceFiles.add(obj.toString()); } } return sourceFiles; } /** * write the table to a file in QIIME-based format * */ public void write(Writer w, boolean ensureQIIMECompatible, boolean includeSecret) throws IOException { final Set<String> attributes = getAttributeSet(); w.write(SAMPLE_ID); if (ensureQIIMECompatible) { if (attributes.contains("BarcodeSequence")) w.write("\tBarcodeSequence"); w.write("\tLinkerPrimerSequence"); for (String name : getAttributeOrder()) { if (!name.equals(SAMPLE_ID) && !name.equals("BarcodeSequence") && !name.equals("LinkerPrimerSequence") && !name.equals("Description") && (includeSecret || !isSecretAttribute(name))) { w.write("\t" + name); } } w.write("\tDescription"); } else { for (String name : getAttributeOrder()) { if (!name.equals(SAMPLE_ID) && !name.equals("BarcodeSequence") && !name.equals("LinkerPrimerSequence") && (includeSecret || !isSecretAttribute(name))) { w.write("\t" + name); } } } w.write("\n"); if (description != null && description.length() > 0) w.write((description.startsWith("#") ? description : "#" + description) + "\n"); for (String sample : getSampleOrder()) { w.write(sample); final Map<String, Object> attributes2value = getAttributesToValues(sample); if (attributes2value != null) { if (ensureQIIMECompatible) { if (attributes.contains("BarcodeSequence")) { Object barcodeSequence = attributes2value.get("BarcodeSequence"); if (barcodeSequence != null) w.write("\t" + StringUtils.quoteIfContainsTab(barcodeSequence)); else w.write("\tAAA"); } Object linkerPrimerSequence = attributes2value.get("LinkerPrimerSequence"); if (linkerPrimerSequence != null) w.write("\t" + StringUtils.quoteIfContainsTab(linkerPrimerSequence)); else w.write("\t"); for (String name : getAttributeOrder()) { if (!name.equals(SAMPLE_ID) && !name.equals("BarcodeSequence") && !name.equals("LinkerPrimerSequence") && (includeSecret || !isSecretAttribute(name))) { Object value = attributes2value.get(name); if (value != null) w.write("\t" + StringUtils.quoteIfContainsTab(value)); else w.write("\tNA"); } } Object description = attributes2value.get("Description"); if (description != null) w.write("\t" + StringUtils.quoteIfContainsTab(description)); else w.write("\tNA"); } else { for (String name : getAttributeOrder()) { if (!name.equals(SAMPLE_ID) && !name.equals("BarcodeSequence") && !name.equals("LinkerPrimerSequence") && (includeSecret || !isSecretAttribute(name))) { Object value = attributes2value.get(name); if (value != null) w.write("\t" + StringUtils.quoteIfContainsTab(value)); else w.write("\tNA"); } } } } w.write("\n"); } w.flush(); } /** * gets a string of bytes representing this table * * @return bytes */ public byte[] getBytes() { StringWriter w = new StringWriter(); try { write(w, false, true); } catch (IOException ignored) { } return w.toString().getBytes(); } /** * reads metadata from a readerWriter * * @param clear @throws IOException */ public void read(Reader reader, Collection<String> knownSamples, boolean clear) throws IOException { int countNotFound = 0; if (clear) clear(); try (BufferedReader r = new BufferedReader(reader)) { // read header line: String aLine = r.readLine(); while (aLine != null && aLine.trim().length() == 0) { aLine = r.readLine(); } if (aLine != null) { String[] tokens = StringUtils.splitWithQuotes(aLine, '\t'); if (tokens.length < 1 || !tokens[0].startsWith(SAMPLE_ID)) { throw new IOException(SAMPLE_ID + " tag not found, no sample-attributes data..."); } final int tokensPerLine = tokens.length; final Set<String> newAttributes = new HashSet<>(); final List<String> attributesOrder = new LinkedList<>(); for (int i = 1; i < tokensPerLine; i++) // first token is SAMPLE_ID, not an attribute { String attribute = tokens[i]; if (!isSecretAttribute(attribute) && !isHiddenAttribute(attribute) && (newAttributes.contains(attribute) || getAttributeOrder().contains(attribute))) { int count = 1; while (newAttributes.contains(attribute + "." + count) || getAttributeOrder().contains(attribute + "." + count)) { count++; } System.err.println("Attribute " + attribute + " already exists, renaming to: " + attribute + "." + count); attribute += "." + count; } newAttributes.add(attribute); attributesOrder.add(attribute); } final String[] pos2attribute = attributesOrder.toArray(new String[0]); for (int i = 0; i < pos2attribute.length; i++) { if (isHiddenAttribute(pos2attribute[i])) // don't import hidden attributes pos2attribute[i] = null; else getAttributeOrder().add(pos2attribute[i]); } final Set<String> mentionedSamples = new HashSet<>(); while ((aLine = r.readLine()) != null) { aLine = aLine.trim(); if (aLine.startsWith("#")) { if (description == null) description = aLine; else if (!description.equals("#EOF") && !description.equals("# EOF")) description += " " + aLine; } else { tokens = StringUtils.splitWithQuotes(aLine, '\t'); if (tokens.length > 0) { if (tokens.length != tokensPerLine) throw new IOException("Expected " + tokensPerLine + " tokens, got " + tokens.length + " in line: " + aLine); final String sample = tokens[0].trim(); if (sample.length() == 0) continue; // empty? if (mentionedSamples.contains(sample)) { System.err.println("Sample occurs more than once: " + sample + ", ignoring repeated occurrences"); continue; } mentionedSamples.add(sample); if (knownSamples == null || knownSamples.contains(sample)) { Map<String, Object> attribute2value = new HashMap<>(); for (int i = 1; i < tokensPerLine; i++) { { String attribute = pos2attribute[i - 1]; if (attribute != null) attribute2value.put(attribute, tokens[i].equals("NA") ? null : tokens[i]); } } addSample(sample, attribute2value, true, true); } else { System.err.println("Sample mentioned in metadata is not present in document, skipping: " + sample); countNotFound++; } } } } setAllAttributeTypesFromValues(); } } finally { if (countNotFound > 0) System.err.println("Warning: Loaded metadata, ignored " + countNotFound + " unknown input samples."); else { if (knownSamples != null) { for (String sample : knownSamples) { if(getSampleLabel(sample)==null) putSampleLabel(sample, getSampleLabel(sample)); } } } } } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** * determines which non-hidden attributes have a numerical interpretation and returns them * * @return numerical attributes */ public Collection<String> getNumericalAttributes() { final Map<String, float[]> attributes = getNumericalAttributes(getUnhiddenAttributes()); return new TreeSet<>(attributes.keySet()); } /** * determines which attributes have a numerical interpretation and returns their values * * @return numerical attributes */ public HashMap<String, float[]> getNumericalAttributes(List<String> samples) { return getNumericalAttributes(samples, true); } /** * determines which attributes have a numerical interpretation and returns their values * * @return numerical attributes */ public HashMap<String, float[]> getNumericalAttributes(List<String> samples, boolean normalize) { if (samples == null) samples = getSampleOrder(); final HashMap<String, float[]> result = new HashMap<>(); final Set<String> hiddenAttributes = new HashSet<>(Arrays.asList("BarcodeSequence", "LinkerPrimerSequence", "Description")); for (String name : getAttributeOrder()) { if (isSecretAttribute(name) || isHiddenAttribute(name) || name.equals("Size") || hiddenAttributes.contains(name)) continue; switch (getAttributeType(name)) { case Float, Integer -> { final float[] array = new float[samples.size()]; float maxAbs = Float.MIN_VALUE; int i = 0; for (String sample : samples) { //System.err.println("sample: "+sample); final Object object = get(sample, name); if (object != null) { String str = object.toString().trim(); float value = str.length() > 0 ? Float.parseFloat(str) : 0f; array[i++] = value; maxAbs = Math.max(Math.abs(value), maxAbs); } else array[i++] = 0; } if (normalize && maxAbs > 0) { for (i = 0; i < array.length; i++) array[i] /= maxAbs; } result.put(name, array); } case String -> { String firstValue = null; String secondValue = null; for (String sample : samples) { Object obj = get(sample, name); if (obj != null) { String str = obj.toString(); if (firstValue == null) firstValue = str; else if (!firstValue.equals(str)) { if (secondValue == null) { secondValue = str; } else if (!secondValue.equals(str)) { secondValue = null; // use this to indicate that not ok break; } } } } if (secondValue != null) { final float[] array = new float[samples.size()]; String firstState = null; int i = 0; for (String sample : samples) { final Object object = get(sample, name); if (object != null) { String str = object.toString(); if (firstState == null || firstState.equals(str)) { firstState = str; array[i++] = 0; } else array[i++] = 1; } else array[i++] = 0; } result.put(name, array); } } } } return result; } /** * sort the samples by the values of the given attribute * * @param ascending, if true, otherwise descending * @return true, if order is changed */ public boolean sortSamplesByAttribute(String attribute, final boolean ascending) { final List<String> originalOrder = new ArrayList<>(getNumberOfSamples()); originalOrder.addAll(getSampleOrder()); try { final List<String> undefined = new ArrayList<>(getNumberOfSamples()); final List<Pair<Object, String>> list = new ArrayList<>(getNumberOfSamples()); for (String sample : getSampleOrder()) { Object value = get(sample, attribute); if (value != null && value.toString().length() > 0) list.add(new Pair<>(value, sample)); else undefined.add(sample); } Pair<Object, String>[] array = list.toArray(new Pair[0]); switch (getAttributeType(attribute)) { case Integer, Float -> Arrays.sort(array, (p1, p2) -> { Float a1 = Float.parseFloat(p1.getFirst().toString()); Float a2 = Float.parseFloat(p2.getFirst().toString()); return ascending ? a1.compareTo(a2) : -a1.compareTo(a2); }); case String -> Arrays.sort(array, (p1, p2) -> { String a1 = p1.getFirst().toString(); String a2 = p2.getFirst().toString(); return ascending ? a1.compareTo(a2) : -a1.compareTo(a2); }); } getSampleOrder().clear(); for (Pair<Object, String> pair : array) { getSampleOrder().add(pair.getSecond()); } getSampleOrder().addAll(undefined); } catch (Exception ex) { Basic.caught(ex); sampleOrder.clear(); sampleOrder.addAll(originalOrder); } return !originalOrder.equals(getSampleOrder()); } /** * is this a secret attribute (such as color etc) * * @return true, if secret */ public boolean isSecretAttribute(String attribute) { return attribute.startsWith("@"); } /** * is this a hidden attribute (such as color etc) * * @return true, if secret */ public boolean isHiddenAttribute(String attribute) { return attribute.endsWith(" [hidden]"); } /** * get a copy * * @return a copy */ public SampleAttributeTable copy() { final SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); try (StringWriter w = new StringWriter()) { write(w, false, true); sampleAttributeTable.read(new StringReader(w.toString()), getSampleOrder(), false); } catch (IOException e) { Basic.caught(e); // shouldn't happend } return sampleAttributeTable; } /** * move set of sample up or down one position * */ public void moveSamples(boolean up, Collection<String> samples) { samples = StringUtils.sortSubsetAsContainingSet(sampleOrder, samples); if (up) { for (String sample : samples) { final int index = sampleOrder.indexOf(sample); swapSamples(index, index - 1); } } else { // down for (String sample : CollectionUtils.reverseList(samples)) { final int index = sampleOrder.indexOf(sample); swapSamples(index, index + 1); } } } private void swapSamples(int index1, int index2) { final int min = Math.min(index1, index2); final int max = Math.max(index1, index2); if (min != max && min >= 0 && max < sampleOrder.size()) { final String minSample = sampleOrder.get(min); final String maxSample = sampleOrder.get(max); sampleOrder.set(min, maxSample); sampleOrder.set(max, minSample); } } }
39,580
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TaxonomicSegmentation.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/analysis/TaxonomicSegmentation.java
/* * TaxonomicSegmentation.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.analysis; import jloda.util.CanceledException; import jloda.util.CollectionUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.IntervalTree; import jloda.util.progress.ProgressListener; import megan.algorithms.IntervalTree4Matches; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.viewer.TaxonomicLevels; import megan.viewer.TaxonomyData; import java.util.*; /** * computes the taxonomic segmentation of a read * Daniel Huson, 8.2018 */ public class TaxonomicSegmentation { private static final int defaultRank = 0; // use next down public static final float defaultSwitchPenalty = 10000f; // always non-negative public static final float defaultCompatibleFactor = 1f; // always non-negative public static final float defaultIncompatibleFactor = 0.2f; // always non-negative private int rank = defaultRank; // rank 0 means use rank one below class id rank private int classId = 0; // class id to which read is taxonomically assigned, or 0 private final Map<Integer, Integer> tax2taxAtRank; private float switchPenalty = defaultSwitchPenalty; private float compatibleFactor = defaultCompatibleFactor; private float incompatibleFactor = defaultIncompatibleFactor; public String getParamaterString() { return "rank=" + TaxonomicLevels.getName(rank) + " classId=" + TaxonomyData.getName2IdMap().get(classId) + " switchPenalty=" + StringUtils.removeTrailingZerosAfterDot("" + switchPenalty) + " compatibleFactor=" + StringUtils.removeTrailingZerosAfterDot("" + compatibleFactor) + " incompatibleFactor=" + StringUtils.removeTrailingZerosAfterDot("" + incompatibleFactor); } /** * constructor */ public TaxonomicSegmentation() { tax2taxAtRank = new HashMap<>(); } /** * computes the segmentation */ public ArrayList<Segment> computeTaxonomicSegmentation(ProgressListener progress, IReadBlock readBlock) throws CanceledException { final var originalSequence = readBlock.getReadSequence(); if (originalSequence == null) return null; progress.setSubtask("Computing intervals"); final var intervals = IntervalTree4Matches.computeIntervalTree(readBlock, null, progress); // todo: use dominated only? final var positions = new TreeSet<Integer>(); for (var interval : intervals) { positions.add(interval.getStart() + 1); positions.add(interval.getEnd() - 1); } final var columns = computeDPColumns(intervals, positions); final var allTaxa = new TreeSet<Integer>(); for (var matchBlock : intervals.values()) { if (matchBlock.getTaxonId() > 0) { final var tax = getTaxonAtRank(matchBlock.getTaxonId()); if (tax > 0) allTaxa.add(tax); else if (classId > 0 && TaxonomyData.isAncestor(tax, classId)) // if alignment lies on or above the target taxon, use it allTaxa.add(classId); } } if (allTaxa.size() == 0) return new ArrayList<>(); progress.setSubtask("Running dynamic program"); progress.setMaximum(columns.size()); progress.setProgress(0); final var tax2row = new HashMap<Integer, Integer>(); { var row = 0; for (var tax : allTaxa) { tax2row.put(tax, row++); } } final var scoreMatrix = new float[columns.size()][allTaxa.size()]; final var traceBackMatrix = new int[columns.size()][allTaxa.size()]; var verbose = false; { for (var col = 1; col < columns.size(); col++) { // skip the first point final var column = columns.get(col); if (verbose) System.err.println(String.format("DPColumn@ %,d", column.getPos()) + ":"); for (var tax : allTaxa) { if (tax != classId) { // don't use current assigned class, just need to use its alignments final var row = tax2row.get(tax); var maxScore = -10000000.0f; var maxScoreTax = 0; for (var otherTax : allTaxa) { final var otherRow = tax2row.get(otherTax); if (otherTax.equals(tax)) { // look at staying with tax final float score; if (column.getScore(tax) > 0 || column.getScore(classId) > 0) { score = scoreMatrix[col - 1][row] + compatibleFactor * Math.max(column.getScore(tax), column.getScore(classId)); } else { score = scoreMatrix[col - 1][row] - incompatibleFactor * column.getMinAlignmentScore(); } if (score > maxScore) { maxScore = score; maxScoreTax = tax; } } else { // other != tax, look at switching from tax to other final float score; if (column.getScore(otherTax) > 0 || column.getScore(classId) > 0) score = scoreMatrix[col - 1][otherRow] - switchPenalty + compatibleFactor * Math.max(column.getScore(otherTax), column.getScore(classId)); else score = scoreMatrix[col - 1][otherRow] - switchPenalty - incompatibleFactor * column.getMinAlignmentScore(); if (score > maxScore) { maxScore = score; maxScoreTax = otherTax; } } } if (verbose) System.err.printf("Traceback %d (%s) %.1f from %d (%s) %.1f%n", tax, TaxonomyData.getName2IdMap().get(tax), maxScore, maxScoreTax, TaxonomyData.getName2IdMap().get(maxScoreTax), scoreMatrix[col - 1][tax2row.get(maxScoreTax)]); scoreMatrix[col][row] = maxScore; traceBackMatrix[col][row] = maxScoreTax; } progress.incrementProgress(); } } } final List<Pair<Float, Integer>> bestScores; if (columns.size() > 0) bestScores = computeBestScores(allTaxa, tax2row, scoreMatrix, 0.1); else bestScores = new ArrayList<>(); if (verbose) { System.err.println("Best scores and taxa:"); for (var pair : bestScores) { System.err.printf("%d (%s): %.1f%n", pair.getSecond(), TaxonomyData.getName2IdMap().get(pair.getSecond()), pair.getFirst()); } } // trace back: final var segments = new ArrayList<Segment>(); if (bestScores.size() > 0) { var tax = bestScores.get(0).getSecond(); var row = tax2row.get(tax); var col = scoreMatrix.length - 1; while (col > 0) { final var currentColumn = columns.get(col); var prevCol = col - 1; while (prevCol > 0 && traceBackMatrix[prevCol][row] == tax) prevCol--; final var prevColumn = columns.get(prevCol); if (tax > 0) segments.add(new Segment(prevColumn.getPos(), currentColumn.getPos(), tax)); if (prevCol > 0) { tax = traceBackMatrix[prevCol][row]; row = tax2row.get(tax); } col = prevCol; } } // reverse: CollectionUtils.reverseInPlace(segments); //System.err.println(">" + Basic.swallowLeadingGreaterSign(readBlock.getReadName()) + ": segments: " + Basic.toString(segments, " ")); return segments; } /** * compute the columns for the DP * * @return DP data points */ private ArrayList<DPColumn> computeDPColumns(IntervalTree<IMatchBlock> intervals, TreeSet<Integer> positions) { final ArrayList<DPColumn> columns = new ArrayList<>(); DPColumn prevColumn = null; for (var pos : positions) { final var column = new DPColumn(pos); if (prevColumn != null) { for (var interval : intervals.getIntervals(pos)) { final var matchBlock = interval.getData(); final var segmentLength = pos - prevColumn.getPos() + 1; if (segmentLength >= 5) { final var score = matchBlock.getBitScore() * segmentLength / matchBlock.getLength(); final var tax = getTaxonAtRank(matchBlock.getTaxonId()); if (tax > 0) column.add(tax, score); else if (classId > 0 && TaxonomyData.isAncestor(tax, classId)) // if alignment lies on or above the target taxon, use it column.add(classId, score); } } if (column.getTaxa().size() > 0) columns.add(column); } prevColumn = column; } return columns; } /** * determine the best scores seen * * @return best scores and taxa seen */ private List<Pair<Float, Integer>> computeBestScores(Set<Integer> taxa, Map<Integer, Integer> tax2row, float[][] scoreMatrix, double topProportion) { List<Pair<Float, Integer>> list = new ArrayList<>(); final var col = scoreMatrix.length - 1; for (var tax : taxa) { list.add(new Pair<>(scoreMatrix[col][tax2row.get(tax)], tax)); } if (list.size() > 1) { list.sort((a, b) -> { if (a.getFirst() > b.getFirst()) return -1; else if (a.getFirst() < b.getFirst()) return 1; else return a.getSecond().compareTo(b.getSecond()); }); var bestScore = list.get(0).getFirst(); for (var i = 1; i < list.size(); i++) { if (list.get(i).getFirst() < topProportion * bestScore) { list = list.subList(0, i); // remove the remaining items break; } } } return list; } public int getRank() { return rank; } public void setRank(int rank) { if (rank != this.rank) { tax2taxAtRank.clear(); this.rank = rank; } } public int getClassId() { return classId; } public void setClassId(int classId) { this.classId = classId; } public float getSwitchPenalty() { return switchPenalty; } public void setSwitchPenalty(float switchPenalty) { if (switchPenalty < 0) throw new IllegalArgumentException("negative switchPenalty"); this.switchPenalty = switchPenalty; } public float getCompatibleFactor() { return compatibleFactor; } public void setCompatibleFactor(float compatibleFactor) { if (compatibleFactor < 0) throw new IllegalArgumentException("negative compatibleFactor"); this.compatibleFactor = compatibleFactor; } public float getIncompatibleFactor() { return incompatibleFactor; } public void setIncompatibleFactor(float incompatibleFactor) { if (incompatibleFactor < 0) throw new IllegalArgumentException("negative incompatibleFactor"); this.incompatibleFactor = incompatibleFactor; } /** * gets the ancestor tax id at the set rank or 0 * * @return ancestor or 0 */ private Integer getTaxonAtRank(Integer taxonId) { if (taxonId == 0) return 0; if (rank == 0 || TaxonomyData.getTaxonomicRank(taxonId) == rank) return taxonId; if (tax2taxAtRank.containsKey(taxonId)) return tax2taxAtRank.get(taxonId); var ancestorId = taxonId; var v = TaxonomyData.getTree().getANode(ancestorId); while (v != null) { var vLevel = TaxonomyData.getTaxonomicRank(ancestorId); if (vLevel == rank) { tax2taxAtRank.put(taxonId, ancestorId); return ancestorId; } if (v.getInDegree() > 0) { v = v.getFirstInEdge().getSource(); ancestorId = (Integer) v.getInfo(); } else break; } return 0; } /** * a segment with tax id */ public record Segment(int start, int end, int tax) { public int getStart() { return start; } public int getEnd() { return end; } public int getTaxon() { return tax; } public String toString() { return String.format("%,d-%,d: %d (%s)", start, end, tax, TaxonomyData.getName2IdMap().get(tax)); } } /** * a column in the dynamic program: all alignments that are available at the given position */ private static class DPColumn { private final int pos; private final Map<Integer, Float> taxon2AlignmentScore; // todo: replace by array and rows private float minAlignmentScore = 0; DPColumn(int pos) { this.pos = pos; taxon2AlignmentScore = new TreeMap<>(); } void add(int tax, float score) { if (score <= 0) throw new RuntimeException("Score must be positive, got: " + score); // should never happen final var prev = taxon2AlignmentScore.get(tax); if (prev == null || prev < score) taxon2AlignmentScore.put(tax, score); if (minAlignmentScore == 0 || score < minAlignmentScore) minAlignmentScore = score; } Set<Integer> getTaxa() { return taxon2AlignmentScore.keySet(); } float getScore(int tax) { return taxon2AlignmentScore.getOrDefault(tax, 0f); } int getPos() { return pos; } float getMinAlignmentScore() { return minAlignmentScore; } public String toString() { final var buf = new StringBuilder(String.format("[%,d-%.1f-%d", pos, minAlignmentScore, taxon2AlignmentScore.size())); for (var tax : getTaxa()) { buf.append(String.format(" %d (%s)-%.1f", tax, TaxonomyData.getName2IdMap().get(tax), getScore(tax))); } buf.append("]"); return buf.toString(); } } }
13,152
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListAssignedCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListAssignedCommand.java
/* * ListAssignedCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.graph.NodeSet; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.CanceledException; import jloda.util.Single; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import jloda.util.progress.ProgressListener; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.Document; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.*; public class ListAssignedCommand extends CommandBase implements ICommand { public String getSyntax() { return "list assigned nodes={all|selected} [outFile=<name>];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list assigned nodes="); String what = np.getWordMatchesIgnoringCase("all selected"); final String fileName; if (np.peekMatchIgnoreCase("outFile")) { np.matchIgnoreCase("outFile="); fileName = np.getWordFileNamePunctuation(); } else fileName = null; np.matchIgnoreCase(";"); final ViewerBase viewer = (ViewerBase) getViewer(); final Document doc = viewer.getDocument(); if (doc.getMeganFile().getFileName() == null) { throw new IOException("No input file\n"); } final Classification classification = ClassificationManager.get(getViewer().getClassName(), true); final NodeSet selectedNodes = (what.equalsIgnoreCase("selected") ? viewer.getSelectedNodes() : null); final Writer w = new BufferedWriter(fileName == null ? new OutputStreamWriter(System.out) : new FileWriter(fileName)); final Single<Integer> countLines = new Single<>(); final ProgressListener progress = doc.getProgressListener(); progress.setTasks("List", "Assignments"); progress.setMaximum(viewer.getTree().getNumberOfNodes()); progress.setProgress(0); try { w.write("########## Begin of summary for file: " + doc.getMeganFile().getFileName() + "\n"); w.write("Samples: " + doc.getNumberOfSamples() + "\n"); w.write("Reads total: " + doc.getNumberOfReads() + "\n"); countLines.set(3); if (viewer.getTree().getRoot() != null) { w.write("Assigned at nodes:" + "\n"); countLines.set(countLines.get() + 1); listAssignedRec(viewer, classification, selectedNodes, viewer.getTree().getRoot(), 0, w, countLines, progress); } w.write("########## End of summary for file: " + doc.getMeganFile().getFileName() + "\n"); } finally { if (fileName != null) w.close(); else w.flush(); } if (fileName != null && countLines.get() > 0) NotificationsInSwing.showInformation(getViewer().getFrame(), "Lines written to file: " + countLines.get()); } /** * recursively print a summary * */ private void listAssignedRec(ViewerBase viewer, Classification classification, NodeSet selectedNodes, Node v, int indent, Writer outs, final Single<Integer> countLines, ProgressListener progress) throws IOException, CanceledException { progress.incrementProgress(); final int id = (Integer) v.getInfo(); if ((selectedNodes == null || selectedNodes.contains(v))) { final String name = classification.getName2IdMap().get(id); NodeData data = (viewer.getNodeData(v)); if (data.getCountSummarized() > 0) { for (int i = 0; i < indent; i++) outs.write(" "); outs.write(name + ": " + StringUtils.toString("%,.0f",data.getSummarized(),0,data.getSummarized().length, ",") + "\n"); countLines.set(countLines.get() + 1); } } if (viewer.getCollapsedIds().contains(id)) { return; } for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) { listAssignedRec(viewer, classification, selectedNodes, f.getOpposite(v), indent + 2, outs, countLines, progress); } } public void actionPerformed(ActionEvent event) { executeImmediately("show window=message;"); final ViewerBase viewer = (ViewerBase) getViewer(); if (viewer.getSelectedNodes().isEmpty()) execute("list assigned nodes=all;"); else execute("list assigned nodes=selected;"); } public boolean isApplicable() { return getDoc().getNumberOfReads() > 0 && getViewer() != null && getViewer() instanceof ViewerBase; } public String getName() { return "List Assigned..."; } public String getDescription() { return "List assigned counts for selected nodes of tree"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/History16.gif"); } public boolean isCritical() { return true; } }
6,026
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ChooseHighLightColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ChooseHighLightColorCommand.java
/* * ChooseHighLightColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import megan.main.MeganProperties; import megan.viewer.MainViewer; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class ChooseHighLightColorCommand extends CommandBase implements ICommand { public String getSyntax() { return "set comparisonHighlightColor=<number>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set comparisonHighlightColor="); Color color = new Color(np.getInt()); np.matchIgnoreCase(";"); ProgramProperties.put(MeganProperties.PVALUE_COLOR, color); NodeDrawer.pvalueColor = color; ((MainViewer) getViewer()).repaint(); } public void actionPerformed(ActionEvent event) { Color previous = ProgramProperties.get(MeganProperties.PVALUE_COLOR, Color.ORANGE); Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose comparison highlight color", previous); executeImmediately("set comparisonHighlightColor=" + color.getRGB() + ";"); } public boolean isApplicable() { return true; } public String getName() { return "Set Highlight Color..."; } public String getDescription() { return "Set the pairwise comparison highlight color"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return getDoc().getNumberOfSamples() == 2; } }
2,511
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScaleBySummarizedCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ScaleBySummarizedCommand.java
/* * ScaleBySummarizedCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; public class ScaleBySummarizedCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return (viewer != null) && (viewer.getNodeDrawer().getScaleBy() == NodeDrawer.ScaleBy.Summarized); } public void apply(NexusStreamParser np) { } public boolean isApplicable() { return true; } public boolean isCritical() { return true; } public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { if (isSelected()) execute("set scaleBy=" + NodeDrawer.ScaleBy.None + ";"); else execute("set scaleBy=" + NodeDrawer.ScaleBy.Summarized + ";"); } public String getName() { return "Scale Nodes By Summarized"; } public String getDescription() { return "Scale nodes by number of reads summarized"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Empty16.gif"); } }
2,156
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExpandHorizontalCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ExpandHorizontalCommand.java
/* * ExpandHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.ScrollPaneAdjuster; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.chart.gui.ChartViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class ExpandHorizontalCommand extends CommandBase implements ICommand { public String getSyntax() { return "expand direction={horizontal|vertical};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("expand direction="); String direction = np.getWordMatchesIgnoringCase("horizontal vertical"); np.matchIgnoreCase(";"); if (getViewer() instanceof ChartViewer) { ChartViewer chartViewer = (ChartViewer) getViewer(); Point center = chartViewer.getZoomCenter(); if (direction.equalsIgnoreCase("horizontal")) chartViewer.zoom(1.2f, 1, center); else if (direction.equalsIgnoreCase("vertical")) chartViewer.zoom(1, 1.2f, center); } else { ViewerBase viewer = (ViewerBase) getViewer(); if (direction.equals("horizontal")) { double scale = 1.2 * viewer.trans.getScaleX(); if (scale <= ViewerBase.XMAX_SCALE) { ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans); viewer.trans.composeScale(1.2, 1); spa.adjust(true, false); } } else { double scale = 2 * viewer.trans.getScaleY(); if (scale <= ViewerBase.YMAX_SCALE) { ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans); viewer.trans.composeScale(1, 1.2); spa.adjust(false, true); } } } } public void actionPerformed(ActionEvent event) { executeImmediately("expand direction=horizontal;"); } public boolean isApplicable() { return true; } public String getName() { return "Expand Horizontal"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ExpandHorizontal16.gif"); } public String getDescription() { return "Expand tree horizontally"; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
3,546
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ComputeShannonIndexCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ComputeShannonIndexCommand.java
/* * ComputeShannonIndexCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.core.Document; import megan.util.DiversityIndex; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ComputeShannonIndexCommand extends CommandBase implements ICommand { public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("compute index="); final String indexName = np.getWordMatchesIgnoringCase(DiversityIndex.SHANNON + " " + DiversityIndex.SIMPSON_RECIPROCAL); np.matchIgnoreCase(";"); String message; final Document doc = getDir().getDocument(); int numberSelectedNodes = ((ViewerBase) getViewer()).getNumberSelectedNodes(); if (indexName.equalsIgnoreCase(DiversityIndex.SHANNON)) { message = "Shannon-Weaver index for " + doc.getNumberOfSamples() + " samples based on " + numberSelectedNodes + " selected nodes:\n" + DiversityIndex.computeShannonWeaver((ViewerBase) getViewer(), doc.getProgressListener()); } else if (indexName.equalsIgnoreCase(DiversityIndex.SIMPSON_RECIPROCAL)) { message = "Simpson's reciprocal index for " + doc.getNumberOfSamples() + " samples based on " + numberSelectedNodes + " selected nodes:\n" + DiversityIndex.computeSimpsonReciprocal((ViewerBase) getViewer(), doc.getProgressListener()); } else { message = "Error: Unknown index: " + indexName; } System.err.println(message); NotificationsInSwing.showInformation(getViewer().getFrame(), message); } public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getNumberSelectedNodes() > 0 && getDir().getDocument().getNumberOfSamples() > 0; } public boolean isCritical() { return true; } public String getSyntax() { return "compute index={" + DiversityIndex.SHANNON + "|" + DiversityIndex.SIMPSON_RECIPROCAL + "};"; } public void actionPerformed(ActionEvent event) { execute("compute index=" + DiversityIndex.SHANNON + ";"); } public String getName() { return "Shannon-Weaver Index..."; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Compute the Shannon-Weaver diversity index"; } }
3,320
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetScaleByLogCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetScaleByLogCommand.java
/* * SetScaleByLogCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.util.ScalingType; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class SetScaleByLogCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer.getNodeDrawer().getScalingType() == ScalingType.LOG; } public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("set scale=log;"); } public boolean isApplicable() { return getViewer() instanceof ViewerBase; } public String getName() { return "Log Scale"; } public String getDescription() { return "Show values on log scale"; } public ImageIcon getIcon() { return ResourceManager.getIcon("LogScale16.gif"); } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,180
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetAPropertyCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetAPropertyCommand.java
/* * SetAPropertyCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class SetAPropertyCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set A Property..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set a property"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("setProp"); String label = np.getWordRespectCase(); np.matchIgnoreCase("="); String value = np.getWordRespectCase(); if (NumberUtils.isBoolean(value)) { ProgramProperties.put(label, Boolean.parseBoolean(value)); } else if (NumberUtils.isInteger(value)) { ProgramProperties.put(label, Integer.parseInt(value)); } else if (NumberUtils.isFloat(value)) { ProgramProperties.put(label, Float.parseFloat(value)); } else ProgramProperties.put(label, value); np.matchIgnoreCase(";"); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "setProp <name>=<value>;"; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,459
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ImportBlastCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ImportBlastCommand.java
/* * ImportBlastCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.*; import megan.inspector.InspectorWindow; import megan.main.MeganProperties; import megan.parsers.blast.BlastFileFormat; import megan.parsers.blast.BlastModeUtils; import megan.rma6.RMA6FromBlastCreator; import megan.util.ReadMagnitudeParser; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; /** * import blast command * Daniel Huson, 10.2010 */ public class ImportBlastCommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ public String getSyntax() { return "import blastFile=<name> [,<name>...] [fastaFile=<name> [,<name>...]] meganFile=<name> [useCompression={true|false}]\n" + "\tformat={" + StringUtils.toString(BlastFileFormat.valuesExceptUnknown(), "|") + "}\n" + "\tmode={" + StringUtils.toString(BlastModeUtils.valuesExceptUnknown(), "|") + "} [maxMatches=<num>] [minScore=<num>] [maxExpected=<num>] [minPercentIdentity=<num>]\n" + "\t[topPercent=<num>] [minSupportPercent=<num>] [minSupport=<num>] [weightedLCA={false|true}] [lcaCoveragePercent=<num>] [minPercentReadToCover=<num>] [minPercentReferenceToCover=<num>] [minComplexity=<num>] [useIdentityFilter={false|true}]\n" + "\t[readAssignmentMode={" + StringUtils.toString(Document.ReadAssignmentMode.values(), "|") + "}] [fNames={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "...} [longReads={false|true}] [paired={false|true} [pairSuffixLength={number}]]\n" + "\t[contaminantsFile=<filename>] [description=<text>];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { final Director dir = getDir(); final MainViewer viewer = dir.getMainViewer(); final Document doc = dir.getDocument(); if (!ProgramProperties.isUseGUI() || doc.neverOpenedReads) { doc.neverOpenedReads = false; np.matchIgnoreCase("import blastFile="); LinkedList<String> blastFiles = new LinkedList<>(); while (true) { boolean comma = false; String name = np.getAbsoluteFileName(); if (name.endsWith(",")) { name = name.substring(0, name.length() - 1); comma = true; } blastFiles.add(name); if (!comma && np.peekMatchIgnoreCase(",")) { np.matchIgnoreCase(","); comma = true; } if (!comma && np.peekMatchAnyTokenIgnoreCase("fastaFile readFile meganFile ;")) break; } LinkedList<String> readsFiles = new LinkedList<>(); if (np.peekMatchAnyTokenIgnoreCase("fastaFile readFile")) { np.matchAnyTokenIgnoreCase("fastaFile readFile"); np.matchIgnoreCase("="); while (true) { boolean comma = false; String name = np.getAbsoluteFileName(); if (name.endsWith(",")) { name = name.substring(0, name.length() - 1); comma = true; } readsFiles.add(name); if (!comma && np.peekMatchIgnoreCase(",")) { np.matchIgnoreCase(","); comma = true; } if (!comma && np.peekMatchAnyTokenIgnoreCase("meganFile ;")) break; } } np.matchIgnoreCase("meganFile="); final String meganFileName = np.getAbsoluteFileName(); boolean useCompression = true; if (np.peekMatchIgnoreCase("useCompression")) { np.matchIgnoreCase("useCompression="); useCompression = np.getBoolean(); } np.matchAnyTokenIgnoreCase("format blastFormat"); np.matchIgnoreCase("="); final BlastFileFormat format = BlastFileFormat.valueOfIgnoreCase(np.getWordMatchesIgnoringCase(StringUtils.toString(BlastFileFormat.valuesExceptUnknown(), " "))); np.matchAnyTokenIgnoreCase("mode blastMode"); np.matchIgnoreCase("="); doc.setBlastMode(BlastModeUtils.valueOfIgnoringCase(np.getWordMatchesIgnoringCase(StringUtils.toString(BlastModeUtils.valuesExceptUnknown(), " ")))); int maxMatchesPerRead = 25; if (np.peekMatchIgnoreCase("maxMatches")) { np.matchIgnoreCase("maxMatches="); maxMatchesPerRead = np.getInt(0, Integer.MAX_VALUE); } if (np.peekMatchIgnoreCase("minScore")) { np.matchIgnoreCase("minScore="); doc.setMinScore((float) np.getDouble(0, Float.MAX_VALUE)); } if (np.peekMatchIgnoreCase("maxExpected")) { np.matchIgnoreCase("maxExpected="); doc.setMaxExpected((float) np.getDouble(0, Float.MAX_VALUE)); } if (np.peekMatchIgnoreCase("minPercentIdentity")) { np.matchIgnoreCase("minPercentIdentity="); doc.setMinPercentIdentity((float) np.getDouble(0, Float.MAX_VALUE)); } if (np.peekMatchIgnoreCase("topPercent")) { np.matchIgnoreCase("topPercent="); doc.setTopPercent((float) np.getDouble(0, 100)); } if (np.peekMatchIgnoreCase("minSupportPercent")) { np.matchIgnoreCase("minSupportPercent="); doc.setMinSupportPercent((float) np.getDouble(0, 100)); } else doc.setMinSupportPercent(0); if (np.peekMatchIgnoreCase("minSupport")) { np.matchIgnoreCase("minSupport="); doc.setMinSupport(np.getInt(1, Integer.MAX_VALUE)); } else doc.setMinScore(1); if (np.peekMatchIgnoreCase("weightedLCA")) { np.matchIgnoreCase("weightedLCA="); getDoc().setLcaAlgorithm(Document.LCAAlgorithm.weighted); } else if (np.peekMatchIgnoreCase("lcaAlgorithm")) { np.matchIgnoreCase("lcaAlgorithm="); getDoc().setLcaAlgorithm(Document.LCAAlgorithm.valueOfIgnoreCase(np.getWordRespectCase())); } if (np.peekMatchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent")) { np.matchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent"); np.matchIgnoreCase("="); getDoc().setLcaCoveragePercent((float) np.getDouble(50, 100)); ProgramProperties.put("lcaCoveragePercent", doc.getLcaCoveragePercent()); } if (np.peekMatchIgnoreCase("minPercentReadToCover")) { np.matchIgnoreCase("minPercentReadToCover="); getDoc().setMinPercentReadToCover((float) np.getDouble(0, 100)); ProgramProperties.put("minPercentReadToCover", doc.getMinPercentReadToCover()); } if (np.peekMatchIgnoreCase("minPercentReferenceToCover")) { np.matchIgnoreCase("minPercentReferenceToCover="); getDoc().setMinPercentReferenceToCover((float) np.getDouble(0, 100)); ProgramProperties.put("minPercentReferenceToCover", doc.getMinPercentReferenceToCover()); } if (np.peekMatchIgnoreCase("minComplexity")) { np.matchIgnoreCase("minComplexity="); doc.setMinComplexity((float) np.getDouble(-1.0, 1.0)); } if (np.peekMatchIgnoreCase("minReadLength")) { np.matchIgnoreCase("minReadLength="); doc.setMinReadLength(np.getInt(0,Integer.MAX_VALUE)); } if (np.peekMatchIgnoreCase("useIdentityFilter")) { np.matchIgnoreCase("useIdentityFilter="); getDoc().setUseIdentityFilter(np.getBoolean()); } if (np.peekMatchIgnoreCase("readAssignmentMode")) { np.matchIgnoreCase("readAssignmentMode="); getDoc().setReadAssignmentMode(Document.ReadAssignmentMode.valueOfIgnoreCase(np.getWordMatchesIgnoringCase(StringUtils.toString(Document.ReadAssignmentMode.values(), " ")))); } Collection<String> known = ClassificationManager.getAllSupportedClassifications(); if (np.peekMatchIgnoreCase("fNames=")) { doc.getActiveViewers().clear(); np.matchIgnoreCase("fNames="); while (!np.peekMatchIgnoreCase(";")) { String token = np.getWordRespectCase(); if (!known.contains(token)) { np.pushBack(); break; } doc.getActiveViewers().add(token); } doc.getActiveViewers().add(Classification.Taxonomy); } if (np.peekMatchIgnoreCase("longReads")) { np.matchIgnoreCase("longReads="); doc.setLongReads(np.getBoolean()); } if (np.peekMatchIgnoreCase("paired")) { np.matchIgnoreCase("paired="); boolean paired = np.getBoolean(); doc.setPairedReads(paired); if (paired) { np.matchIgnoreCase("pairSuffixLength="); doc.setPairedReadSuffixLength(np.getInt(0, 10)); System.err.println("Assuming paired-reads distinguishing suffix has length: " + doc.getPairedReadSuffixLength()); } } if (np.peekMatchIgnoreCase("contaminantsFile")) { np.matchIgnoreCase("contaminantsFile="); final String contaminantsFile = np.getWordFileNamePunctuation().trim(); ContaminantManager contaminantManager = new ContaminantManager(); contaminantManager.read(contaminantsFile); doc.getDataTable().setContaminants(contaminantManager.getTaxonIdsString()); doc.setUseContaminantFilter(true); } String description; if (np.peekMatchIgnoreCase("description")) { np.matchIgnoreCase("description="); description = np.getWordFileNamePunctuation().trim(); } else description = null; np.matchIgnoreCase(";"); if (meganFileName == null) throw new IOException("Must specify MEGAN file"); if (format == null) throw new IOException("Failed to determine file format"); File meganFile = new File(meganFileName); if (meganFile.exists()) { if (meganFile.delete()) System.err.println("Deleting existing file: " + meganFile.getPath()); } final String[] blastFileNames = blastFiles.toArray(new String[0]); final String[] readFileNames = readsFiles.toArray(new String[0]); ReadMagnitudeParser.setEnabled(doc.getReadAssignmentMode() == Document.ReadAssignmentMode.readMagnitude); doc.getMeganFile().setFile(meganFileName, MeganFile.Type.RMA6_FILE); RMA6FromBlastCreator rma6Creator = new RMA6FromBlastCreator(ProgramProperties.getProgramName(), format, doc.getBlastMode(), blastFileNames, readFileNames, doc.getMeganFile().getFileName(), useCompression, doc, maxMatchesPerRead); rma6Creator.parseFiles(doc.getProgressListener()); doc.loadMeganFile(); if (description != null && description.length() > 0) { description = description.replaceAll("^ +| +$|( )+", "$1"); // replace all white spaces by a single space final String sampleName = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(doc.getMeganFile().getFileName()), ""); doc.getSampleAttributeTable().put(sampleName, SampleAttributeTable.DescriptionAttribute, description); } MeganProperties.addRecentFile(meganFileName); if (doc.getNumberOfReads() == 0) NotificationsInSwing.showWarning(getViewer().getFrame(), "No reads found"); if (dir.getViewerByClass(InspectorWindow.class) != null) ((InspectorWindow) dir.getViewerByClass(InspectorWindow.class)).clear(); viewer.setCollapsedIds(TaxonomyData.getTree().getAllAtLevel(3)); viewer.setDoReset(true); viewer.setDoReInduce(true); ProgramProperties.put(MeganProperties.DEFAULT_PROPERTIES, doc.getParameterString()); } else // launch new window { final Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.execute(np.getQuotedTokensRespectCase(null, ";") + ";", newDir.getMainViewer().getCommandManager()); } } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { } /** * get the name to be used as a menu label * * @return name */ public String getName() { return null; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Import BLAST (or RDP or Silva or SAM) and reads files to create a new MEGAN file"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
15,879
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelNodesByNamesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/LabelNodesByNamesCommand.java
/* * LabelNodesByNamesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class LabelNodesByNamesCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer != null && viewer.isNodeLabelNames(); } public String getSyntax() { return "nodeLabels [names=<bool>] [ids=<bool>] [assigned=<bool>] [summarized=<bool>];"; } public void apply(NexusStreamParser np) throws Exception { ViewerBase viewer = (ViewerBase) getViewer(); np.matchIgnoreCase("nodeLabels"); if (np.peekMatchIgnoreCase("names")) { np.matchIgnoreCase("names="); viewer.setNodeLabelNames(np.getBoolean()); } if (np.peekMatchIgnoreCase("ids")) { np.matchIgnoreCase("ids="); viewer.setNodeLabelIds(np.getBoolean()); } if (np.peekMatchIgnoreCase("assigned")) { np.matchIgnoreCase("assigned="); viewer.setNodeLabelAssigned(np.getBoolean()); } if (np.peekMatchIgnoreCase("summarized")) { np.matchIgnoreCase("summarized="); viewer.setNodeLabelSummarized(np.getBoolean()); } np.matchRespectCase(";"); viewer.setupNodeLabels(false); viewer.repaint(); } public void actionPerformed(ActionEvent event) { execute("nodeLabels names=" + (!isSelected()) + ";"); } public String getName() { return "Show Names"; } public String getDescription() { return "Determine what to label nodes with"; } public KeyStroke getAcceleratorKey() { return null; } public ImageIcon getIcon() { return null; } public boolean isApplicable() { return true; } public boolean isCritical() { return true; } }
2,890
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SaveCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SaveCommand.java
/* * SaveCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.classification.data.SyncDataTableAndClassificationViewer; import megan.core.Director; import megan.core.Document; import megan.core.MeganFile; import megan.main.MeganProperties; import megan.samplesviewer.SamplesViewer; import megan.util.MeganFileFilter; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.SyncDataTableAndTaxonomy; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Objects; public class SaveCommand extends CommandBase implements ICommand { public String getSyntax() { return "save file=<filename> [summary={true|false}];"; } public void apply(NexusStreamParser np) throws Exception { MainViewer viewer = getDir().getMainViewer(); Director dir = getDir(); Document doc = dir.getDocument(); String fileName = null; try { np.matchIgnoreCase("save file="); fileName = np.getAbsoluteFileName(); boolean summary = true; if (np.peekMatchIgnoreCase("summary")) { np.matchIgnoreCase("summary="); summary = np.getBoolean(); } np.matchIgnoreCase(";"); File file = new File(fileName); doc.getProgressListener().setTasks("Saving MEGAN file", file.getName()); if (summary) { final SamplesViewer sampleViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class); if (sampleViewer != null) { sampleViewer.getSamplesTableView().syncFromViewToDocument(); } if (viewer != null) SyncDataTableAndTaxonomy.syncFormattingFromViewer2Summary(viewer, doc.getDataTable()); for (String cName : ClassificationManager.getAllSupportedClassifications()) { if (dir.getViewerByClassName(ClassificationViewer.getClassName(cName)) != null && dir.getViewerByClassName(ClassificationViewer.getClassName(cName)) instanceof ClassificationViewer) { ClassificationViewer classificationViewer = (ClassificationViewer) dir.getViewerByClassName(ClassificationViewer.getClassName(cName)); SyncDataTableAndClassificationViewer.syncFormattingFromViewer2Summary(classificationViewer, doc.getDataTable()); } } try (FileWriter writer = new FileWriter(fileName)) { if (!doc.getChartColorManager().isUsingProgramColors()) { doc.getDataTable().setColorTable(doc.getChartColorManager().getColorTableName(), doc.getChartColorManager().isColorByPosition(), doc.getChartColorManager().getHeatMapTable().getName()); doc.getDataTable().setColorEdits(doc.getChartColorManager().getColorEdits()); } if(doc.getMeganFile().getMergedFiles().size()>0) doc.getDataTable().setMergedFiles(doc.getSampleNames().get(0),doc.getMeganFile().getMergedFiles()); doc.getDataTable().setParameters(doc.getParameterString()); doc.getDataTable().write(writer); doc.getSampleAttributeTable().write(writer, false, true); } if (doc.getMeganFile().getFileType() == MeganFile.Type.UNKNOWN_FILE) doc.getMeganFile().setFileType(MeganFile.Type.MEGAN_SUMMARY_FILE); if (doc.getMeganFile().isMeganSummaryFile()) { dir.setDirty(false); doc.getMeganFile().setFileName(file.getPath()); } } else { throw new IOException("RMA and DAA files can only be saved as summary files"); } System.err.println("done"); if (FileUtils.getFileSuffix(file.getPath()).equalsIgnoreCase(".megan")) MeganProperties.addRecentFile(file); } catch (IOException ex) { NotificationsInSwing.showError(Objects.requireNonNull(viewer).getFrame(), "Save file '" + fileName + "'failed: " + ex, Integer.MAX_VALUE); throw ex; } } public void actionPerformed(ActionEvent event) { Director dir = getDir(); final boolean inAskToSave = event.getActionCommand().equals("askToSave"); String fileName = dir.getDocument().getMeganFile().getFileName(); File lastOpenFile = null; if (fileName != null) lastOpenFile = new File(fileName); if (lastOpenFile == null) { String name = dir.getTitle(); if (!name.endsWith(".meg") && !name.endsWith(".megan")) name += ".megan"; if (ProgramProperties.getFile(MeganProperties.SAVEFILE) != null) lastOpenFile = new File(ProgramProperties.getFile(MeganProperties.SAVEFILE), name); else lastOpenFile = new File(name); } File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new MeganFileFilter(), new MeganFileFilter(), event, "Save MEGAN file", ".megan"); if (file != null) { // if file name has no suffix, add one, unless file with suffix already exists. if (file.getPath().equals(FileUtils.replaceFileSuffix(file.getPath(), ""))) { final File other = FileUtils.replaceFileSuffix(file, ".megan"); if (!other.exists()) file = other; } ProgramProperties.put(MeganProperties.SAVEFILE, file); String cmd = "save file='" + file.getPath() + "' summary=true;"; if (inAskToSave) executeImmediately(cmd); // we are already in a thread, use immediate execution else execute(cmd); } } // if in ask to save, modify event source to tell calling method can see that user has canceled void replyUserHasCanceledInAskToSave(ActionEvent event) { ((Boolean[]) event.getSource())[0] = true; } public boolean isApplicable() { return getDoc().getNumberOfReads() > 0 && getDoc().getMeganFile().isMeganSummaryFile(); } final public static String NAME = "Save As..."; public String getName() { return NAME; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/SaveAs16.gif"); } public String getDescription() { return "Save current data set"; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } public boolean isCritical() { return true; } }
7,901
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetRoundedPhylogramCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetRoundedPhylogramCommand.java
/* * SetRoundedPhylogramCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw as rounded phylogram * Daniel Huson, 5.2015 */ public class SetRoundedPhylogramCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return ((ViewerBase) getViewer()).getDrawerType().equals(ViewerBase.DiagramType.RoundedPhylogram); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set drawer=" + ViewerBase.DiagramType.RoundedPhylogram + ";"); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Rounded Phylogram"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Draw tree as rounded phylogram with all leaves positioned as left as possible"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("RoundedPhylogram16.gif"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } }
2,911
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetScaleLinearCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetScaleLinearCommand.java
/* * SetScaleLinearCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.util.ScalingType; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class SetScaleLinearCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer.getNodeDrawer().getScalingType() == ScalingType.LINEAR; } public String getSyntax() { return "set scale={linear|percent|log};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set scale="); String scale = np.getWordMatchesIgnoringCase("linear sqrt log"); np.matchIgnoreCase(";"); ViewerBase viewer = (ViewerBase) getViewer(); if (scale.equalsIgnoreCase(ScalingType.LINEAR.toString())) viewer.getNodeDrawer().setScalingType(ScalingType.LINEAR); else if (scale.equalsIgnoreCase(ScalingType.LOG.toString())) viewer.getNodeDrawer().setScalingType(ScalingType.LOG); else if (scale.equalsIgnoreCase(ScalingType.SQRT.toString())) viewer.getNodeDrawer().setScalingType(ScalingType.SQRT); viewer.repaint(); } public void actionPerformed(ActionEvent event) { execute("set scale=linear;"); } public boolean isApplicable() { return getViewer() instanceof ViewerBase; } public String getName() { return "Linear Scale"; } public String getDescription() { return "Show values on a linear scale"; } public ImageIcon getIcon() { return ResourceManager.getIcon("LinScale16.gif"); } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,884
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetWindowSizeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetWindowSizeCommand.java
/* * SetWindowSizeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.StringTokenizer; public class SetWindowSizeCommand extends jloda.swing.commands.CommandBase implements ICommand { public String getSyntax() { return "set windowSize=<width> x <height>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set windowSize="); int width = np.getInt(1, Integer.MAX_VALUE); np.matchIgnoreCase("x"); int height = np.getInt(1, Integer.MAX_VALUE); np.matchIgnoreCase(";"); getViewer().getFrame().setSize(width, height); } public void actionPerformed(ActionEvent event) { IDirectableViewer viewer = getViewer(); String original = viewer.getFrame().getWidth() + " x " + viewer.getFrame().getHeight(); String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set window size (width x height):", original); if (result != null && !result.equals(original)) { int height = 0; int width = 0; StringTokenizer st = new StringTokenizer(result, "x "); try { if (st.hasMoreTokens()) width = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) height = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) throw new NumberFormatException("Unexpected characters at end of string"); execute("set windowSize=" + width + " x " + height + ";"); } catch (NumberFormatException e) { NotificationsInSwing.showError("Window Size: Invalid entry: " + e.getMessage()); } } } public boolean isApplicable() { return true; } public String getName() { return "Set Window Size..."; } public String getDescription() { return "Set the window size"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } public boolean isCritical() { return false; } public KeyStroke getAcceleratorKey() { return null; } }
3,253
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListTaxonNamesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListTaxonNamesCommand.java
/* * ListTaxonNamesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.ArrayList; /** * list taxon names * Daniel Huson, 11.2017 */ public class ListTaxonNamesCommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "list taxa=<taxon-id ...> [title=<string>];"; } /** * parses and applies the command */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list taxa="); final ArrayList<Integer> taxonIds = new ArrayList<>(); String title = null; while (!np.peekMatchIgnoreCase(";")) { if (np.peekMatchIgnoreCase("title")) { np.matchIgnoreCase("title="); title = np.getWordFileNamePunctuation(); break; } else { taxonIds.add(np.getInt(1, Integer.MAX_VALUE)); } } np.matchIgnoreCase(";"); if (title != null) System.out.println(title + "(" + taxonIds.size() + "):"); for (Integer taxId : taxonIds) { System.out.println("[" + taxId + "] " + TaxonomyData.getName2IdMap().get(taxId)); } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { } /** * /** * get the name to be used as a menu label * * @return name */ public String getName() { return null; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "File provides list of contaminant taxa (ids or names)"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,487
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ImportMetaDataCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ImportMetaDataCommand.java
/* * ImportMetaDataCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.util.TextFileFilter; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileReader; public class ImportMetaDataCommand extends CommandBase implements ICommand { public String getSyntax() { return "import metaData=<file> [clearExisting={true|false}];"; } public void apply(NexusStreamParser np) throws Exception { final Director dir = getDir(); final Document doc = dir.getDocument(); final SamplesViewer samplesViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class); np.matchIgnoreCase("import metaData="); String fileName = np.getAbsoluteFileName(); final boolean clearExisting; if (np.peekMatchIgnoreCase("clearExisting")) { np.matchIgnoreCase("clearExisting="); clearExisting = np.getBoolean(); } else clearExisting = true; np.matchIgnoreCase(";"); if (clearExisting) { System.err.println("Cleared existing metadata"); if (samplesViewer != null) { samplesViewer.getSamplesTableView().clear(); } doc.getSampleAttributeTable().clear(); } else { System.err.println("Overwriting metadata"); if (samplesViewer != null) samplesViewer.getSamplesTableView().syncFromViewToDocument(); } final int oldNumberOfSamples = doc.getNumberOfSamples(); final int oldNumberOfAttributes = doc.getSampleAttributeTable().getNumberOfAttributes(); doc.getSampleAttributeTable().read(new FileReader(fileName), doc.getSampleNames(), false); if (doc.getSampleAttributeTable().getSampleOrder().size() != oldNumberOfSamples) { doc.getSampleAttributeTable().setSampleOrder(doc.getSampleNames()); } if (!doc.getSampleAttributeTable().getSampleOrder().equals(doc.getSampleNames())) { doc.reorderSamples(doc.getSampleAttributeTable().getSampleOrder()); } doc.setDirty(true); if (samplesViewer != null) { samplesViewer.getSamplesTableView().syncFromDocumentToView(); } NotificationsInSwing.showInformation(getViewer().getFrame(), "Number of attributes imported: " + (doc.getSampleAttributeTable().getNumberOfAttributes() - oldNumberOfAttributes)); } public void actionPerformed(ActionEvent event) { final File lastOpenFile = ProgramProperties.getFile("MetaDataFilePath"); final File file = ChooseFileDialog.chooseFileToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter(".csv"), new TextFileFilter(".csv"), event, "Open metadata mapping file"); if (file != null && file.length() > 0) { int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), "Clear existing metadata?", "Clear existing metadata?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()); if (result == JOptionPane.CANCEL_OPTION) return; execute("import metadata='" + file.getPath() + "' clearExisting=" + (result == JOptionPane.YES_OPTION) + ";show window=samplesViewer;"); ProgramProperties.put("MetaDataFilePath", file.getPath()); } } public boolean isApplicable() { Director dir = getDir(); Document doc = dir.getDocument(); return doc.getNumberOfSamples() > 0; } public String getName() { return "Metadata..."; } public String getAltName() { return "Import Metadata..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } public String getDescription() { return "Import a metadata mapping file (as defined in http://qiime.org/documentation/file_formats.html)"; } public boolean isCritical() { return true; } }
5,163
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListAssignmentsToLevelsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListAssignmentsToLevelsCommand.java
/* * ListAssignmentsToLevelsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.phylo.PhyloTree; import jloda.swing.commands.ICommand; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.classification.IdMapper; import megan.viewer.MainViewer; import megan.viewer.TaxonomicLevels; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * list assignments to different levels * Daniel Huson, 7.2010 */ public class ListAssignmentsToLevelsCommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "list assignmentsToLevels [outFile=<name>];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list assignmentsToLevels"); final String fileName; if (np.peekMatchIgnoreCase("outFile")) { np.matchIgnoreCase("outFile="); fileName = np.getWordFileNamePunctuation(); } else fileName = null; np.matchIgnoreCase(";"); // use -3 for leaves, -2 and -1 for no hits and unassigned final SortedMap<Integer, Float> level2count = new TreeMap<>(); level2count.put(-3, 0f); level2count.put(-2, 0f); level2count.put(-1, 0f); final SortedMap<String, Float> rank2count = new TreeMap<>(); final PhyloTree tree = getDir().getMainViewer().getTree(); listAssignmentsRec(tree, tree.getRoot(), 0, level2count, rank2count); final Writer w = new BufferedWriter(fileName == null ? new OutputStreamWriter(System.out) : new FileWriter(fileName)); int count = 0; try { w.write("########## Begin of level-to-assignment listing for file: " + getDir().getDocument().getMeganFile().getName() + "\n"); w.write("To leaves: " + level2count.get(-3) + "\n"); w.write("Unassigned: " + level2count.get(-2) + "\n"); w.write("No hits: " + level2count.get(-1) + "\n"); w.write("Assignments to levels (distance from root):\n"); count += 5; for (int level : level2count.keySet()) { if (level >= 0) { w.write(level + "\t" + level2count.get(level) + "\n"); count++; } } w.write("Assignments to taxonomic ranks (where known):\n"); count++; for (String rank : TaxonomicLevels.getAllNames()) { if (rank2count.get(rank) != null) { w.write(rank + "\t" + rank2count.get(rank) + "\n"); count++; } } w.write("########## End of level-to-assignment listing\n"); count++; } finally { if (fileName != null) w.close(); else w.flush(); } if (fileName != null && count > 0) NotificationsInSwing.showInformation(getViewer().getFrame(), "Lines written to file: " + count); } /** * recursively collects the numbers * */ private void listAssignmentsRec(PhyloTree tree, Node v, int level, SortedMap<Integer, Float> level2count, Map<String, Float> rank2count) { int taxonId = (Integer) (tree.getInfo(v)); if (taxonId == IdMapper.UNASSIGNED_ID || taxonId == IdMapper.NOHITS_ID || taxonId == IdMapper.LOW_COMPLEXITY_ID) { level2count.put(taxonId, ((NodeData) v.getData()).getCountAssigned()); } else // a true node in the taxonomy { final Float count = level2count.get(level); level2count.merge(level, ((NodeData) v.getData()).getCountAssigned(), Float::sum); final int taxLevel = TaxonomyData.getTaxonomicRank(taxonId); if (taxLevel != 0) { String rank = TaxonomicLevels.getName(taxLevel); if (rank != null) { rank2count.merge(rank, ((NodeData) v.getData()).getCountAssigned(), Float::sum); } } if (v.getOutDegree() == 0) // is leaf { level = -3; if (count == null) level2count.put(level, ((NodeData) v.getData()).getCountAssigned()); else level2count.put(level, count + ((NodeData) v.getData()).getCountAssigned()); } else { for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { listAssignmentsRec(tree, e.getTarget(), level + 1, level2count, rank2count); } } } } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "List Assignments to Levels"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "List the number of reads assigned to each level of the taxonomy"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof MainViewer && getDir().getDocument().getNumberOfSamples() > 0; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately("show window=message;"); execute("list assignmentsToLevels;"); } }
7,347
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CommandBase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/CommandBase.java
/* * CommandBase.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandManager; import megan.core.Director; import megan.core.Document; import javax.swing.*; /** * base class * Daniel Huson, 6.2010 */ public abstract class CommandBase extends jloda.swing.commands.CommandBase { public Director getDir() { return (Director) super.getDir(); } protected Document getDoc() { return getDir().getDocument(); } public KeyStroke getAcceleratorKey() { return null; } public CommandBase(){} public CommandBase(CommandManager commandManager) { super(commandManager); } }
1,433
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ContractHorizontalCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ContractHorizontalCommand.java
/* * ContractHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.graphview.ScrollPaneAdjuster; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.chart.gui.ChartViewer; import megan.clusteranalysis.ClusterViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ContractHorizontalCommand extends CommandBase implements ICommand { public String getSyntax() { return "contract direction={horizontal|vertical};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("contract direction="); String direction = np.getWordMatchesIgnoringCase("horizontal vertical"); np.matchIgnoreCase(";"); if (getViewer() instanceof ChartViewer) { ChartViewer chartViewer = (ChartViewer) getViewer(); if (direction.equalsIgnoreCase("horizontal")) chartViewer.zoom(1f / 1.2f, 1, chartViewer.getZoomCenter()); else if (direction.equalsIgnoreCase("vertical")) chartViewer.zoom(1, 1f / 1.2f, chartViewer.getZoomCenter()); } else { GraphView viewer; if (getViewer() instanceof GraphView) viewer = (GraphView) getViewer(); else if (getViewer() instanceof ClusterViewer) viewer = ((ClusterViewer) getViewer()).getGraphView(); else return; if (direction.equals("horizontal")) { double scale = 1.2 * viewer.trans.getScaleX(); if (scale >= ViewerBase.XMIN_SCALE) { ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans); viewer.trans.composeScale(1 / 1.2, 1); spa.adjust(true, false); } } else { double scale = 1.2 * viewer.trans.getScaleY(); if (scale >= ViewerBase.YMIN_SCALE) { ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans); viewer.trans.composeScale(1, 1 / 1.2); spa.adjust(false, true); } } } } public void actionPerformed(ActionEvent event) { executeImmediately("contract direction=horizontal;"); } public boolean isApplicable() { return true; } public String getName() { return "Contract Horizontal"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ContractHorizontal16.gif"); } public String getDescription() { return "Contract view horizontally"; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
3,878
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractSamplesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ExtractSamplesCommand.java
/* * ExtractSamplesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.core.MeganFile; import megan.main.MeganProperties; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; /** * * extract samples command * * Daniel Huson, 6.2015 */ public class ExtractSamplesCommand extends CommandBase implements ICommand { public String getSyntax() { return "extract samples=<name1 name2 ...> [toFile=<name>];"; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("extract"); final List<String> toExtract = new ArrayList<>(); np.matchIgnoreCase("samples="); while (!np.peekMatchIgnoreCase(";") && !np.peekMatchIgnoreCase("file=")) { String name = np.getWordRespectCase(); toExtract.add(name); } String fileName=null; if(np.peekMatchIgnoreCase("file")) { np.matchIgnoreCase("file="); fileName=np.getWordFileNamePunctuation(); } np.matchIgnoreCase(";"); if(fileName==null) { final String sourceFileName = ((Director) getDir()).getDocument().getMeganFile().getFileName(); if (toExtract.size() == 1) fileName = FileUtils.getFileWithNewUniqueName(FileUtils.replaceFileSuffix(sourceFileName, "-" + StringUtils.toCleanName(toExtract.get(0)) + ".megan")).toString(); else fileName = FileUtils.getFileWithNewUniqueName(FileUtils.replaceFileSuffix(sourceFileName, "-extract.megan")).toString(); } final Director newDir = Director.newProject(); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); final Document newDocument = newDir.getDocument(); if (toExtract.size() > 0) { newDir.notifyLockInput(); try { newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE); newDocument.extractSamples(toExtract, ((Director) getDir()).getDocument()); newDocument.setNumberReads(newDocument.getDataTable().getTotalReads()); newDir.getMainViewer().getFrame().setVisible(true); System.err.println("Number of reads: " + newDocument.getNumberOfReads()); newDocument.processReadHits(); newDocument.setTopPercent(100); newDocument.setMinScore(0); newDocument.setMaxExpected(10000); newDocument.setMinSupport(1); newDocument.setDirty(true); newDocument.getActiveViewers().addAll(newDocument.getDataTable().getClassification2Class2Counts().keySet()); if (newDocument.getNumberOfSamples() > 1) { newDir.getMainViewer().getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart); } NotificationsInSwing.showInformation(String.format("Extracted %,d reads to file '%s'", +newDocument.getNumberOfReads(), fileName)); } finally { newDir.notifyUnlockInput(); } newDir.execute("update reprocess=true reInduce=true;", newDir.getMainViewer().getCommandManager()); } } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return true; } public String getName() { return "Extract Samples..."; } public String getDescription() { return "Extract samples to a new document"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
5,034
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ContractVerticalCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ContractVerticalCommand.java
/* * ContractVerticalCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; public class ContractVerticalCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("contract direction=vertical;"); } public boolean isApplicable() { return true; } public String getName() { return "Contract Vertical"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ContractVertical16.gif"); } public String getDescription() { return "Contract view vertically"; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
1,949
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
setSearchURLCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/setSearchURLCommand.java
/* * setSearchURLCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; public class setSearchURLCommand extends CommandBase implements ICommand { public String getSyntax() { return "set searchURL={<URL>|default};"; } public void apply(NexusStreamParser np) throws Exception { // todo: fix so that number of reads can also be set for megan summary file np.matchIgnoreCase("set searchURL="); final String url = np.getWordFileNamePunctuation(); np.matchRespectCase(";"); if (url.equalsIgnoreCase("default")) ProgramProperties.put(ProgramProperties.SEARCH_URL, ProgramProperties.defaultSearchURL); else if (url.contains("%s")) ProgramProperties.put("SearchURL", url); else System.err.println("Set URL failed: must contain %s as placeholder for query"); } public void actionPerformed(ActionEvent event) { String searchURL = ProgramProperties.get(ProgramProperties.SEARCH_URL, ProgramProperties.defaultSearchURL); searchURL = JOptionPane.showInputDialog(getViewer().getFrame(), "Set search URL (use %s for search term):", searchURL); if (searchURL != null) { if (searchURL.contains("%s") || searchURL.equalsIgnoreCase("default")) execute("set searchURL='" + searchURL + "';"); } else NotificationsInSwing.showError(getViewer().getFrame(), "Search URL must contain %s as placeholder for query"); } public boolean isApplicable() { return true; } public String getName() { return "Set Search URL..."; } public String getDescription() { return "Set the URL used for searching the web"; } public KeyStroke getAcceleratorKey() { return null; } public boolean isCritical() { return true; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } }
3,010
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetDescriptionCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetDescriptionCommand.java
/* * SetDescriptionCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.core.Document; import megan.core.SampleAttributeTable; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 1.2015 */ public class SetDescriptionCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Description..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Edit or show the description of the data"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("Command16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set description="); String description = np.getWordRespectCase(); np.matchIgnoreCase(";"); getDoc().getSampleAttributeTable().put(getDoc().getSampleNames().get(0), SampleAttributeTable.DescriptionAttribute, description); getDoc().setDirty(true); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Document doc = getDoc(); if ((doc.getMeganFile().isRMA2File() || doc.getMeganFile().isRMA3File()) && !doc.getMeganFile().isReadOnly()) { Object object = doc.getSampleAttributeTable().get(doc.getSampleNames().get(0), SampleAttributeTable.DescriptionAttribute); if (object == null) object = ""; String description = JOptionPane.showInputDialog(getViewer().getFrame(), "A short description:", object); if (description != null) { description = description.replaceAll("^ +| +$|( )+", "$1"); // replace all white spaces by a single spac execute("set description='" + description + "';"); } } else { StringBuilder buf = new StringBuilder(); for (String name : doc.getSampleNames()) { Object object = doc.getSampleAttributeTable().get(name, SampleAttributeTable.DescriptionAttribute); if (object != null) { buf.append(name).append(": ").append(object).append("\n"); } } if (buf.length() > 0) { NotificationsInSwing.showInformation(getViewer().getFrame(), "Description:\n" + buf); } } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return (getDoc().getMeganFile().isRMA2File() || getDoc().getMeganFile().isRMA3File()) || (getDoc().getSampleNames().size() > 0 && getDoc().getSampleAttributeTable().get(getDoc().getSampleNames().get(0), SampleAttributeTable.DescriptionAttribute) != null); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set description=<text>;"; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,832
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListPathCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListPathCommand.java
/* * ListPathCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.graph.NodeSet; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.viewer.TaxonomyData; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.OutputStreamWriter; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; public class ListPathCommand extends CommandBase implements ICommand { public String getSyntax() { return "list paths nodes=selected [outFile=<name>];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list paths nodes=selected"); final String fileName; if (np.peekMatchIgnoreCase("outFile")) { np.matchIgnoreCase("outFile="); fileName = np.getWordFileNamePunctuation(); } else fileName = null; np.matchIgnoreCase(";"); final ViewerBase viewer = (ViewerBase) getViewer(); final Classification classification = ClassificationManager.get(viewer.getClassName(), true); final boolean isTaxonomy = (viewer.getClassName().equals(Classification.Taxonomy)); final Set<Node> nodes = new HashSet<>(); { final NodeSet selected = viewer.getSelectedNodes(); nodes.addAll(selected); for (Node v : selected) { // for a given node, add all that have same id nodes.addAll(viewer.getNodes((Integer) v.getInfo())); } } final BufferedWriter writer = new BufferedWriter(fileName == null ? new OutputStreamWriter(System.out) : new FileWriter(fileName)); int count = 0; try { for (Node v : nodes) { if (isTaxonomy) { final Integer id = (Integer) v.getInfo(); if (id != null) { final String path = TaxonomyData.getPath(id, false); if (path != null) writer.write(path + " "); else writer.write(classification.getName2IdMap().get(id) + " "); } } else { LinkedList<String> list = new LinkedList<>(); while (true) { Integer id = (Integer) v.getInfo(); if (id != null) { list.add(classification.getName2IdMap().get(id)); } if (v.getInDegree() > 0) v = v.getFirstInEdge().getSource(); else { break; } } for (Iterator<String> it = list.descendingIterator(); it.hasNext(); ) { writer.write(it.next() + "; "); } } final NodeData data = viewer.getNodeData(v); if (data != null) { final float[] summarized; if (data.getSummarized() != null) summarized = data.getSummarized(); else summarized = data.getAssigned(); if (summarized != null && summarized.length >= 1) { writer.write("\t" + StringUtils.toString(summarized, ", ")); } } writer.newLine(); count++; } } finally { if (fileName != null) writer.close(); else writer.flush(); } if (fileName != null && count > 0) NotificationsInSwing.showInformation(getViewer().getFrame(), "Lines written to file: " + count); } public void actionPerformed(ActionEvent event) { executeImmediately("show window=message;"); execute("list paths nodes=selected;"); } public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0; } public String getName() { return "List Paths..."; } public String getDescription() { return "List path from root to node for all selected"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/History16.gif"); } public boolean isCritical() { return true; } }
5,652
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetRoundedCladogramCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetRoundedCladogramCommand.java
/* * SetRoundedCladogramCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw as rounded cladogram * Daniel Huson, 5.2015 */ public class SetRoundedCladogramCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return ((ViewerBase) getViewer()).getDrawerType().equals(ViewerBase.DiagramType.RoundedCladogram); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set drawer=" + ViewerBase.DiagramType.RoundedCladogram + ";"); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Rounded Cladogram"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Draw tree as rounded cladogram with all leaves positioned as right as possible"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("RoundedCladogram16.gif"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } }
2,911
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetRectangularPhylogramCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetRectangularPhylogramCommand.java
/* * SetRectangularPhylogramCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw as rectangular cladogram * Daniel Huson, 11.2010 */ public class SetRectangularPhylogramCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return ((ViewerBase) getViewer()).getDrawerType().equals(ViewerBase.DiagramType.RectangularPhylogram); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set drawer=" + ViewerBase.DiagramType.RectangularPhylogram + ";"); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Phylogram"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Draw tree as phylogram with all leaves positioned as left as possible"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("RectangularPhylogram16.gif"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } }
2,920
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetScaleBySqrtCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetScaleBySqrtCommand.java
/* * SetScaleBySqrtCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.util.ScalingType; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class SetScaleBySqrtCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer.getNodeDrawer().getScalingType() == ScalingType.SQRT; } public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("set scale=sqrt;"); } public boolean isApplicable() { return getViewer() instanceof ViewerBase; } public String getName() { return "Sqrt Scale"; } public String getDescription() { return "Show values on square-root scale"; } public ImageIcon getIcon() { return ResourceManager.getIcon("SqrtScale16.gif"); } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,194
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ToFrontCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ToFrontCommand.java
/* * ToFrontCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.util.WindowUtilities; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * bring window to front * Daniel Huson, 2.2011 */ public class ToFrontCommand extends CommandBase implements ICommand { public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("toFront"); String fileName = null; if (np.peekMatchIgnoreCase("file")) { np.matchIgnoreCase("file="); fileName = np.getWordFileNamePunctuation(); } np.matchIgnoreCase(";"); IDirectableViewer viewer = null; if (fileName == null) { viewer = getViewer(); } else { for (IDirector iDir : ProjectManager.getProjects()) { final Director dir = (Director) iDir; final String aName = dir.getDocument().getMeganFile().getFileName(); if (aName != null && aName.equals(fileName)) { viewer = dir.getMainViewer(); break; } } } if (viewer != null) { WindowUtilities.toFront(viewer.getFrame()); } else if (getParent() != null && getParent() instanceof Window) { WindowUtilities.toFront((Window) getParent()); } } public boolean isApplicable() { return getViewer() != null || (getParent() != null && getParent() instanceof Window); } public boolean isCritical() { return false; } public String getSyntax() { return "toFront [file=name];"; } public void actionPerformed(ActionEvent event) { execute(getSyntax()); } public String getName() { return "To Front"; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Bring window to front"; } }
2,964
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractReadsDialogCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ExtractReadsDialogCommand.java
/* * ExtractReadsDialogCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.Director; import megan.core.Document; import megan.data.IName2IdMap; import megan.dialogs.extractor.ReadsExtractor; import megan.viewer.TaxonomyData; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.HashSet; import java.util.Set; public class ExtractReadsDialogCommand extends CommandBase implements ICommand { public String getSyntax() { return "extract what=reads outDir=<directory> outFile=<filename-template> [data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "}][ids=<SELECTED|numbers...>]\n" + "\t[names=<names...>] [allBelow={false|true}];"; } public void apply(NexusStreamParser np) throws Exception { final Director dir = getDir(); final Document doc = dir.getDocument(); np.matchIgnoreCase("extract what=reads"); np.matchIgnoreCase("outdir="); String outDirectory = np.getWordFileNamePunctuation(); np.matchIgnoreCase("outfile="); String outFile = np.getWordFileNamePunctuation(); doc.getProgressListener().setTasks("Extracting reads", "Initialization"); doc.getProgressListener().setMaximum(-1); String cName = Classification.Taxonomy; if (np.peekMatchIgnoreCase("data")) { np.matchIgnoreCase("data="); cName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); } final ViewerBase viewer; if (cName.equals(Classification.Taxonomy)) viewer = dir.getMainViewer(); else viewer = (ViewerBase) dir.getViewerByClassName(cName); final Set<Integer> ids = new HashSet<>(); if (np.peekMatchIgnoreCase("ids=")) { np.matchIgnoreCase("ids="); if (np.peekMatchIgnoreCase("selected")) { np.matchIgnoreCase("selected"); ids.addAll(viewer.getSelectedNodeIds()); } else { while (!np.peekMatchAnyTokenIgnoreCase("names allBelow ;")) ids.add(np.getInt()); } } Set<String> names = new HashSet<>(); if (np.peekMatchIgnoreCase("names")) { np.matchIgnoreCase("names="); while (!np.peekMatchAnyTokenIgnoreCase("allBelow ;") && np.peekNextToken() != NexusStreamParser.TT_EOF) { names.add(np.getWordRespectCase()); } } boolean summary = false; if (np.peekMatchIgnoreCase("allBelow")) { np.matchIgnoreCase("allBelow="); summary = np.getBoolean(); } np.matchIgnoreCase(";"); if (names.size() > 0) { if (cName.equalsIgnoreCase(Classification.Taxonomy)) { for (String name : names) { int id = TaxonomyData.getName2IdMap().get(name); if (id != 0) ids.add(id); else System.err.println("Unrecognized name: " + name); } } else { final IName2IdMap map = ClassificationManager.get(cName, true).getName2IdMap(); for (String name : names) { int id = map.get(name); if (id != 0) ids.add(id); else System.err.println("Unrecognized name: " + name); } } } if (ids.size() == 0) { NotificationsInSwing.showWarning(viewer.getFrame(), "Nothing to extract"); return; } int count; if (cName.equalsIgnoreCase(Classification.Taxonomy)) { count = ReadsExtractor.extractReadsByTaxonomy(doc.getProgressListener(), ids, outDirectory, outFile, doc, summary); } else { count = ReadsExtractor.extractReadsByFViewer(cName, doc.getProgressListener(), ids, outDirectory, outFile, doc, true); } if (count != -1) NotificationsInSwing.showInformation(getViewer().getFrame(), "Number of reads written: " + count); } public void actionPerformed(ActionEvent event) { } public boolean isApplicable() { return getDir().getDocument().getNumberOfReads() > 0; } private final static String NAME = "Extract Reads..."; public String getName() { return NAME; } public String getDescription() { return "Extract reads for the selected nodes"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Extractor16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
5,925
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenNCBIWebPageCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/OpenNCBIWebPageCommand.java
/* * OpenNCBIWebPageCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Node; import jloda.swing.commands.ICommand; import jloda.swing.util.BasicSwing; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.net.URL; public class OpenNCBIWebPageCommand extends CommandBase implements ICommand { public String getSyntax() { return "show webpage taxon=<name|id>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("show webpage taxon="); String taxon = np.getWordRespectCase(); np.matchIgnoreCase(";"); boolean ok = false; int taxId; if (NumberUtils.isInteger(taxon)) taxId = Integer.parseInt(taxon); else taxId = TaxonomyData.getName2IdMap().get(taxon); if (taxId > 0) { try { BasicSwing.openWebPage(new URL("https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=" + taxId)); ok = true; } catch (Exception e1) { Basic.caught(e1); } } if (!ok) NotificationsInSwing.showError(getViewer().getFrame(), "Failed to open NCBI website for taxon: " + taxon); } public void actionPerformed(ActionEvent event) { ClassificationViewer viewer = (ClassificationViewer) getViewer(); int selectedTaxa = viewer.getSelectedNodes().size(); if (selectedTaxa >= 5 && JOptionPane.showConfirmDialog(viewer.getFrame(), "Do you really want to open " + selectedTaxa + " windows in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) != JOptionPane.YES_OPTION) return; boolean ok = false; for (Node v : viewer.getSelectedNodes()) { Integer taxId = (Integer) v.getInfo(); if (taxId != null && taxId > 0) { try { BasicSwing.openWebPage(new URL("https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=" + taxId)); ok = true; } catch (Exception e1) { Basic.caught(e1); } } } if (!ok) NotificationsInSwing.showError(viewer.getFrame(), "Failed to open NCBI website"); } public boolean isApplicable() { return getViewer() instanceof MainViewer && ((MainViewer) getViewer()).getSelectedNodes().size() > 0; } static final public String NAME = "Open NCBI Web Page..."; public String getName() { return NAME; } public ImageIcon getIcon() { return ResourceManager.getIcon("Ncbi16.gif"); } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } public String getDescription() { return "Open NCBI Taxonomy web site in browser"; } public boolean isCritical() { return true; } }
4,188
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PageSetupCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/PageSetupCommand.java
/* * PageSetupCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.print.PageFormat; import java.awt.print.PrinterJob; /** * page setup command * Daniel Huson, 6.2010 */ public class PageSetupCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Page Setup..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Setup the page for printing"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/PageSetup16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pageFormat = job.pageDialog(new PageFormat()); ProgramProperties.setPageFormat(pageFormat); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { executeImmediately("show window=pagesetup;"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return false; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "show window=pagesetup;"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,261
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetMaxNodeHeightCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetMaxNodeHeightCommand.java
/* * SetMaxNodeHeightCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class SetMaxNodeHeightCommand extends CommandBase implements ICommand { public String getSyntax() { return "set maxNodeHeight=<number>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set maxNodeHeight="); int radius = np.getInt(1, 1000); np.matchIgnoreCase(";"); ViewerBase viewer = (ViewerBase) getViewer(); viewer.setMaxNodeRadius(radius); if (viewer instanceof MainViewer) ((MainViewer) viewer).setDoReInduce(true); } public void actionPerformed(ActionEvent event) { String input = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter max node height in pixels", ((ClassificationViewer) getViewer()).getMaxNodeRadius()); if (input != null && NumberUtils.isInteger(input)) { execute("set maxNodeHeight=" + input + ";"); } } public boolean isApplicable() { return getViewer() instanceof ViewerBase; } public String getName() { return "Set Max Node Height..."; } public String getDescription() { return "Set the maximum node height in pixels"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
2,403
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelAssignedCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/LabelAssignedCommand.java
/* * LabelAssignedCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class LabelAssignedCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer != null && viewer.isNodeLabelAssigned(); } public void actionPerformed(ActionEvent event) { execute("nodeLabels assigned=" + (!isSelected()) + ";"); } public boolean isApplicable() { return ((Director) getDir()).getDocument().getNumberOfReads() > 0; } public String getSyntax() { return null; } public String getName() { return "Show Number of Assigned"; } public String getDescription() { return "Show the number of reads, aligned bases or bases assigned to a node"; } public KeyStroke getAcceleratorKey() { return null; } public ImageIcon getIcon() { return null; } /* * parses the given command and executes it * * @param np * @throws java.io.IOException */ @Override public void apply(NexusStreamParser np) { } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } }
2,379
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ImportBIOMCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ImportBIOMCommand.java
/* * ImportBIOMCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.FileUtils; import jloda.util.parse.NexusStreamParser; import megan.biom.biom1.BIOM1Importer; import megan.biom.biom2.Biom2Importer; import megan.core.Director; import megan.core.Document; import megan.inspector.InspectorWindow; import megan.main.MeganProperties; import megan.util.BiomFileFilter; import megan.viewer.MainViewer; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.List; public class ImportBIOMCommand extends CommandBase implements ICommand { public String getSyntax() { return "import format=biom file=<fileName> [type={TAXONOMY|KEGG|SEED|UNKNOWN}] [taxonomyIgnorePath={false|true}];"; } public void apply(NexusStreamParser np) throws Exception { final Director dir = getDir(); final MainViewer viewer = dir.getMainViewer(); final Document doc = dir.getDocument(); np.matchIgnoreCase("import format="); final String choice = np.getWordMatchesIgnoringCase("biom"); if (!choice.equalsIgnoreCase("biom")) throw new IOException("Unsupported format: " + choice); np.matchIgnoreCase("file="); final String fileName = np.getAbsoluteFileName(); final String type; if (np.peekMatchIgnoreCase("type")) { np.matchIgnoreCase("type="); type = np.getWordMatchesIgnoringCase("taxonomy kegg seed unknown"); } else type = ""; final boolean taxonomyIgnorePath; if (np.peekMatchIgnoreCase("taxonomyIgnorePath")) { np.matchIgnoreCase("taxonomyIgnorePath="); taxonomyIgnorePath = np.getBoolean(); } else taxonomyIgnorePath = false; np.matchIgnoreCase(";"); if (!ProgramProperties.isUseGUI() || doc.neverOpenedReads) { doc.neverOpenedReads = false; doc.clearReads(); if (BiomFileFilter.isBiom1File(fileName)) BIOM1Importer.apply(fileName, doc, type, taxonomyIgnorePath); else if (BiomFileFilter.isBiom2File(fileName)) Biom2Importer.apply(fileName, doc, type, taxonomyIgnorePath); if (dir.getViewerByClass(InspectorWindow.class) != null) ((InspectorWindow) dir.getViewerByClass(InspectorWindow.class)).clear(); getDir().getMainViewer().getCollapsedIds().clear(); doc.getMeganFile().setFileName(FileUtils.replaceFileSuffix(fileName, ".megan")); final String docName = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(fileName), ""); if (doc.getSampleNames().size() == 1 && !doc.getSampleNames().get(0).equals(docName)) { doc.getDataTable().changeSampleName(0, docName); } doc.processReadHits(); doc.setDirty(true); viewer.getNodeDrawer().setStyle(doc.getNumberOfSamples() > 1 ? NodeDrawer.Style.PieChart : NodeDrawer.Style.Circle); viewer.setDoReInduce(true); viewer.setDoReset(true); doc.getSampleAttributeTable().setSampleOrder(doc.getSampleNames()); } else { final Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.execute("import format=biom file='" + fileName + "'" + (!type.equals("") ? " type=" + type + "" : "") + (taxonomyIgnorePath ? " taxonomyIgnorePath=true" : "") + ";", newDir.getMainViewer().getCommandManager()); } } public void actionPerformed(ActionEvent event) { final File lastOpenFile = ProgramProperties.getFile(MeganProperties.BIOMFILE); final List<File> files = ChooseFileDialog.chooseFilesToOpen(getViewer().getFrame(), lastOpenFile, new BiomFileFilter(), new BiomFileFilter(), event, "Open BIOM file(s)"); if (files.size() > 0) { final String[] choices = new String[]{"Taxonomy", "KEGG", "SEED", "Unknown"}; final String[] taxonomyAssignmentAlgorithm = new String[]{"Match taxonomic path (more conservative)", "Match most specific node (more specific)"}; String choice = null; String algorithm = null; boolean taxonomyIgnorePath = false; final StringBuilder buf = new StringBuilder(); for (File file : files) { final boolean isBiom1File = BiomFileFilter.isBiom1File(file.getPath()); if (choice == null && isBiom1File) { choice = ProgramProperties.get("BIOMImportType", "Unknown"); choice = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose data type", "MEGAN choice", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choice); if (choice != null) ProgramProperties.put("BIOMImportType", choice); else return; // canceled } if (algorithm == null && !isBiom1File) { algorithm = ProgramProperties.get("BIOMImportTaxonomyAssignment", taxonomyAssignmentAlgorithm[0]); algorithm = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "How to map assignments to taxonomy", "MEGAN choice", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), taxonomyAssignmentAlgorithm, algorithm); if (algorithm != null) ProgramProperties.put("BIOMImportTaxonomyAssignment", algorithm); else return; // canceled if (algorithm.equals(taxonomyAssignmentAlgorithm[1])) taxonomyIgnorePath = true; } buf.append("import format=biom file='").append(file.getPath()).append("'"); if (choice != null && isBiom1File) buf.append(" type=").append(choice); if (taxonomyIgnorePath) buf.append(" taxonomyIgnorePath=true"); buf.append(";"); } execute(buf.toString()); ProgramProperties.put(MeganProperties.BIOMFILE, files.get(0).getPath()); } } public boolean isApplicable() { return getViewer() != null; } public String getName() { return "BIOM Format..."; } public String getAltName() { return "Import BIOM Format..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } public String getDescription() { return "Import samples from a table in BIOM 1.0 or BIOM 2.1 format (see http://biom-format.org)"; } public boolean isCritical() { return true; } }
7,782
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractToNewDocumentCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ExtractToNewDocumentCommand.java
/* * ExtractToNewDocumentCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import jloda.util.parse.NexusStreamParser; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.ClassificationType; import megan.core.Director; import megan.core.Document; import megan.core.MeganFile; import megan.data.ExtractToNewDocument; import megan.main.MeganProperties; import megan.rma6.ExtractToNewDocumentRMA6; import megan.util.RMAFileFilter; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * extract to new document command * Daniel Huson, 2.2011, 4.2015 */ public class ExtractToNewDocumentCommand extends CommandBase implements ICommand { public String getSyntax() { return "extract what=document file=<megan-filename> [data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "}]\n" + "\t[ids=<SELECTED|numbers...>] [includeCollapsed={true|false}];"; } public void apply(NexusStreamParser np) throws Exception { final Director srcDir = getDir(); final MainViewer mainViewer = srcDir.getMainViewer(); final Document srcDoc = srcDir.getDocument(); np.matchIgnoreCase("extract what=document"); np.matchIgnoreCase("file="); final String tarFileName = np.getAbsoluteFileName(); if (srcDir.getDocument().getMeganFile().getFileName().equals(tarFileName)) throw new IOException("Target file name equals source file name"); ProgramProperties.put("ExtractToNewFile", tarFileName); String classificationName = ClassificationType.Taxonomy.toString(); if (np.peekMatchIgnoreCase("data")) { np.matchIgnoreCase("data="); classificationName = np.getWordMatchesRespectingCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ") + " readNames"); } final Set<Integer> ids = new HashSet<>(); if (np.peekMatchIgnoreCase("ids=")) { np.matchIgnoreCase("ids="); if (np.peekMatchIgnoreCase("selected")) { np.matchIgnoreCase("selected"); if (classificationName.equals(Classification.Taxonomy)) ids.addAll(mainViewer.getSelectedNodeIds()); else if (!classificationName.equalsIgnoreCase("readNames")) { final ClassificationViewer viewer = (ClassificationViewer) srcDir.getViewerByClassName(classificationName); ids.addAll(viewer.getSelectedNodeIds()); } } else { while (!np.peekMatchAnyTokenIgnoreCase("includeCollapsed ;")) ids.add(np.getInt()); } } boolean allBelow = true; if (np.peekMatchIgnoreCase("includeCollapsed")) { np.matchIgnoreCase("includeCollapsed="); allBelow = np.getBoolean(); } np.matchIgnoreCase(";"); if (ids.size() == 0) { NotificationsInSwing.showWarning("Nothing to extract"); return; } if (allBelow) { System.err.println("Collecting all ids below selected leaves"); final Set<Integer> collapsedIds = new HashSet<>(); if (classificationName.equals(Classification.Taxonomy)) { for (Integer id : ids) { if (mainViewer.getCollapsedIds().contains(id)) collapsedIds.add(id); } ids.addAll(TaxonomyData.getTree().getAllDescendants(collapsedIds)); } else if (!classificationName.equalsIgnoreCase("readNames")) { final ClassificationViewer viewer = (ClassificationViewer) srcDir.getViewerByClassName(classificationName); if (viewer != null) { for (Integer id : ids) { if (viewer.getCollapsedIds().contains(id)) collapsedIds.add(id); } ids.addAll(viewer.getClassification().getFullTree().getAllDescendants(collapsedIds)); } } } final Director tarDir = Director.newProject(false); final Document tarDoc = tarDir.getDocument(); tarDoc.getMeganFile().setFile(tarFileName, MeganFile.Type.RMA6_FILE); boolean userCanceled = false; Single<Long> totalReadsExtracted = new Single<>(0L); try { tarDir.notifyLockInput(); tarDoc.getActiveViewers().addAll(Arrays.asList(srcDoc.getMeganFile().getConnector().getAllClassificationNames())); tarDoc.parseParameterString(srcDoc.getParameterString()); tarDoc.setBlastMode(srcDoc.getBlastMode()); tarDoc.setPairedReads(srcDoc.isPairedReads()); if (srcDoc.getMeganFile().isRMA6File()) ExtractToNewDocumentRMA6.apply(srcDoc.getMeganFile().getFileName(), classificationName, ids, tarFileName, srcDoc.getProgressListener(), totalReadsExtracted); else { ExtractToNewDocument.apply(srcDoc, classificationName, ids, tarFileName, srcDoc.getProgressListener(), totalReadsExtracted); //tarDoc.processReadHits(); } } catch (CanceledException ex) { srcDoc.getProgressListener().setUserCancelled(false); userCanceled = true; } if (totalReadsExtracted.get() == 0) { String message = "No reads extracted"; if (userCanceled) message += "\n\tUSER CANCELED"; NotificationsInSwing.showWarning(message); ProjectManager.removeProject(tarDir); ProjectManager.updateWindowMenus(); return; } String message = String.format("Extracted %,d reads to file '%s'", totalReadsExtracted.get(), tarDoc.getMeganFile().getName()); if (userCanceled) message += "\n\tUSER CANCELED, list of reads may not be complete"; NotificationsInSwing.showInformation(message); tarDoc.neverOpenedReads = false; MeganProperties.addRecentFile(tarFileName); tarDir.getDocument().getProgressListener().setSubtask("Opening new document"); if (ProgramProperties.isUseGUI()) tarDir.execute("toFront;update reprocess=true reset=true reinduce=true;toFront;", tarDir.getCommandManager()); else { srcDir.executeImmediately("close;", srcDir.getCommandManager()); tarDir.executeImmediately("toFront;update reprocess=true reset=true reinduce=true;", tarDir.getCommandManager()); } } public boolean isApplicable() { return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0 && ((ClassificationViewer) getViewer()).getDocument().getMeganFile().hasDataConnector(); } public boolean isCritical() { return true; } public void actionPerformed(ActionEvent event) { Director dir = getDir(); if (!dir.getDocument().getMeganFile().hasDataConnector()) return; String className = null; if (getViewer() instanceof ClassificationViewer) { final ClassificationViewer viewer = (ClassificationViewer) getViewer(); Collection<String> selectedLabels = viewer.getSelectedNodeLabels(false); if (selectedLabels.size() == 1) className = StringUtils.toCleanName(selectedLabels.iterator().next()); } final String name = ProjectManager.getUniqueName(FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-" + (className != null ? className : "Extracted") + ".rma")); final String directory = (new File(ProgramProperties.get("ExtractToNewFile", ""))).getParent(); File lastOpenFile = new File(directory, name); dir.notifyLockInput(); File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new RMAFileFilter(true), new RMAFileFilter(true), event, "Extract selected data to document", ".rma"); if (file != null) { final String data = (getViewer() instanceof ClassificationViewer ? getViewer().getClassName() : ClassificationType.Taxonomy.toString()); execute("extract what=document file='" + file.getPath() + "' data=" + data + " ids=selected includeCollapsed=true;"); } else dir.notifyUnlockInput(); } public String getName() { return "Extract To New Document..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Export16.gif"); } public String getDescription() { return "Extract all reads and matches for all selected nodes to a new document"; } }
10,009
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetNumberOfReadsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetNumberOfReadsCommand.java
/* * SetNumberOfReadsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.Alert; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import megan.data.IConnector; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.IOException; public class SetNumberOfReadsCommand extends CommandBase implements ICommand { public String getSyntax() { return "set totalReads=<num>;"; } public void apply(NexusStreamParser np) throws Exception { // todo: fix so that number of reads can also be set for megan summary file np.matchIgnoreCase("set totalReads="); int num = np.getInt(1, Integer.MAX_VALUE); np.matchRespectCase(";"); if (getDoc().getMeganFile().isReadOnly()) throw new IOException("Can't set number of reads, file is read-only"); if (!(getDoc().getMeganFile().hasDataConnector() || getDoc().getMeganFile().isMeganSummaryFile() && getDoc().getNumberOfSamples() == 1)) throw new IOException("Can't set number of reads, wrong kind of file"); if (getDoc().getMeganFile().hasDataConnector() || getDoc().getMeganFile().isMeganSummaryFile() && getDoc().getNumberOfSamples() == 1) { if (num != getDoc().getNumberOfReads()) { if (num > getDoc().getNumberOfReads()) getDoc().setAdditionalReads(num - getDoc().getNumberOfReads()); else getDoc().setAdditionalReads(0); getDoc().processReadHits(); getDir().getMainViewer().setDoReInduce(true); } } } public void actionPerformed(ActionEvent event) { String str = JOptionPane.showInputDialog(getViewer().getFrame(), "Total number of reads:", getDoc().getNumberOfReads()); if (str != null) { long numberOfReads = getDoc().getNumberOfReads(); try { numberOfReads = Integer.parseInt(str); } catch (Exception ex) { new Alert(getViewer().getFrame(), "Number expected, got: " + str); } if (numberOfReads != getDoc().getNumberOfReads()) { if (getDoc().getMeganFile().hasDataConnector()) { int numberOfMatches = 0; try { IConnector connector = getDoc().getConnector(); numberOfMatches = connector.getNumberOfMatches(); } catch (IOException e) { Basic.caught(e); } if (numberOfMatches > 10000000) { int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), String.format("This sample contains %,d matches, processing may take a long time, proceed?", numberOfMatches), "Very large dataset, proceed?", JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) return; } } execute("set totalReads=" + numberOfReads + ";"); } } } public boolean isApplicable() { return getViewer() instanceof MainViewer && !getDoc().getMeganFile().isReadOnly() && (getDoc().getMeganFile().hasDataConnector() || getDoc().getMeganFile().isMeganSummaryFile() && getDoc().getNumberOfSamples() == 1); } public String getName() { return "Set Number Of Reads..."; } public String getDescription() { return "Set the total number of reads in the analysis (will initiate recalculation of all classifications)"; } public KeyStroke getAcceleratorKey() { return null; } public boolean isCritical() { return true; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } }
4,817
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HideLabelsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/HideLabelsCommand.java
/* * HideLabelsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.NodeSet; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class HideLabelsCommand extends CommandBase implements ICommand { public String getSyntax() { return "hide labels=selected;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ViewerBase viewer = (ViewerBase) getViewer(); NodeSet selected = viewer.getSelectedNodes(); if (selected.size() == 0) { viewer.showNodeLabels(false); } else viewer.showLabels(selected, false); viewer.repaint(); } public void actionPerformed(ActionEvent event) { execute(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "Node Labels Off"; } public String getDescription() { return "Hide labels for selected nodes"; } public boolean isCritical() { return true; } public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,237
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScrollToSelectionCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ScrollToSelectionCommand.java
/* * ScrollToSelectionCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * scroll to a specific node * Daniel Huson, 8.2011 */ public class ScrollToSelectionCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Scroll To Selected"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Scroll to a selected node"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("ZoomToSelection16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() > 0; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("scrollTo node=selected;"); } }
2,931
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowReferenceManualCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ShowReferenceManualCommand.java
/* * ShowReferenceManualCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.BasicSwing; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.net.URL; /** * go to reference manual * Daniel Huson, 6.2010 */ public class ShowReferenceManualCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { try { BasicSwing.openWebPage(new URL("http://ab.inf.uni-tuebingen.de/data/software/megan6/download/manual.pdf")); } catch (Exception e1) { Basic.caught(e1); } } public boolean isApplicable() { return true; } public String getName() { return "Reference Manual..."; } public String getDescription() { return "Open the reference manual in your web browser"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/WebComponent16.gif"); } public boolean isCritical() { return false; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,224
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowScaleBoxCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ShowScaleBoxCommand.java
/* * ShowScaleBoxCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import megan.viewer.ClassificationViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * show scale bar command * Daniel Huson, 2.2020 */ public class ShowScaleBoxCommand extends CommandBase implements ICheckBoxCommand { public String getSyntax() { return "show scaleBox={true|false};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("show scaleBox="); final boolean show = np.getBoolean(); np.matchIgnoreCase(";"); ViewerBase viewer = (ViewerBase) getViewer(); if (viewer instanceof ClassificationViewer) { ((ClassificationViewer) viewer).setShowScaleBox(show); ProgramProperties.put("ShowScaleBox", show); viewer.repaint(); } } @Override public boolean isSelected() { return getViewer() instanceof ClassificationViewer && ((ClassificationViewer)getViewer()).isShowScaleBox(); } public void actionPerformed(ActionEvent event) { execute("show scaleBox="+(!isSelected())+";"); } public boolean isApplicable() { return getViewer() instanceof ClassificationViewer; } public String getName() { return "Show Scale Bar"; } public String getDescription() { return "Show scale bar"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,678
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
EnableFeatureCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/EnableFeatureCommand.java
/* * EnableFeatureCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * enable feature command * Daniel Huson, 11.2017 */ public class EnableFeatureCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Enable Software Feature..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Enable an experimental feature"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { var feature = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter feature:", ""); if (feature != null) { feature = feature.trim().split("\\s+")[0]; var enable=true; if (feature.startsWith("!")) { enable = false; feature=feature.substring(1); } if(!feature.startsWith("enable-")) feature="enable-"+feature; execute("setprop " + feature + "="+enable+";"); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,383
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UpdateCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/UpdateCommand.java
/* * UpdateCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.util.parse.NexusStreamParser; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * rescan some of the computation */ public class UpdateCommand extends CommandBase implements ICommand { public String getSyntax() { return "update [reProcess={false|true}] [reset={false|true}] [reInduce={false|true}];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("update"); IDirectableViewer viewer = getViewer(); boolean reInduce = np.peekMatchIgnoreCase(";"); // if nothing specified, assume reinduce requested boolean reprocess = false; if (np.peekMatchIgnoreCase("reProcess")) // reprocess all hits { np.matchIgnoreCase("reProcess="); reprocess = np.getBoolean(); } boolean reset = false; if (np.peekMatchIgnoreCase("reset")) // result the tree { np.matchIgnoreCase("reset="); reset = np.getBoolean(); } if (np.peekMatchIgnoreCase("reInduce")) // reinduce the tree { np.matchIgnoreCase("reInduce="); reInduce = np.getBoolean(); } np.matchIgnoreCase(";"); if (viewer instanceof MainViewer) { if (reprocess) { getDoc().processReadHits(); } ((MainViewer) viewer).setDoReset(reset); ((MainViewer) viewer).setDoReInduce(reInduce); if (reInduce) { getDoc().setLastRecomputeTime(System.currentTimeMillis()); } } viewer.updateView(IDirector.ALL); } public void actionPerformed(ActionEvent event) { executeImmediately("update reprocess=true reset=true reInduce=true;"); } public boolean isApplicable() { return true; } public String getName() { return "Update"; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Update data"; } public boolean isCritical() { return true; } }
3,096
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListVersionCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListVersionCommand.java
/* * ListVersionCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; public class ListVersionCommand extends CommandBase implements ICommand { public String getSyntax() { return "version;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); System.err.println(ProgramProperties.getProgramName()); } public void actionPerformed(ActionEvent event) { executeImmediately("show window=message;"); executeImmediately(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "Version..."; } public String getDescription() { return "Show version info"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/About16.gif"); } public boolean isCritical() { return false; } }
1,905
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CompareGroupsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/CompareGroupsCommand.java
/* * CompareGroupsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.seq.BlastMode; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.util.ProgramProperties; import jloda.util.FileUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.commands.algorithms.ComputeCoreOrRareBiome; import megan.core.Director; import megan.core.Document; import megan.core.MeganFile; import megan.dialogs.compare.Comparer; import megan.main.MeganProperties; import megan.viewer.MainViewer; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.*; /** * compute comparison of groups * Daniel Huson, 7.2015 */ public class CompareGroupsCommand extends jloda.swing.commands.CommandBase implements ICommand { public void apply(NexusStreamParser np) throws Exception { final Document doc = ((Director) getDir()).getDocument(); final List<Pair<String, List<String>>> groups = new ArrayList<>(); final Set<String> nameSet = new HashSet<>(); final Set<String> sampleSet = new HashSet<>(); // parse command: String mode = Comparer.COMPARISON_MODE.ABSOLUTE.toString(); boolean ignoreUnassigned = false; String title = "Untitled"; { np.matchIgnoreCase("compare"); while (!np.peekMatchIgnoreCase(";")) { if (np.peekMatchIgnoreCase("title")) { np.matchIgnoreCase("title="); title = np.getWordRespectCase(); } np.matchIgnoreCase("name="); final Pair<String, List<String>> group = new Pair<>(); final String name = np.getWordRespectCase(); if (nameSet.contains(name)) throw new IOException("Name used multiple times: " + name); else nameSet.add(name); group.setFirst(name); final ArrayList<String> samples = new ArrayList<>(); group.setSecond(samples); if (np.peekMatchIgnoreCase("samples")) { np.matchIgnoreCase("samples="); while (!np.peekMatchAnyTokenIgnoreCase("name comparisonMode ignoreUnassigned;")) { final String sample = np.getWordRespectCase(); if (sampleSet.contains(sample)) throw new IOException("Sample used multiple times: " + sample); else sampleSet.add(sample); if (!doc.getSampleNames().contains(sample)) throw new IOException("Unknown sample: " + sample); if (sample.equalsIgnoreCase("samples") || sample.equals("=")) throw new IOException("Illegal sample name: '" + sample + "'"); samples.add(sample); } } if (group.getSecond().size() > 0) groups.add(group); else System.err.println("Ignored empty group: " + group.getFirst()); } if (np.peekMatchIgnoreCase("mode")) { np.matchIgnoreCase("mode="); mode = np.getWordMatchesRespectingCase(StringUtils.toString(Comparer.COMPARISON_MODE.values(), " ")); } if (np.peekMatchIgnoreCase("ignoreUnassigned")) { np.matchIgnoreCase("ignoreUnassigned="); ignoreUnassigned = np.getBoolean(); } np.matchIgnoreCase(";"); } if (groups.size() == 0) { System.err.println("No groups to compare"); return; } System.err.println("Number of groups to compare: " + groups.size()); System.err.println("Number of samples to compare: " + sampleSet.size()); final Comparer comparer = new Comparer(); comparer.setMode(mode); comparer.setIgnoreUnassigned(ignoreUnassigned); // build document for each sample: { for (Pair<String, List<String>> group : groups) { final Map<String, Map<Integer, float[]>> classification2class2counts = new HashMap<>(); int sampleSize = ComputeCoreOrRareBiome.apply(doc, group.getSecond(), false, 0, 0, classification2class2counts, doc.getProgressListener()); final Director tmpDir = Director.newProject(false); final Document tmpDocument = tmpDir.getDocument(); final MainViewer tmpViewer = tmpDir.getMainViewer(); if (classification2class2counts.size() > 0) { tmpDocument.addSample(group.getFirst(), sampleSize, 0, BlastMode.Unknown, classification2class2counts); tmpDocument.setNumberReads(tmpDocument.getDataTable().getTotalReads()); String fileName = group.getFirst() + ".megan"; tmpDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE); System.err.println("Number of reads: " + tmpDocument.getNumberOfReads()); tmpDocument.processReadHits(); tmpDocument.setTopPercent(100); tmpDocument.setMinScore(0); tmpDocument.setMaxExpected(10000); tmpDocument.setMinSupport(1); tmpDocument.setDirty(true); for (String classificationName : tmpDocument.getDataTable().getClassification2Class2Counts().keySet()) { tmpDocument.getActiveViewers().add(classificationName); } tmpDocument.getSampleAttributeTable().addTable(doc.getSampleAttributeTable().mergeSamples(group.getSecond(), tmpDocument.getSampleNames().get(0)), false, true); tmpDocument.processReadHits(); tmpViewer.setDoReset(true); tmpViewer.setDoReInduce(true); tmpDocument.setLastRecomputeTime(System.currentTimeMillis()); tmpViewer.updateView(IDirector.ALL); } comparer.addDirector(tmpDir); } } // make comparer: { final Director newDir = Director.newProject(); final MainViewer newViewer = newDir.getMainViewer(); newViewer.getFrame().setVisible(true); newViewer.setDoReInduce(true); newViewer.setDoReset(true); final Document newDocument = newDir.getDocument(); final String fileName = FileUtils.replaceFileSuffix(new File(new File(doc.getMeganFile().getFileName()).getParent(), title).getPath(), ".megan"); newDocument.getMeganFile().setFile(fileName, MeganFile.Type.MEGAN_SUMMARY_FILE); newDocument.setReadAssignmentMode(doc.getReadAssignmentMode()); comparer.computeComparison(newDocument.getSampleAttributeTable(), newDocument.getDataTable(), doc.getProgressListener()); newDocument.processReadHits(); newDocument.setTopPercent(100); newDocument.setMinScore(0); newDocument.setMinSupportPercent(0); newDocument.setMinSupport(1); newDocument.setMaxExpected(10000); newDocument.getActiveViewers().addAll(newDocument.getDataTable().getClassification2Class2Counts().keySet()); newDocument.setDirty(true); if (newDocument.getNumberOfSamples() > 1) { newViewer.getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.BarChart); newViewer.setShowLegend("horizontal"); } newDir.execute("update reprocess=true reinduce=true;", newDir.getMainViewer().getCommandManager()); } // remove temporary directors and documents: for (Director tmpDir : comparer.getDirs()) { ProjectManager.removeProject(tmpDir); } } public boolean isApplicable() { return ((Director) getDir()).getDocument().getNumberOfSamples() > 1; } public boolean isCritical() { return true; } public String getSyntax() { return "compare title=<string> name=<string> samples=<string ...> [name=<string> samples=<string ...>] ... [comparisonMode={" + StringUtils.toString(Comparer.COMPARISON_MODE.values(), "|") + "}] [ignoreUnassigned={false|true}] ;"; } public void actionPerformed(ActionEvent event) { } public String getName() { return "Compare Groups"; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Compare some groups of samples"; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ @Override public KeyStroke getAcceleratorKey() { return null; } }
9,933
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ComputeSimpsonReciprocalIndexCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ComputeSimpsonReciprocalIndexCommand.java
/* * ComputeSimpsonReciprocalIndexCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.util.DiversityIndex; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ComputeSimpsonReciprocalIndexCommand extends CommandBase implements ICommand { public void apply(NexusStreamParser np) { } public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getNumberSelectedNodes() > 0 && getDir().getDocument().getNumberOfSamples() > 0; } public boolean isCritical() { return true; } public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { execute("compute index=" + DiversityIndex.SIMPSON_RECIPROCAL + ";"); } public String getName() { return "Simpson-Reciprocal Index..."; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Compute the Simpson-Reciprocal diversity index"; } }
1,926
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetTreeDrawerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetTreeDrawerCommand.java
/* * SetTreeDrawerCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * sets the tree drawer * Daniel Huson, 5.2015 */ public class SetTreeDrawerCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set drawer="); String drawerName = np.getWordMatchesIgnoringCase(StringUtils.toString(ViewerBase.DiagramType.values(), " ")); np.matchIgnoreCase(";"); ViewerBase viewer = (ViewerBase) getViewer(); viewer.setDrawerType(drawerName); viewer.updateTree(); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set drawer={" + StringUtils.toString(ViewerBase.DiagramType.values(), ",") + "};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { } /** * get the name to be used as a menu label * * @return name */ public String getName() { return null; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the tree drawer"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase; } }
2,932
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PrintCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/PrintCommand.java
/* * PrintCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import megan.dialogs.lrinspector.LRInspectorViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.print.Printable; import java.awt.print.PrinterJob; public class PrintCommand extends CommandBase implements ICommand { public String getSyntax() { return "show window=print;"; } public void apply(NexusStreamParser np) throws Exception { if (getViewer() instanceof LRInspectorViewer) { megan.dialogs.lrinspector.commands.PrintCommand command = new megan.dialogs.lrinspector.commands.PrintCommand(); command.setDir(getDir()); command.setViewer(getViewer()); command.setCommandManager(getCommandManager()); command.apply(np); return; } np.matchIgnoreCase(getSyntax()); PrinterJob job = PrinterJob.getPrinterJob(); if (ProgramProperties.getPageFormat() != null) job.setPrintable((Printable) getViewer(), ProgramProperties.getPageFormat()); else job.setPrintable((Printable) getViewer()); // Put up the dialog box if (job.printDialog()) { // Print the job if the user didn't cancel printing try { job.print(); } catch (Exception ex) { Basic.caught(ex); NotificationsInSwing.showError(getViewer().getFrame(), "Print failed: " + ex); } } } public void actionPerformed(ActionEvent event) { executeImmediately(getSyntax()); } public boolean isApplicable() { return getViewer() instanceof Printable; } public String getName() { return "Print..."; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK); } public String getDescription() { return "Print the main panel"; } public boolean isCritical() { return true; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Print16.gif"); } }
3,301
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenWebPageCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/OpenWebPageCommand.java
/* * OpenWebPageCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.BasicSwing; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import megan.chart.FViewerChart; import megan.chart.TaxaChart; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.net.URL; public class OpenWebPageCommand extends CommandBase implements ICommand { public String getSyntax() { return "show webpage classification=<name> id=<id>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("show webpage classification="); String name = np.getWordRespectCase(); np.matchIgnoreCase("id="); String id = np.getWordRespectCase(); np.matchIgnoreCase(";"); boolean ok = false; try { final String searchURL = ProgramProperties.get(ProgramProperties.SEARCH_URL, ProgramProperties.defaultSearchURL); final URL url = new URL(String.format(searchURL, name.trim().replaceAll(" ", "+") + "+" + id.trim().replaceAll(" ", "+"))); System.err.println(url); BasicSwing.openWebPage(url); ok = true; } catch (Exception e1) { Basic.caught(e1); } if (!ok) NotificationsInSwing.showWarning(getViewer().getFrame(), "Failed search for: " + name + "+" + id); } public void actionPerformed(ActionEvent event) { ViewerBase viewer = (ViewerBase) getViewer(); java.util.Collection<String> selectedIds = viewer.getSelectedNodeLabels(false); if (selectedIds.size() >= 5 && JOptionPane.showConfirmDialog(getViewer().getFrame(), "Do you really want to open " + selectedIds.size() + " windows in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) != JOptionPane.YES_OPTION) return; String name = ""; if (getViewer() instanceof MainViewer || getViewer() instanceof TaxaChart) name = "Taxonomy"; else if (getViewer() instanceof ClassificationViewer) { name = getViewer().getClassName(); } else if (getViewer() instanceof FViewerChart) { name = ((FViewerChart) getViewer()).getCName(); } if (name.contains("2")) name = name.substring(name.indexOf("2") + 1); boolean ok = false; for (String id : selectedIds) { try { final String searchURL = ProgramProperties.get(ProgramProperties.SEARCH_URL, ProgramProperties.defaultSearchURL); final URL url = new URL(String.format(searchURL, name.trim().replaceAll("\\s+", "+") + "+" + id.trim() .replaceAll("<", " ").replaceAll(">", " ").replaceAll("\\s+", "+"))); System.err.println(url); BasicSwing.openWebPage(url); ok = true; } catch (Exception e1) { Basic.caught(e1); } } if (!ok) NotificationsInSwing.showWarning(viewer.getFrame(), "Failed to open website"); } public boolean isApplicable() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer.getSelectedNodes().size() > 0; } public static final String NAME = "Web Search..."; public String getName() { return NAME; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/WebComponent16.gif"); } public KeyStroke getAcceleratorKey() { return null; } public String getDescription() { return "Search for selected items in browser"; } public boolean isCritical() { return true; } }
4,755
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetMarginCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetMarginCommand.java
/* * SetMarginCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class SetMarginCommand extends CommandBase implements ICommand { public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set margin"); ViewerBase viewer = getViewer() instanceof ViewerBase ? (ViewerBase) getViewer() : null; while (!(np.peekMatchIgnoreCase(";"))) { if (np.peekMatchIgnoreCase("left")) { np.matchIgnoreCase("left="); if (viewer != null) viewer.trans.setLeftMargin(np.getInt()); } else if (np.peekMatchIgnoreCase("right")) { np.matchIgnoreCase("right="); if (viewer != null) viewer.trans.setRightMargin(np.getInt()); } else if (np.peekMatchIgnoreCase("top")) { np.matchIgnoreCase("top="); if (viewer != null) viewer.trans.setTopMargin(np.getInt()); } else if (np.peekMatchIgnoreCase("bottom")) { np.matchIgnoreCase("bottom="); if (viewer != null) viewer.trans.setBottomMargin(np.getInt()); } else np.matchAnyTokenIgnoreCase("left right bottom top"); // will throw an exception } np.matchIgnoreCase(";"); if (viewer != null) System.out.println("margin: left=" + viewer.trans.getLeftMargin() + " right=" + viewer.trans.getRightMargin() + " top=" + viewer.trans.getTopMargin() + " bottom=" + viewer.trans.getBottomMargin()); if (viewer != null) viewer.fitGraphToWindow(); } public boolean isApplicable() { return getViewer() != null && getViewer() instanceof ViewerBase; } public boolean isCritical() { return true; } public String getSyntax() { return "set margin [left=<number>] [right=<number>] [bottom=<number>] [top=<number>];"; } public void actionPerformed(ActionEvent event) { if (getViewer() instanceof ViewerBase) { ViewerBase viewer = (ViewerBase) getViewer(); String input = "left=" + viewer.trans.getLeftMargin() + " right=" + viewer.trans.getRightMargin() + " top=" + viewer.trans.getTopMargin() + " bottom=" + viewer.trans.getBottomMargin(); input = JOptionPane.showInputDialog(viewer.getFrame(), "Set margin", input); if (input != null) { input = input.trim(); if (input.length() > 0 && !input.equals(";")) { if (!input.endsWith(";")) input += ";"; execute("set margin=" + input); } } } } public String getName() { return "Set Margins..."; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Set margins used in tree visualization"; } }
3,992
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CloseCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/CloseCommand.java
/* * CloseCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.graphview.GraphView; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.CanceledException; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; /** * close the window * Daniel Huson, 6.2010 */ public class CloseCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return NAME; } public static final String NAME = "Close"; /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Close window"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("Close16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("close"); final String what; if (np.peekMatchAnyTokenIgnoreCase("what")) { np.matchIgnoreCase("what="); what = np.getWordMatchesIgnoringCase("current others"); } else what = "current"; np.matchIgnoreCase(";"); if (what.equalsIgnoreCase("current")) { if (getViewer() instanceof MainViewer) { if (getViewer().isLocked()) { if (ProgramProperties.isUseGUI()) { int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), "Process running, close anyway?", "Close?", JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) return; } else { System.err.println("Internal error: process running, close request ignored"); return; // todo: could cause problems } } if (ProjectManager.getNumberOfProjects() == 1) executeImmediately("quit;"); else { try { if (getDir().getDocument().getProgressListener() != null) getDir().getDocument().getProgressListener().setUserCancelled(true); getDir().close(); } catch (CanceledException ex) { //Basic.caught(ex); } } } else if (getViewer() != null) { getViewer().destroyView(); } else if (getParent() instanceof GraphView) { ((GraphView) getParent()).getFrame().setVisible(false); } } else if (what.equalsIgnoreCase("others")) { final ArrayList<IDirector> projects = new ArrayList<>(ProjectManager.getProjects()); for (IDirector aDir : projects) { if (aDir == getDir()) { for (IDirectableViewer viewer : ((Director) aDir).getViewers()) { if (!(viewer instanceof MainViewer) && viewer != getViewer()) { viewer.destroyView(); } } } else if (ProjectManager.getProjects().contains(aDir) && !((Director) aDir).isLocked()) { int numberOfProjects = ProjectManager.getNumberOfProjects(); aDir.executeImmediately("close;", ((Director) aDir).getCommandManager()); if (numberOfProjects == ProjectManager.getNumberOfProjects()) { System.err.println("(Failed to close window, canceled?)"); break; } } } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { executeImmediately("close what=current;"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return false; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "close [what={current|others};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
6,234
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ImportCSVCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ImportCSVCommand.java
/* * ImportCSVCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.util.TextFileFilter; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.core.Director; import megan.core.Document; import megan.core.MeganFile; import megan.dialogs.importcsv.ImportCSVWindow; import megan.dialogs.parameters.ParametersDialogSmall; import megan.inspector.InspectorWindow; import megan.main.MeganProperties; import megan.parsers.CSVReadsHitsParser; import megan.parsers.CSVSummaryParser; import megan.viewer.MainViewer; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.util.LinkedList; import java.util.List; public class ImportCSVCommand extends CommandBase implements ICommand { public String getSyntax() { return "import csv={reads|summary} separator={comma|tab} file=<fileName> fNames={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + ",...} [topPercent=<num>] [minScore=<num>] [minSupportPercent=<num>] [minSupport=<num>] [multiplier=<number>];"; } public void apply(NexusStreamParser np) throws Exception { final Director dir = getDir(); final MainViewer viewer = dir.getMainViewer(); final Document doc = dir.getDocument(); np.matchIgnoreCase("import csv="); String choice = np.getWordMatchesIgnoringCase("reads summary"); boolean tabSeparator = false; if (np.peekMatchIgnoreCase("separator")) { np.matchIgnoreCase("separator="); if (np.getWordMatchesIgnoringCase("comma tab").equals("tab")) tabSeparator = true; } np.matchIgnoreCase("file="); final String fileName = np.getAbsoluteFileName(); final List<String> cNames = new LinkedList<>(); np.matchIgnoreCase("fNames="); while (!np.peekMatchIgnoreCase(";")) { String cName = np.getWordRespectCase(); if (ClassificationManager.getAllSupportedClassifications().contains(cName)) { cNames.add(cName); } else { np.pushBack(); break; } } if (choice.equalsIgnoreCase("reads")) { float topPercent = -1; float minScore = -1; int minSupport = -1; float minSupportPercent = -1; float minComplexity = -1; if (np.peekMatchIgnoreCase("topPercent")) { np.matchIgnoreCase("topPercent="); topPercent = (float) np.getDouble(); } if (np.peekMatchIgnoreCase("minScore")) { np.matchIgnoreCase("minScore="); minScore = (float) np.getDouble(); } if (np.peekMatchIgnoreCase("minSupportPercent")) { np.matchIgnoreCase("minSupportPercent="); minSupportPercent = (float) np.getDouble(0, 100); } if (np.peekMatchIgnoreCase("minSupport")) { np.matchIgnoreCase("minSupport="); minSupport = np.getInt(); } np.matchIgnoreCase(";"); if (!ProgramProperties.isUseGUI() || doc.neverOpenedReads) { doc.neverOpenedReads = false; doc.clearReads(); if (topPercent != -1) doc.setTopPercent(topPercent); if (minScore != -1) doc.setMinScore(minScore); if (minSupportPercent != -1) doc.setMinSupportPercent(minSupportPercent); if (minSupport != -1) doc.setMinSupport(minSupport); CSVReadsHitsParser.apply(fileName, doc, cNames.toArray(new String[0]), tabSeparator); if (dir.getViewerByClass(InspectorWindow.class) != null) ((InspectorWindow) dir.getViewerByClass(InspectorWindow.class)).clear(); viewer.collapseToDefault(); doc.getMeganFile().setFileName(FileUtils.replaceFileSuffix(fileName, ".megan")); doc.getMeganFile().setFileType(MeganFile.Type.MEGAN_SUMMARY_FILE); doc.getActiveViewers().clear(); doc.getActiveViewers().addAll(cNames); doc.processReadHits(); if (doc.getNumberOfReads() > 0) doc.setDirty(true); viewer.getNodeDrawer().setStyle(doc.getNumberOfSamples() > 1 ? NodeDrawer.Style.PieChart : NodeDrawer.Style.Circle); viewer.setDoReInduce(true); viewer.setDoReset(true); dir.executeImmediately("update;", viewer.getCommandManager()); NotificationsInSwing.showInformation(String.format("Imported %,d reads from file '%s'", +doc.getNumberOfReads(), fileName)); } else { Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.execute("import csv=reads separator=" + (tabSeparator ? "tab" : "comma") + " file='" + fileName + "' fNames=" + StringUtils.toString(cNames, " ") + " topPercent=" + topPercent + " minScore=" + minScore + " minSupportPercent=" + minSupportPercent + " minSupport=" + minSupport + ";", newDir.getMainViewer().getCommandManager()); } } else // csv-summary { long multiplier = 1; if (np.peekMatchIgnoreCase("multiplier")) { np.matchIgnoreCase("multiplier="); multiplier = np.getInt(1, Integer.MAX_VALUE); } np.matchIgnoreCase(";"); if (!ProgramProperties.isUseGUI() || doc.neverOpenedReads) { doc.neverOpenedReads = false; doc.clearReads(); CSVSummaryParser.apply(fileName, doc, cNames.toArray(new String[0]), tabSeparator, multiplier); if (dir.getViewerByClass(InspectorWindow.class) != null) ((InspectorWindow) dir.getViewerByClass(InspectorWindow.class)).clear(); viewer.collapseToDefault(); doc.getMeganFile().setFileName(FileUtils.getFileBaseName(fileName) + ".megan"); doc.getMeganFile().setFileType(MeganFile.Type.MEGAN_SUMMARY_FILE); if (doc.getNumberOfReads() > 0) doc.setDirty(true); if (doc.getNumberOfSamples() > 1) viewer.getNodeDrawer().setStyle(ProgramProperties.get(MeganProperties.COMPARISON_STYLE, ""), NodeDrawer.Style.PieChart); viewer.setDoReInduce(true); viewer.setDoReset(true); dir.executeImmediately("update;", viewer.getCommandManager()); NotificationsInSwing.showInformation(String.format("Imported %,d reads from file '%s'", +doc.getNumberOfReads(), fileName)); } else { Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.executeImmediately("import csv=summary separator=" + (tabSeparator ? "tab" : "comma") + " file='" + fileName + "' fNames=" + StringUtils.toString(cNames, " ") + (multiplier != 1 ? " multiplier=" + multiplier : "") + ";", newDir.getMainViewer().getCommandManager()); } } } public void actionPerformed(ActionEvent event) { File lastOpenFile = ProgramProperties.getFile(MeganProperties.CSVFILE); List<File> files = ChooseFileDialog.chooseFilesToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter("csv", "tsv", "csv", "tab"), new TextFileFilter("csv", "tsv", "csv", "tab"), event, "Open CSV file"); if (files.size() > 0) { File file = files.get(0); ImportCSVWindow importCSVWindow = new ImportCSVWindow(getViewer(), getDir()); importCSVWindow.setTabSeparator(CSVSummaryParser.guessTabSeparator(file)); importCSVWindow.setDoReadsHits(CSVSummaryParser.getTokensPerLine(file, importCSVWindow.isTabSeparator() ? "\t" : ",") == 3); if (importCSVWindow.apply()) { String template; if (importCSVWindow.isDoReadsHits()) { ParametersDialogSmall dialog = new ParametersDialogSmall(getViewer().getFrame(), getDir()); if (!dialog.isOk()) return; float topPercent = (float) dialog.getTopPercent(); float minScore = (float) dialog.getMinScore(); int minSupport = dialog.getMinSupport(); float minSupportPercent = dialog.getMinSupportPercent(); template = ("import csv=reads separator=" + (importCSVWindow.isTabSeparator() ? "tab" : "comma") + " file='XXXXXXXX' fNames=" + StringUtils.toString(importCSVWindow.getSelectedCNames(), " ") + " topPercent=" + topPercent + " minScore=" + minScore + " minSupportPercent=" + minSupportPercent + " minSupport=" + minSupport + ";\n"); } else { template = ("import csv=summary separator=" + (importCSVWindow.isTabSeparator() ? "tab" : "comma") + " file='XXXXXXXX' fNames=" + StringUtils.toString(importCSVWindow.getSelectedCNames(), " ") + (importCSVWindow.getMultiplier() != 1 ? " multiplier=" + importCSVWindow.getMultiplier() : "") + ";\n"); } StringBuilder buf = new StringBuilder(); for (File aFile : files) { String cName = StringUtils.protectBackSlashes(aFile.getPath()); buf.append(template.replaceAll("XXXXXXXX", cName)); } execute(buf.toString()); } ProgramProperties.put(MeganProperties.CSVFILE, file.getPath()); } } public boolean isApplicable() { return getViewer() != null; } public String getName() { return "Text (CSV) Format..."; } public String getAltName() { return "Import Text (CSV) Format..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } public String getDescription() { return "Load data in CSV (comma- or tab-separated value) format: READ_NAME,CLASS-NAME,SCORE or CLASS,COUNT(,COUNT...)"; } public boolean isCritical() { return true; } }
11,693
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenFileCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/OpenFileCommand.java
/* * OpenFileCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ProgressDialog; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.parse.NexusStreamParser; import megan.core.ClassificationType; import megan.core.Director; import megan.core.MeganFile; import megan.main.MeganProperties; import megan.util.MeganAndRMAFileFilter; import megan.util.MeganizedDAAFileFilter; import megan.viewer.SyncDataTableAndTaxonomy; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.util.Collection; /** * the open file command * Daniel Huson, 6.2010 */ public class OpenFileCommand extends CommandBase implements ICommand { private static long timeOfLastOpen = 0; /** * constructor */ public OpenFileCommand() { } /** * constructor * */ public OpenFileCommand(IDirector dir) { setDir(dir); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "open file=<filename> [readOnly={false|true}];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { final var dir = getDir(); final var doc = dir.getDocument(); final var viewer = dir.getMainViewer(); np.matchIgnoreCase("open file="); var fileName = np.getAbsoluteFileName(); if (fileName.contains("'")) NotificationsInSwing.showWarning(viewer.getFrame(), "File name or path contains a single quote ', this will cause problems, please change!"); var readOnly = false; if (np.peekMatchIgnoreCase("readOnly=")) { np.matchIgnoreCase("readOnly="); readOnly = np.getBoolean(); } np.matchIgnoreCase(";"); if (ProgramProperties.isUseGUI() && (doc.getNumberOfSamples() > 0 || !doc.neverOpenedReads || doc.isDirty())) { final var newDir = Director.newProject(); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.getMainViewer().getFrame().requestFocus(); // todo: recently added in an attempt to fix problem that window opens behind old one newDir.execute("open file='"+fileName+"' readOnly="+readOnly+";", newDir.getMainViewer().getCommandManager()); } else { try { SwingUtilities.invokeLater(() -> viewer.getFrame().toFront()); doc.closeConnector(); // close connector if it open doc.setDirty(false); final var meganFile = doc.getMeganFile(); meganFile.setFileFromExistingFile(fileName, readOnly); meganFile.checkFileOkToRead(); // will throw IOException if there is a problem if (meganFile.isMeganServerFile() || meganFile.hasDataConnector()) { if (meganFile.isMeganServerFile()) meganFile.setReadOnly(true); if (!meganFile.isReadOnly() && !meganFile.isMeganSummaryFile() && MeganFile.isUIdContainedInSetOfOpenFiles(meganFile.getName(), meganFile.getConnector().getUId())) { NotificationsInSwing.showWarning(viewer.getFrame(), "File already open: " + meganFile.getFileName() + "\nWill open read-only"); meganFile.setReadOnly(true); } } doc.getProgressListener().setMaximum(-1); doc.getProgressListener().setProgress(-1); if (doc.getProgressListener() instanceof ProgressDialog) { doc.getProgressListener().setTasks("Opening file", meganFile.getName()); ((ProgressDialog) doc.getProgressListener()).show(); } viewer.getCollapsedIds().clear(); doc.loadMeganFile(); // note that megan3 summary and comparison files get converted to megan4 files here if (meganFile.isMeganSummaryFile()) { SyncDataTableAndTaxonomy.syncCollapsedFromSummaryToTaxonomyViewer(doc.getDataTable(), viewer); if (doc.getDataTable().getTotalReads() > 0) { doc.setNumberReads(doc.getDataTable().getTotalReads()); if (doc.getDataTable().getNumberOfSamples() == 1) { viewer.getNodeDrawer().setStyle(doc.getDataTable().getNodeStyle(ClassificationType.Taxonomy.toString()), NodeDrawer.Style.Circle); } else { viewer.getNodeDrawer().setStyle(doc.getDataTable().getNodeStyle(ClassificationType.Taxonomy.toString()), NodeDrawer.Style.PieChart); } } else { throw new IOException("File is either empty or format is too old: " + meganFile.getName()); } } else if (meganFile.hasDataConnector()) { if (doc.getDataTable().getNumberOfSamples() > 0) { SyncDataTableAndTaxonomy.syncCollapsedFromSummaryToTaxonomyViewer(doc.getDataTable(), viewer); if (doc.getDataTable().getTotalReads() > 0) { doc.setNumberReads(doc.getDataTable().getTotalReads()); } viewer.getNodeDrawer().setStyle(doc.getDataTable().getNodeStyle(ClassificationType.Taxonomy.toString()), NodeDrawer.Style.Circle); // make sure we use the correct name for the sample: doc.getDataTable().setSamples(new String[]{FileUtils.getFileBaseName(meganFile.getName())}, doc.getDataTable().getSampleUIds(), doc.getDataTable().getSampleSizes(), doc.getDataTable().getBlastModes()); } } else throw new IOException("Old MEGAN2 format, not supported by this version of MEGAN"); viewer.setDoReInduce(true); viewer.setDoReset(true); doc.neverOpenedReads = false; if (!dir.isInternalDocument()) MeganProperties.addRecentFile(meganFile.getFileName()); if (!meganFile.isMeganSummaryFile() && meganFile.hasDataConnector()) MeganFile.addUIdToSetOfOpenFiles(meganFile.getName(), meganFile.getConnector().getUId()); if (System.currentTimeMillis() - timeOfLastOpen > 5000) { NotificationsInSwing.showInformation(String.format("Opened file '%s' with %,d reads", FileUtils.getFileNameWithoutPath(fileName), doc.getNumberOfReads()), 5000); } else System.err.printf("Opened file '%s' with %,d reads%n", fileName, doc.getNumberOfReads()); timeOfLastOpen = System.currentTimeMillis(); if (!ProgramProperties.isUseGUI()) executeImmediately("update;"); } catch (Exception ex) { //NotificationsInSwing.showError(viewer.getFrame(), "Open file failed: " + ex); doc.getMeganFile().setFileName(null); if (doc.neverOpenedReads && ProjectManager.getNumberOfProjects() > 1) { System.err.println("Closing window..."); dir.close(); } throw ex; } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { var lastOpenFile = ProgramProperties.getFile(MeganProperties.MEGANFILE); var meganRmaDaaFileFilter = new MeganAndRMAFileFilter(); meganRmaDaaFileFilter.setAllowGZipped(true); meganRmaDaaFileFilter.setAllowZipped(true); meganRmaDaaFileFilter.add(MeganizedDAAFileFilter.getInstance()); getDir().notifyLockInput(); Collection<File> files; try { files = ChooseFileDialog.chooseFilesToOpen(getViewer().getFrame(), lastOpenFile, meganRmaDaaFileFilter, meganRmaDaaFileFilter, ev, "Open MEGAN file"); } finally { getDir().notifyUnlockInput(); } if (files.size() > 0) { var buf = new StringBuilder(); for (var file : files) { if (file != null && file.exists() && file.canRead()) { ProgramProperties.put(MeganProperties.MEGANFILE, file.getAbsolutePath()); buf.append("open file='").append(file.getPath()).append("';"); } } execute(buf.toString()); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Open..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open a MEGAN file (ending on .rma, .meg or .megan)"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Open16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
11,044
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NewCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/NewCommand.java
/* * NewCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * new main viewer command * Daniel Huson, 6.2010 */ public class NewCommand extends CommandBase implements ICommand { public String getSyntax() { return "new document;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); makeNewDocument(); } public static void makeNewDocument(String... commands) { final Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.execute(StringUtils.toString(commands, "; ") + ";", newDir.getMainViewer().getCommandManager()); } public void actionPerformed(ActionEvent event) { executeImmediately(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "New..."; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } public String getDescription() { return "Open a new empty document"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/New16.gif"); } public boolean isCritical() { return false; } }
2,488
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AddSampleFromFileCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/AddSampleFromFileCommand.java
/* * AddSampleFromFileCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.main.MeganProperties; import megan.samplesviewer.SamplesViewer; import megan.util.MeganAndRMAFileFilter; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * * add command * * Daniel Huson, 9.2012 */ public class AddSampleFromFileCommand extends CommandBase implements ICommand { public String getSyntax() { return "addSample [sample=<name>] source=<filename|pid> ... [overwrite={false|true}];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("addSample"); Set<Pair<String, String>> sampleAndSources = new HashSet<>(); do { String sampleName = "ALL"; if (np.peekMatchIgnoreCase("sample")) { np.matchIgnoreCase("sample="); sampleName = np.getWordRespectCase(); } np.matchIgnoreCase("source="); String source = np.getWordFileNamePunctuation(); sampleAndSources.add(new Pair<>(sampleName, source)); } while (np.peekMatchAnyTokenIgnoreCase("sample source")); boolean overwrite = false; if (np.peekMatchIgnoreCase("overwrite")) { np.matchIgnoreCase("overwrite="); overwrite = np.getBoolean(); } np.matchIgnoreCase(";"); final SamplesViewer samplesViewer = (SamplesViewer) getDir().getViewerByClass(SamplesViewer.class); if (samplesViewer != null) samplesViewer.getSamplesTableView().syncFromViewToDocument(); LinkedList<String> skipped = new LinkedList<>(); Document doc = ((Director) getDir()).getDocument(); int count = 0; for (Pair<String, String> pair : sampleAndSources) { String sampleName = pair.getFirst(); String source = pair.getSecond(); if (NumberUtils.isInteger(source)) { // is a director id Director sourceDir = (Director) ProjectManager.getProject(NumberUtils.parseInt(source)); if (sourceDir == null) throw new IOException("Document not found (pid=" + source + ")"); if (!sampleName.equalsIgnoreCase("ALL") && !sourceDir.getDocument().getSampleNames().contains(sampleName)) throw new IOException("Sample not found in document (pid=" + source + "): " + sampleName); if (sampleName.equalsIgnoreCase("ALL")) { for (String sample : sourceDir.getDocument().getSampleNames()) { if (!overwrite && doc.getSampleNames().contains(sample)) { skipped.add(sample); } else { doc.addSample(sample, sourceDir.getDocument()); count++; } } } else { if (!overwrite && doc.getSampleNames().contains(sampleName)) { skipped.add(sampleName); } else { doc.addSample(sampleName, sourceDir.getDocument()); count++; } } } else // is a file { if (!(new File(source)).isFile()) throw new IOException("File not found: " + source); Director sourceDir = Director.newProject(); try { sourceDir.executeImmediately("open file='" + source + "';update;", sourceDir.getMainViewer().getCommandManager()); if (!sampleName.equalsIgnoreCase("ALL") && !sourceDir.getDocument().getSampleNames().contains(sampleName)) throw new IOException("Sample not found in document (pid=" + source + "): " + sampleName); if (sampleName.equalsIgnoreCase("ALL")) { for (String sample : sourceDir.getDocument().getSampleNames()) { if (!overwrite && doc.getSampleNames().contains(sample)) { skipped.add(sample); } else { doc.addSample(sample, sourceDir.getDocument()); count++; } } } else { if (!overwrite && doc.getSampleNames().contains(sampleName)) { skipped.add(sampleName); } else { doc.addSample(sampleName, sourceDir.getDocument()); count++; } } } finally { sourceDir.close(); } } } if (skipped.size() > 0) { NotificationsInSwing.showWarning(getViewer().getFrame(), String.format("Skipped %d samples because their names are already present, e.g.: %s", skipped.size(), skipped.iterator().next())); } if (count > 0) { doc.setDirty(true); if (samplesViewer != null) samplesViewer.getSamplesTableView().syncFromDocumentToView(); try { doc.processReadHits(); NotificationsInSwing.showInformation(getViewer().getFrame(), String.format("Added %d reads to file '%s'", count, doc.getMeganFile().getName())); } catch (CanceledException e) { Basic.caught(e); } ((Director) getDir()).getMainViewer().setDoReInduce(true); } } public void actionPerformed(ActionEvent event) { File lastOpenFile = ProgramProperties.getFile(MeganProperties.MEGANFILE); getDir().notifyLockInput(); List<File> files = ChooseFileDialog.chooseFilesToOpen(getViewer().getFrame(), lastOpenFile, new MeganAndRMAFileFilter(), new MeganAndRMAFileFilter(), event, "Open MEGAN file to add"); getDir().notifyUnlockInput(); if (files.size() > 0) { StringBuilder command = new StringBuilder("addSample"); for (File file : files) { command.append(" source='").append(file.getPath()).append("'"); } command.append(";"); execute(command.toString()); ProgramProperties.put(MeganProperties.MEGANFILE, files.iterator().next().getAbsolutePath()); } } public boolean isApplicable() { return ((Director) getDir()).getDocument().getMeganFile().isMeganSummaryFile(); } public String getName() { return "Add From File..."; } public String getAltName() { return "Add Samples From File..."; } public String getDescription() { return "Add samples from other documents"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
8,288
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelTaxonIdsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/LabelTaxonIdsCommand.java
/* * LabelTaxonIdsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class LabelTaxonIdsCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer != null && viewer.isNodeLabelIds(); } public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { execute("nodeLabels ids=" + (!isSelected()) + ";"); } public String getName() { return "Show IDs"; } public String getDescription() { return "Display the NCBI ids of taxa"; } public KeyStroke getAcceleratorKey() { return null; } public ImageIcon getIcon() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
2,325
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UseMagnifierCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/UseMagnifierCommand.java
/* * UseMagnifierCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * command * Daniel Huson, 6.2010 */ public class UseMagnifierCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { if (getViewer() instanceof ViewerBase) { ViewerBase viewer = (ViewerBase) getViewer(); return viewer.trans.getMagnifier() != null && viewer.trans.getMagnifier().isActive(); } else return false; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Use Magnifier"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Turn the magnifier on or off"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("Magnifier16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_M, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set magnifier="); boolean state = np.getBoolean(); np.matchIgnoreCase(";"); if (getViewer() instanceof ViewerBase) { ViewerBase viewer = (ViewerBase) getViewer(); viewer.trans.getMagnifier().setInRectilinearMode(true); viewer.trans.getMagnifier().setActive(state); viewer.repaint(); } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set magnifier=" + !isSelected() + ";"); } /** * is this a critical command that can only be executed when no other * command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set magnifier={true|false};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,857
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CloseOthersCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/CloseOthersCommand.java
/* * CloseOthersCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; /** * close the window * Daniel Huson, 6.2010 */ public class CloseOthersCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return NAME; } private static final String NAME = "Close All Other Windows..."; /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Close all other windows"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("Close16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { executeImmediately("close what=others;"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return false; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ProjectManager.getNumberOfProjects() > 1 || getDir().getViewers().size() > 1; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,264
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScaleByNoneCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ScaleByNoneCommand.java
/* * ScaleByNoneCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; public class ScaleByNoneCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer != null && viewer.getNodeDrawer().getScaleBy() == NodeDrawer.ScaleBy.None; } public void apply(NexusStreamParser np) { } public boolean isApplicable() { return true; } public boolean isCritical() { return true; } public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { execute("set scaleBy=" + NodeDrawer.ScaleBy.None + ";"); } public String getName() { return "Scale Nodes By None"; } public String getDescription() { return "Don't scale nodes"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Empty16.gif"); } }
1,986
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetRectangularCladogramCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetRectangularCladogramCommand.java
/* * SetRectangularCladogramCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw as rectangular cladogram * Daniel Huson, 11.2010 */ public class SetRectangularCladogramCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return ((ViewerBase) getViewer()).getDrawerType().equals(ViewerBase.DiagramType.RectangularCladogram); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set drawer=" + ViewerBase.DiagramType.RectangularCladogram + ";"); } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Cladogram"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Draw tree as cladogram with all leaves aligned right"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("RectangularCladogram16.gif"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase; } }
2,901
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetDirectoryCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetDirectoryCommand.java
/* * SetDirectoryCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; /** * set the working directory * Daniel Huson, 1.2011 */ public class SetDirectoryCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set dir="); String result = np.getAbsoluteFileName(); np.matchIgnoreCase(";"); if (!(new File(result)).isDirectory()) { System.err.println("No such directory: " + result); } else { System.setProperty("user.dir", result); System.err.println("user.dir set to: " + result); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set dir=<directory>"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { JFrame frame = null; if (getViewer() != null) frame = getViewer().getFrame(); String result = JOptionPane.showInputDialog(frame, "Set directory:", System.getProperty("user.dir")); if (result != null && result.trim().length() > 0) { execute("set dir='" + result.trim() + "';"); } } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Directory..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the current directory"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return false; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,227
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowWebsiteCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ShowWebsiteCommand.java
/* * ShowWebsiteCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.BasicSwing; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.net.URL; /** * go to program website * Daniel Huson, 6.2010 */ public class ShowWebsiteCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { try { BasicSwing.openWebPage(new URL("http://megan.informatik.uni-tuebingen.de")); } catch (Exception e1) { Basic.caught(e1); } } public boolean isApplicable() { return true; } public String getName() { return "Community Website..."; } public String getDescription() { return "Open the community website in your web browser"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/WebComponent16.gif"); } public boolean isCritical() { return false; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,179
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ComputeMannWhitneyUCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ComputeMannWhitneyUCommand.java
/* * ComputeMannWhitneyUCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.swing.commands.ICommand; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.core.Document; import megan.viewer.ViewerBase; import org.apache.commons.math3.stat.inference.MannWhitneyUTest; import javax.swing.*; import java.awt.event.ActionEvent; public class ComputeMannWhitneyUCommand extends CommandBase implements ICommand { public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final Document doc = getDir().getDocument(); int numberSelectedNodes = ((ViewerBase) getViewer()).getNumberSelectedNodes(); MannWhitneyUTest mannWhitneyUTest = new MannWhitneyUTest(); double[] x = new double[numberSelectedNodes]; double[] y = new double[numberSelectedNodes]; ViewerBase viewer = (ViewerBase) getViewer(); int count = 0; for (Node v : viewer.getSelectedNodes()) { if (v.getOutDegree() > 0) { x[count] = ((NodeData) v.getData()).getAssigned(0); y[count] = ((NodeData) v.getData()).getAssigned(1); } else { x[count] = ((NodeData) v.getData()).getSummarized(0); y[count] = ((NodeData) v.getData()).getSummarized(1); } } double p = mannWhitneyUTest.mannWhitneyUTest(x, y); final String message = "Mann Whitney U Test for " + doc.getNumberOfSamples() + " samples based on " + numberSelectedNodes + " selected nodes:\n" + "U value=" + mannWhitneyUTest.mannWhitneyU(x, y) + "\n" + "p-value=" + (float) p + "\n"; //System.err.println(message); NotificationsInSwing.showInformation(getViewer().getFrame(), message); } public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getNumberSelectedNodes() > 0 && getDir().getDocument().getNumberOfSamples() == 2; } public boolean isCritical() { return true; } public String getSyntax() { return "compute test=MannWhitneyUTest;"; } public void actionPerformed(ActionEvent event) { if (getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getSelectedNodes().size() == 0) executeImmediately("select nodes=leaves;"); execute(getSyntax()); } public String getName() { return "Mann Whitney U Test..."; } public ImageIcon getIcon() { return null; } public String getDescription() { return "Perform the Mann Whitney U Test on comparison document containing exactly two samples"; } }
3,569
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExpandVerticalCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ExpandVerticalCommand.java
/* * ExpandVerticalCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; public class ExpandVerticalCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("expand direction=vertical;"); } public boolean isApplicable() { return true; } public String getName() { return "Expand Vertical"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ExpandVertical16.gif"); } public String getDescription() { return "Expand tree vertically"; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
1,937
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
QuitCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/QuitCommand.java
/* * QuitCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.ProjectManager; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.chart.ChartColorManager; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class QuitCommand extends CommandBase implements ICommand { public String getSyntax() { return "quit;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("quit;"); if (!ProgramProperties.isUseGUI()) // in non-gui mode, ensure that the program terminates { ChartColorManager.store(); ProgramProperties.store(); System.exit(0); } else { // todo: in non-gui mode, call the code below results in a deadlock... ProjectManager.doQuit(ChartColorManager::store, NewCommand::makeNewDocument); } } public void actionPerformed(ActionEvent event) { executeImmediately("quit;"); } public boolean isApplicable() { return true; } public String getName() { return "Quit"; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } public String getDescription() { return "Quit the program"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Stop16.gif"); } public boolean isCritical() { return false; } }
2,455
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListSummaryCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ListSummaryCommand.java
/* * ListSummaryCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.graph.NodeSet; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.CanceledException; import jloda.util.Single; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import jloda.util.progress.ProgressListener; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.core.Document; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.*; public class ListSummaryCommand extends CommandBase implements ICommand { public String getSyntax() { return "list summary nodes={all|selected} [outFile=<name>];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("list summary nodes="); String what = np.getWordMatchesIgnoringCase("all selected"); final String fileName; if (np.peekMatchIgnoreCase("outFile")) { np.matchIgnoreCase("outFile="); fileName = np.getWordFileNamePunctuation(); } else fileName = null; np.matchIgnoreCase(";"); final ViewerBase viewer = (ViewerBase) getViewer(); final Document doc = viewer.getDocument(); if (doc.getMeganFile().getFileName() == null) { throw new IOException("No input file\n"); } final Classification classification = ClassificationManager.get(getViewer().getClassName(), true); final NodeSet selectedNodes = (what.equalsIgnoreCase("selected") ? viewer.getSelectedNodes() : null); final Writer w = new BufferedWriter(fileName == null ? new OutputStreamWriter(System.out) : new FileWriter(fileName)); final Single<Integer> countLines = new Single<>(); final ProgressListener progress = doc.getProgressListener(); progress.setTasks("List", "Summary"); progress.setMaximum(viewer.getTree().getNumberOfNodes()); progress.setProgress(0); try { w.write("########## Begin of summary for file: " + doc.getMeganFile().getFileName() + "\n"); w.write("Samples: %,d%n".formatted(doc.getNumberOfSamples())); w.write("Reads total: %,d%n".formatted(doc.getNumberOfReads())); countLines.set(3); if (viewer.getTree().getRoot() != null) { w.write("Summarized at nodes:" + "\n"); countLines.set(countLines.get() + 1); listSummaryRec(viewer, classification, selectedNodes, viewer.getTree().getRoot(), 0, w, countLines, progress); } w.write("########## End of summary for file: " + doc.getMeganFile().getFileName() + "\n"); } finally { if (fileName != null) w.close(); else w.flush(); } if (fileName != null && countLines.get() > 0) NotificationsInSwing.showInformation(getViewer().getFrame(), "Lines written to file: " + countLines.get()); } /** * recursively print a summary * */ private void listSummaryRec(ViewerBase viewer, Classification classification, NodeSet selectedNodes, Node v, int indent, Writer outs, final Single<Integer> countLines, ProgressListener progress) throws IOException, CanceledException { progress.incrementProgress(); final int id = (Integer) v.getInfo(); if ((selectedNodes == null || selectedNodes.contains(v))) { final NodeData data = (viewer.getNodeData(v)); final String name = classification.getName2IdMap().get(id); if (data.getCountSummarized() > 0) { for (int i = 0; i < indent; i++) outs.write(" "); outs.write(name + ": " + StringUtils.toString("%,.0f",data.getSummarized(),0,data.getSummarized().length,",") + "\n"); countLines.set(countLines.get() + 1); } } if (viewer.getCollapsedIds().contains(id)) { return; } for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) { listSummaryRec(viewer, classification, selectedNodes, f.getOpposite(v), indent + 2, outs, countLines, progress); } } public void actionPerformed(ActionEvent event) { executeImmediately("show window=message;"); ViewerBase viewer = (ViewerBase) getViewer(); if (viewer.getSelectedNodes().isEmpty()) execute("list summary nodes=all;"); else execute("list summary nodes=selected;"); } public boolean isApplicable() { return getDoc().getNumberOfReads() > 0 && getViewer() != null && getViewer() instanceof ViewerBase; } public String getName() { return "List Summary..."; } public String getDescription() { return "List summarized counts for nodes selected of tree"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/History16.gif"); } public boolean isCritical() { return true; } }
6,035
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AddSampleFromExistingDocumentCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/AddSampleFromExistingDocumentCommand.java
/* * AddSampleFromExistingDocumentCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.HashSet; import java.util.Set; /** * * add command * * Daniel Huson, 9.2012 */ public class AddSampleFromExistingDocumentCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { Chooser chooser = new Chooser(getViewer().getFrame()); Set<String> result = chooser.getResult(); StringBuilder buf = new StringBuilder(); if (result.size() > 0) { for (String line : result) { String[] tokens = line.split("] "); if (tokens.length == 2) { int pid = Integer.parseInt(tokens[0].substring(1)); String sample = tokens[1].trim(); Director sourceDir = (Director) ProjectManager.getProject(pid); if (sourceDir != null) { Document sourceDoc = sourceDir.getDocument(); if (sourceDoc.getSampleNames().contains(sample)) { buf.append(" sample='").append(sample).append("' source=").append(pid); } } } } if (buf.toString().length() > 0) execute("add " + buf + ";"); } } public boolean isApplicable() { return ((Director) getDir()).getDocument().getMeganFile().isMeganSummaryFile(); } public String getName() { return "Add..."; } public String getAltName() { return "Add Samples From Document..."; } public String getDescription() { return "Add samples from open document"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } private int loadList(JList list) { for (IDirector iDir : ProjectManager.getProjects()) { Director sourceDir = (Director) iDir; if (sourceDir != getDir()) { Document doc = sourceDir.getDocument(); int pid = sourceDir.getID(); for (String name : doc.getSampleNames()) ((DefaultListModel) list.getModel()).addElement("[" + pid + "] " + name); } } return list.getModel().getSize(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } private class Chooser extends JDialog { private final JList list = new JList(); final Set<String> result = new HashSet<>(); Chooser(JFrame parent) { setSize(300, 400); setLocationRelativeTo(parent); setModal(true); list.setModel(new DefaultListModel()); getContentPane().setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.setBorder(BorderFactory.createEmptyBorder(2, 4, 0, 4)); getContentPane().add(mainPanel, BorderLayout.CENTER); mainPanel.add(new JLabel("Select samples to add"), BorderLayout.NORTH); mainPanel.add(new JScrollPane(list), BorderLayout.CENTER); JPanel bottom = new JPanel(); bottom.setBorder(BorderFactory.createEtchedBorder()); bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS)); bottom.add(Box.createHorizontalGlue()); JButton cancelButton = new JButton(new AbstractAction("Cancel") { public void actionPerformed(ActionEvent actionEvent) { Chooser.this.setVisible(false); } }); bottom.add(cancelButton); final JButton applyButton = new JButton(new AbstractAction("Apply") { public void actionPerformed(ActionEvent actionEvent) { for (int i : list.getSelectedIndices()) { result.add(list.getModel().getElementAt(i).toString()); } Chooser.this.setVisible(false); } }); applyButton.setEnabled(false); bottom.add(applyButton); mainPanel.add(bottom, BorderLayout.SOUTH); list.getSelectionModel().addListSelectionListener(listSelectionEvent -> applyButton.setEnabled(list.getSelectionModel().getMaxSelectionIndex() >= 0)); if (loadList(list) > 0) setVisible(true); } Set<String> getResult() { return result; } } }
6,015
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScaleByAssignedCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ScaleByAssignedCommand.java
/* * ScaleByAssignedCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import megan.viewer.gui.NodeDrawer; import javax.swing.*; import java.awt.event.ActionEvent; public class ScaleByAssignedCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return (viewer != null) && (viewer.getNodeDrawer().getScaleBy() == NodeDrawer.ScaleBy.Assigned); } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set scaleBy="); String value = np.getWordMatchesIgnoringCase(StringUtils.toString(NodeDrawer.ScaleBy.values(), " ")); np.matchIgnoreCase(";"); ViewerBase viewer = (ViewerBase) getViewer(); viewer.getNodeDrawer().setScaleBy(value); viewer.updateTree(); } public boolean isApplicable() { return true; } public boolean isCritical() { return true; } public String getSyntax() { return "set scaleBy={" + StringUtils.toString(NodeDrawer.ScaleBy.values(), "|") + "};"; } public void actionPerformed(ActionEvent event) { if (isSelected()) execute("set scaleBy=" + NodeDrawer.ScaleBy.None + ";"); else execute("set scaleBy=" + NodeDrawer.ScaleBy.Assigned + ";"); } public String getName() { return "Scale Nodes By Assigned"; } public String getDescription() { return "Scale nodes by number of reads assigned"; } public ImageIcon getIcon() { return null; } }
2,507
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CopyLegendCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/CopyLegendCommand.java
/* * CopyLegendCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IViewerWithLegend; import jloda.swing.export.TransferableGraphic; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class CopyLegendCommand extends CommandBase implements ICommand { public String getSyntax() { return "copyLegend;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); IViewerWithLegend viewer = (IViewerWithLegend) getViewer(); TransferableGraphic tg = new TransferableGraphic(viewer.getLegendPanel(), viewer.getLegendScrollPane()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(tg, tg); } public void actionPerformed(ActionEvent event) { execute(getSyntax()); } public boolean isApplicable() { return getViewer() != null && getViewer() instanceof IViewerWithLegend && !((IViewerWithLegend) getViewer()).getShowLegend().equals("none"); } public String getName() { return "Copy Legend"; } public String getDescription() { return "Copy legend image to clipboard"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Copy16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,319
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenFileFromURLCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/OpenFileFromURLCommand.java
/* * OpenFileFromURLCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; /** * command * Daniel Huson, 11.2010 */ public class OpenFileFromURLCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { String result = JOptionPane.showInputDialog((getViewer() != null ? getViewer().getFrame() : null), "Paste MeganServer file URL:"); if (result != null) { if (!result.endsWith(";")) result += ";"; result = result.replaceAll("'", ""); String[] tokens = result.split(";"); final StringBuilder buf = new StringBuilder(); int count = 0; for (String token : tokens) { final String fileName = token.trim(); if (fileName.length() > 0) buf.append("open file='").append(fileName).append("';"); count++; } if (count > 10) { if (JOptionPane.showConfirmDialog(getViewer() != null ? getViewer().getFrame() : null, "Do you really want to open " + count + " new files?", "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } execute(buf.toString()); } } public String getName() { return "Open From URL..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open file using MeganServer URL (separate multiple URLs by semicolons)"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Open16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,919
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HideIntermediateLabelsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/HideIntermediateLabelsCommand.java
/* * HideIntermediateLabelsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class HideIntermediateLabelsCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { return getViewer() != null && ((ViewerBase) getViewer()).isShowIntermediateLabels(); } public String getSyntax() { return "show intermediate=<bool>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("show intermediate="); boolean visible = np.getBoolean(); np.matchIgnoreCase(";"); ((ViewerBase) getViewer()).setShowIntermediateLabels(visible); } public void actionPerformed(ActionEvent event) { execute("show intermediate=" + (!isSelected()) + ";"); } public boolean isApplicable() { return true; } public String getName() { return "Show Intermediate Labels"; } public String getDescription() { return "Show intermediate labels at nodes of degree 2"; } public boolean isCritical() { return true; } public ImageIcon getIcon() { return ResourceManager.getIcon("Empty16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,401
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetUseMagnitudeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/SetUseMagnitudeCommand.java
/* * SetUseMagnitudeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.util.ReadMagnitudeParser; import javax.swing.*; import java.awt.event.ActionEvent; public class SetUseMagnitudeCommand extends megan.importblast.commands.CommandBase implements ICheckBoxCommand { public boolean isSelected() { return ReadMagnitudeParser.isEnabled(); } public String getSyntax() { return "set useMagnitude={true|false};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set useMagnitude="); boolean use = np.getBoolean(); np.matchIgnoreCase(";"); ReadMagnitudeParser.setEnabled(use); ProgramProperties.put("allow-read-weights", use); } public void actionPerformed(ActionEvent event) { executeImmediately("set useMagnitude=" + (!ReadMagnitudeParser.isEnabled()) + ";"); } public boolean isApplicable() { return true; } private static final String NAME = "Use Magnitudes"; public String getName() { return NAME; } public String getDescription() { return "Use reads magnitude values to weight reads, if present in their FastA header lines"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } public boolean isCritical() { return false; } public KeyStroke getAcceleratorKey() { return null; } }
2,416
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowLabelsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ShowLabelsCommand.java
/* * ShowLabelsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.NodeSet; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ShowLabelsCommand extends CommandBase implements ICommand { public String getSyntax() { return "show labels=selected;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ViewerBase viewer = (ViewerBase) getViewer(); NodeSet selected = viewer.getSelectedNodes(); if (selected.size() == 0) viewer.showNodeLabels(true); else viewer.showLabels(selected, true); viewer.repaint(); } public void actionPerformed(ActionEvent event) { execute(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "Node Labels On"; } public String getDescription() { return "Show labels for selected nodes"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } }
2,230
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ResetWindowCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ResetWindowCommand.java
/* * ResetWindowCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; public class ResetWindowCommand extends jloda.swing.commands.CommandBase implements ICommand { public String getSyntax() { return "reset windowLocation;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final IDirectableViewer viewer = getViewer(); // viewer.getFrame().setSize(1000, 1000);\ SwingUtilities.invokeLater(() -> { viewer.getFrame().setLocation(100, 100); viewer.getFrame().setVisible(true); viewer.getFrame().toFront(); }); } public void actionPerformed(ActionEvent event) { executeImmediately(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "Reset Window Location"; } public String getDescription() { return "Reset the location of a window"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } public boolean isCritical() { return false; } public KeyStroke getAcceleratorKey() { return null; } }
2,232
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganizeDAACommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/MeganizeDAACommand.java
/* * MeganizeDAACommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.CanceledException; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.classification.ClassificationManager; import megan.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.daa.Meganize; import megan.main.MeganProperties; import megan.util.ReadMagnitudeParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; /** * meganize DAA files * Daniel Huson, 3.2016 */ public class MeganizeDAACommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ public String getSyntax() { return "meganize daaFile=<name> [,<name>...] [minScore=<num>] [maxExpected=<num>] [minPercentIdentity=<num>]\n" + "\t[topPercent=<num>] [minSupportPercent=<num>] [minSupport=<num>] [lcaAlgorithm={" + StringUtils.toString(Document.LCAAlgorithm.values(), "|") + "}] [lcaCoveragePercent=<num>] [minPercentReadToCover=<num>]\n" + "\t[minComplexity=<num>] [useIdentityFilter={false|true}]\n" + "\t[fNames={" + StringUtils.toString(ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy(), "|") + "...} [longReads={false|true}] [paired={false|true} [pairSuffixLength={number}]]\n" + "\t[contaminantsFile=<filename>] [description=<text>];"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("meganize daaFile="); final ArrayList<String> daaFiles = new ArrayList<>(); daaFiles.add(np.getWordFileNamePunctuation()); while (np.peekMatchAnyTokenIgnoreCase(",")) { np.matchIgnoreCase(","); daaFiles.add(np.getWordFileNamePunctuation()); } float minScore = Document.DEFAULT_MINSCORE; if (np.peekMatchIgnoreCase("minScore")) { np.matchIgnoreCase("minScore="); minScore = (float) np.getDouble(0, Float.MAX_VALUE); } float maxExpected = Document.DEFAULT_MAXEXPECTED; if (np.peekMatchIgnoreCase("maxExpected")) { np.matchIgnoreCase("maxExpected="); maxExpected = (float) np.getDouble(0, Float.MAX_VALUE); } float minPercentIdentity = Document.DEFAULT_MIN_PERCENT_IDENTITY; if (np.peekMatchIgnoreCase("minPercentIdentity")) { np.matchIgnoreCase("minPercentIdentity="); minPercentIdentity = (float) np.getDouble(0, Float.MAX_VALUE); } float topPercent = Document.DEFAULT_TOPPERCENT; if (np.peekMatchIgnoreCase("topPercent")) { np.matchIgnoreCase("topPercent="); topPercent = (float) np.getDouble(0, 100); } float minSupportPercent = Document.DEFAULT_MINSUPPORT_PERCENT; if (np.peekMatchIgnoreCase("minSupportPercent")) { np.matchIgnoreCase("minSupportPercent="); minSupportPercent = (float) np.getDouble(0, 100); } int minSupport = Document.DEFAULT_MINSUPPORT; if (np.peekMatchIgnoreCase("minSupport")) { np.matchIgnoreCase("minSupport="); minSupport = np.getInt(0, Integer.MAX_VALUE); if (minSupport >= 1) minSupportPercent = 0; } Document.LCAAlgorithm lcaAlgorithm = Document.DEFAULT_LCA_ALGORITHM_SHORT_READS; if (np.peekMatchIgnoreCase("weightedLCA")) { np.matchIgnoreCase("weightedLCA="); if (np.getBoolean()) lcaAlgorithm = Document.LCAAlgorithm.weighted; else lcaAlgorithm = Document.LCAAlgorithm.naive; ProgramProperties.put("lcaAlgorithm", lcaAlgorithm.toString()); } else if (np.peekMatchIgnoreCase("lcaAlgorithm")) { np.matchIgnoreCase("lcaAlgorithm="); lcaAlgorithm = Document.LCAAlgorithm.valueOfIgnoreCase(np.getWordRespectCase()); } float lcaCoveragePercent = Document.DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS; if (np.peekMatchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent")) { np.matchAnyTokenIgnoreCase("lcaCoveragePercent weightedLCAPercent"); np.matchIgnoreCase("="); lcaCoveragePercent = (float) np.getDouble(1, 100); ProgramProperties.put("lcaCoveragePercent", lcaCoveragePercent); } float minPercentReadToCover = Document.DEFAULT_MIN_PERCENT_READ_TO_COVER; if (np.peekMatchIgnoreCase("minPercentReadToCover")) { np.matchIgnoreCase("minPercentReadToCover="); minPercentReadToCover = (float) np.getDouble(0, 100); ProgramProperties.put("minPercentReadToCover", minPercentReadToCover); } float minPercentReferenceToCover = Document.DEFAULT_MIN_PERCENT_REFERENCE_TO_COVER; if (np.peekMatchIgnoreCase("minPercentReferenceToCover")) { np.matchIgnoreCase("minPercentReferenceToCover="); minPercentReferenceToCover = (float) np.getDouble(0, 100); ProgramProperties.put("minPercentReferenceToCover", minPercentReferenceToCover); } float minComplexity; if (np.peekMatchIgnoreCase("minComplexity")) { np.matchIgnoreCase("minComplexity="); minComplexity = (float) np.getDouble(-1.0, 1.0); if (minComplexity > 0) System.err.println("IGNORED setting: minComplexity=" + minComplexity); } int minReadLength = 0; if (np.peekMatchIgnoreCase("minReadLength")) { np.matchIgnoreCase("minReadLength="); minReadLength = np.getInt(0, Integer.MAX_VALUE); } boolean useIdentityFilter; if (np.peekMatchIgnoreCase("useIdentityFilter")) { np.matchIgnoreCase("useIdentityFilter="); useIdentityFilter = np.getBoolean(); if (useIdentityFilter) System.err.println("IGNORED setting: useIdentityFilter=" + true); } Document.ReadAssignmentMode readAssignmentMode = Document.DEFAULT_READ_ASSIGNMENT_MODE_SHORT_READS; if (np.peekMatchIgnoreCase("readAssignmentMode")) { np.matchIgnoreCase("readAssignmentMode="); readAssignmentMode = Document.ReadAssignmentMode.valueOfIgnoreCase(np.getWordMatchesIgnoringCase(StringUtils.toString(Document.ReadAssignmentMode.values(), " "))); } final Collection<String> known = ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy(); final ArrayList<String> cNames = new ArrayList<>(); if (np.peekMatchIgnoreCase("fNames=")) { np.matchIgnoreCase("fNames="); while (!np.peekMatchIgnoreCase(";")) { String token = np.getWordRespectCase(); if (!known.contains(token)) { np.pushBack(); break; } cNames.add(token); } } final boolean longReads; if (np.peekMatchIgnoreCase("longReads")) { np.matchIgnoreCase("longReads="); longReads = np.getBoolean(); } else longReads = false; boolean pairedReads = false; int pairSuffixLength = 0; if (np.peekMatchIgnoreCase("paired")) { np.matchIgnoreCase("paired="); pairedReads = np.getBoolean(); if (pairedReads) { np.matchIgnoreCase("pairSuffixLength="); pairSuffixLength = np.getInt(0, 10); System.err.println("Assuming paired-reads distinguishing suffix has length: " + pairSuffixLength); } } final String contaminantsFile; if (np.peekMatchIgnoreCase("contaminantsFile")) { np.matchIgnoreCase("contaminantsFile="); contaminantsFile = np.getWordFileNamePunctuation().trim(); } else contaminantsFile = ""; String description = null; if (np.peekMatchIgnoreCase("description")) { np.matchIgnoreCase("description="); description = np.getWordFileNamePunctuation().trim(); } np.matchIgnoreCase(";"); ReadMagnitudeParser.setUnderScoreEnabled(ProgramProperties.get("allow-read-weights-underscore", false)); final Director dir = (Director) getDir(); final Document doc = dir.getDocument(); int countFailed = 0; for (String daaFile : daaFiles) { try { System.err.println("Meganizing file: " + daaFile); final Director openDir = findOpenDirector(daaFile); if (openDir != null) { throw new IOException("File is currently open, cannot meganize open files"); } Meganize.apply(((Director) getDir()).getDocument().getProgressListener(), daaFile, "", cNames, minScore, maxExpected, minPercentIdentity, topPercent, minSupportPercent, minSupport, pairedReads, pairSuffixLength, minReadLength,lcaAlgorithm, readAssignmentMode, lcaCoveragePercent, longReads, minPercentReadToCover, minPercentReferenceToCover, contaminantsFile); // todo: save the description { final Document tmpDoc = new Document(); tmpDoc.getMeganFile().setFileFromExistingFile(daaFile, false); tmpDoc.loadMeganFile(); ProgramProperties.put(MeganProperties.DEFAULT_PROPERTIES, tmpDoc.getParameterString()); if (description != null && description.length() > 0) { description = description.replaceAll("^ +| +$|( )+", "$1"); // replace all white spaces by a single space final String sampleName = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(tmpDoc.getMeganFile().getFileName()), ""); tmpDoc.getSampleAttributeTable().put(sampleName, SampleAttributeTable.DescriptionAttribute, description); } if (tmpDoc.getNumberOfReads() == 0) NotificationsInSwing.showWarning(getViewer().getFrame(), "No reads found"); } MeganProperties.addRecentFile(daaFile); if (ProgramProperties.isUseGUI() && daaFiles.size() == 1) { int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), "Open meganized file?", "Open?", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { if (daaFiles.size() == 1 && doc.neverOpenedReads) { dir.getDocument().clearReads(); dir.getMainViewer().setDoReInduce(true); dir.getMainViewer().setDoReset(true); dir.executeImmediately("open file='" + daaFile + "';", dir.getMainViewer().getCommandManager()); } else { final Director newDir = Director.newProject(); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); newDir.execute("open file='" + daaFile + "';", newDir.getMainViewer().getCommandManager()); } } } } catch (CanceledException ex) { throw ex; } catch (Exception ex) { NotificationsInSwing.showError(ex.getMessage()); System.err.println(ex.getMessage()); countFailed++; } } NotificationsInSwing.showInformation("Finished meganizing " + daaFiles.size() + " files" + (countFailed > 0 ? ". ERRORS: " + countFailed : ".")); } /** * get directory if this file is currently open * * @return directory */ private Director findOpenDirector(String daaFile) { final File file = new File(daaFile); if (file.isFile()) { for (IDirector dir : ProjectManager.getProjects()) { File aFile = new File(((Director) dir).getDocument().getMeganFile().getFileName()); if (aFile.isFile() && aFile.equals(file)) return (Director) dir; } } return null; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { } /** * get the name to be used as a menu label * * @return name */ public String getName() { return null; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Meganize DAA File"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
14,938
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelSummarizedCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/LabelSummarizedCommand.java
/* * LabelSummarizedCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class LabelSummarizedCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { ViewerBase viewer = (ViewerBase) getViewer(); return viewer != null && viewer.isNodeLabelSummarized(); } public String getSyntax() { return null; } public void actionPerformed(ActionEvent event) { execute("nodeLabels summarized=" + (!isSelected()) + ";"); } public boolean isApplicable() { return ((Director) getDir()).getDocument().getNumberOfReads() > 0; } public String getName() { return "Show Number of Summarized"; } public String getDescription() { return "Show the number of reads, aligned bases or bases assigned to a node or one of its descendants"; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK); } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } }
2,393
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScrollToNodeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/ScrollToNodeCommand.java
/* * ScrollToNodeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.List; /** * scroll to a specific node * Daniel Huson, 8.2011 */ public class ScrollToNodeCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Scroll To..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Scroll to a specific node"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("scrollTo node="); String name = np.getWordRespectCase(); np.matchWordIgnoreCase(";"); if (getViewer() instanceof ViewerBase) { ViewerBase viewerBase = (ViewerBase) getViewer(); if (name.equalsIgnoreCase("selected")) { List<String> labels = viewerBase.getSelectedNodeLabels(true); if (labels.size() > 0) { name = labels.get(0); } else return; } for (Node v = viewerBase.getGraph().getFirstNode(); v != null; v = v.getNext()) { String label = viewerBase.getLabel(v); if (label != null && label.equals(name)) { viewerBase.scrollToNode(v); break; } } } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "scrollTo node={<name>|selected};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof ViewerBase && ((ViewerBase) getViewer()).getGraph().getNumberOfNodes() > 0; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { String input = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter label of node to scroll to", "None"); if (input != null) { input = input.trim(); if (input.length() > 0) execute("scrollTo node='" + input + "';"); } } }
4,020
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowImportBlastCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowImportBlastCommand.java
/* * ShowImportBlastCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.show; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.importblast.ImportBlastDialog; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; /** * import blast command * Daniel Huson, 10.2010 */ public class ShowImportBlastCommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "show window=ImportBlast;"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final ImportBlastDialog dialog = new ImportBlastDialog(getViewer().getFrame(), getDir(), "Import BLAST and READs files - MEGAN"); final String command = dialog.showAndGetCommand(); if (command != null) execute(command); } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } private static final String NAME = "Import From BLAST..."; /** * get the name to be used as a menu label * * @return name */ public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show the 'Import from Blast' dialog"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Import16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,435
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowChartRareFactionCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowChartRareFactionCommand.java
/* * ShowChartRareFactionCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.show; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.util.ResourceManager; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.chart.RarefactionPlot; import megan.chart.gui.ChartViewer; import megan.classification.ClassificationManager; import megan.commands.CommandBase; import megan.core.Director; import megan.util.WindowUtilities; import megan.viewer.ClassificationViewer; import javax.swing.*; import java.awt.event.ActionEvent; public class ShowChartRareFactionCommand extends CommandBase implements ICommand { public String getSyntax() { return "show rarefaction data={" + StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), "|") + "};"; } public void apply(NexusStreamParser np) throws Exception { Director dir = getDir(); ChartViewer chartViewer; np.matchIgnoreCase("show rarefaction"); String data = "taxonomy"; if (np.peekMatchIgnoreCase("data")) { np.matchIgnoreCase("data="); data = np.getWordMatchesIgnoringCase(StringUtils.toString(ClassificationManager.getAllSupportedClassifications(), " ")); } np.matchIgnoreCase(";"); chartViewer = (RarefactionPlot) dir.getViewerByClassName(RarefactionPlot.getClassName(data)); if (chartViewer == null) { chartViewer = new RarefactionPlot(dir, (ClassificationViewer) dir.getViewerByClassName(data)); getDir().addViewer(chartViewer); } else { chartViewer.sync(); chartViewer.updateView(Director.ALL); } WindowUtilities.toFront(chartViewer); } public void actionPerformed(ActionEvent event) { IDirectableViewer viewer = getViewer(); String data; if (viewer instanceof ClassificationViewer) data = viewer.getClassName(); else return; execute("show rarefaction data=" + data + ";"); } public boolean isApplicable() { return getDir().getDocument().getNumberOfReads() > 0 && getViewer() instanceof ClassificationViewer; } public String getName() { return "Rarefaction Analysis..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("RareFaction16.gif"); } public String getDescription() { return "Compute and chart a rarefaction curve based on the leaves of the tree shown in the viewer"; } public boolean isCritical() { return true; } }
3,413
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowParametersDialogCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowParametersDialogCommand.java
/* * ShowParametersDialogCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.show; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.core.Document; import megan.dialogs.parameters.ParametersDialog; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class ShowParametersDialogCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { final ParametersDialog dialog = new ParametersDialog(getViewer().getFrame(), getDir()); if (dialog.apply()) { execute("recompute " + dialog.getParameterString() + ";"); } dialog.dispose(); } public boolean isApplicable() { Document doc = getDoc(); return !doc.getMeganFile().isReadOnly() && doc.getMeganFile().hasDataConnector() && !doc.getMeganFile().isMeganSummaryFile(); } public String getName() { return "Change LCA Parameters..."; } public String getDescription() { return "Rerun the LCA analysis with different parameters"; } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Preferences16.gif"); } }
2,418
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowAboutWindowCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/show/ShowAboutWindowCommand.java
/* * ShowAboutWindowCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.show; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.About; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ShowAboutWindowCommand extends CommandBase implements ICommand { public String getSyntax() { return "show window=about;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); About.getAbout().showAboutModal(); } public void actionPerformed(ActionEvent event) { executeImmediately(getSyntax()); } public boolean isApplicable() { return true; } public String getName() { return "About..."; } public String getDescription() { return "Display the 'about' window"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/About16.gif"); } public boolean isCritical() { return false; } }
1,887
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z